Advertisement
Guest User

Calanus

a guest
Dec 8th, 2009
2,539
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.95 KB | None | 0 0
  1. private void btnLoad_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             OpenFileDialog ofd = new OpenFileDialog();
  4.             ofd.Filter = "Excel or CSV Files|*.xls;*.xlsx;*.csv";
  5.             bool? userClickedOK = ofd.ShowDialog();
  6.             if (userClickedOK == true)
  7.             {
  8.                 //use the CSVReader to read in the data
  9.                 using (CSVReader csv = new CSVReader(ofd.File.OpenRead()))
  10.                 {
  11.                     var data = ReadInCSVData(csv);
  12.                     var Idata = ConvertToIEnumerable(data);
  13.  
  14.                     this.theGrid.ItemsSource = Idata.ToDataSource();
  15.                 }
  16.             }
  17.         }
  18.  
  19.         private IEnumerable<IDictionary> ConvertToIEnumerable(List<Dictionary<string, object>> rows)
  20.         {
  21.             foreach (var row in rows) yield return row;
  22.         }
  23.  
  24.  
  25.         private List<Dictionary<string, object>> ReadInCSVData(CSVReader csv)
  26.         {
  27.             bool firstLine = true;
  28.             List<Dictionary<string, object>> datatable = new List<Dictionary<string, object>>();
  29.             List<string> headers = new List<string>();
  30.  
  31.             try
  32.             {
  33.                 //use the csvreader to read in the csv data
  34.                 string[] fields;
  35.                 while ((fields = csv.GetCSVLine()) != null)
  36.                 {
  37.                     Dictionary<string, object> rowData = new Dictionary<string, object>();
  38.  
  39.                     if (firstLine) //the first row will always be treated as column headers
  40.                     {
  41.                         for (int i = 0; i < fields.Length; i++)
  42.                         {
  43.                             headers.Add(fields[i]);
  44.                         }
  45.  
  46.                         firstLine = false;
  47.  
  48.                         if (headers.Distinct().Count() != headers.Count) throw new Exception();
  49.                     }
  50.                     else
  51.                     {
  52.                         for (int i = 0; i < fields.Length; i++)
  53.                         {
  54.                             rowData[headers[i]] = fields[i];
  55.                         }
  56.  
  57.                         datatable.Add(rowData);
  58.  
  59.                     }
  60.  
  61.                 }
  62.  
  63.             }
  64.             //catch (DuplicateNameException)
  65.             //{
  66.             //    MessageBox.Show(
  67.             //        "Error: Two or more of the variables have the same name. Please rename the variables prior importing the data into InVivoStat.", "Load DataSet", MessageBoxButton.OK);
  68.             //    return null;
  69.             //}
  70.             catch (ArgumentException)
  71.             {
  72.                 datatable.Clear();
  73.                 MessageBox.Show("The data needs to be in either Excel or CSV format.", "Error pasting in data.", MessageBoxButton.OK);
  74.                 return null;
  75.             }
  76.  
  77.             return datatable;
  78.         }
  79.     }
  80.  
  81.     public static class DataSourceCreator
  82.     {
  83.         private static readonly Regex PropertNameRegex =
  84.                 new Regex(@"^[A-Za-z]+[A-Za-z0-9_]*$", RegexOptions.Singleline);
  85.  
  86.         private static readonly Dictionary<string, Type> _typeBySigniture =
  87.                 new Dictionary<string, Type>();
  88.  
  89.  
  90.         public static IEnumerable ToDataSource(this IEnumerable<IDictionary> list)
  91.         {
  92.             IDictionary firstDict = null;
  93.             bool hasData = false;
  94.             foreach (IDictionary currentDict in list)
  95.             {
  96.                 hasData = true;
  97.                 firstDict = currentDict;
  98.                 break;
  99.             }
  100.             if (!hasData)
  101.             {
  102.                 return new object[] { };
  103.             }
  104.             if (firstDict == null)
  105.             {
  106.                 throw new ArgumentException("IDictionary entry cannot be null");
  107.             }
  108.  
  109.             string typeSigniture = GetTypeSigniture(firstDict);
  110.  
  111.             Type objectType = GetTypeByTypeSigniture(typeSigniture);
  112.  
  113.             if (objectType == null)
  114.             {
  115.                 TypeBuilder tb = GetTypeBuilder(typeSigniture);
  116.  
  117.                 ConstructorBuilder constructor =
  118.                             tb.DefineDefaultConstructor(
  119.                                         MethodAttributes.Public |
  120.                                         MethodAttributes.SpecialName |
  121.                                         MethodAttributes.RTSpecialName);
  122.  
  123.  
  124.                 foreach (DictionaryEntry pair in firstDict)
  125.                 {
  126.                     if (PropertNameRegex.IsMatch(Convert.ToString(pair.Key), 0))
  127.                     {
  128.                         CreateProperty(tb,
  129.                                         Convert.ToString(pair.Key),
  130.                                         GetValueType(pair.Value));
  131.                     }
  132.                     else
  133.                     {
  134.                         throw new ArgumentException(
  135.                                     @"Each key of IDictionary must be
  136.                                alphanumeric and start with character.");
  137.                     }
  138.                 }
  139.                 objectType = tb.CreateType();
  140.  
  141.                 _typeBySigniture.Add(typeSigniture, objectType);
  142.             }
  143.  
  144.             return GenerateEnumerable(objectType, list, firstDict);
  145.         }
  146.  
  147.         private static Type GetTypeByTypeSigniture(string typeSigniture)
  148.         {
  149.             Type type;
  150.             return _typeBySigniture.TryGetValue(typeSigniture, out type) ? type : null;
  151.         }
  152.  
  153.         private static Type GetValueType(object value)
  154.         {
  155.             return value == null ? typeof(object) : value.GetType();
  156.         }
  157.  
  158.         private static string GetTypeSigniture(IDictionary firstDict)
  159.         {
  160.             StringBuilder sb = new StringBuilder();
  161.             foreach (DictionaryEntry pair in firstDict)
  162.             {
  163.                 sb.AppendFormat("_{0}_{1}", pair.Key, GetValueType(pair.Value));
  164.             }
  165.             return sb.ToString().GetHashCode().ToString().Replace("-", "Minus");
  166.         }
  167.  
  168.         private static IEnumerable GenerateEnumerable(
  169.                  Type objectType, IEnumerable<IDictionary> list, IDictionary firstDict)
  170.         {
  171.             var listType = typeof(List<>).MakeGenericType(new[] { objectType });
  172.             var listOfCustom = Activator.CreateInstance(listType);
  173.  
  174.             foreach (var currentDict in list)
  175.             {
  176.                 if (currentDict == null)
  177.                 {
  178.                     throw new ArgumentException("IDictionary entry cannot be null");
  179.                 }
  180.                 var row = Activator.CreateInstance(objectType);
  181.                 foreach (DictionaryEntry pair in firstDict)
  182.                 {
  183.                     if (currentDict.Contains(pair.Key))
  184.                     {
  185.                         PropertyInfo property =
  186.                             objectType.GetProperty(Convert.ToString(pair.Key));
  187.                         property.SetValue(
  188.                             row,
  189.                             Convert.ChangeType(
  190.                                     currentDict[pair.Key],
  191.                                     property.PropertyType,
  192.                                     null),
  193.                             null);
  194.                     }
  195.                 }
  196.                 listType.GetMethod("Add").Invoke(listOfCustom, new[] { row });
  197.             }
  198.             return listOfCustom as IEnumerable;
  199.         }
  200.  
  201.         private static TypeBuilder GetTypeBuilder(string typeSigniture)
  202.         {
  203.             AssemblyName an = new AssemblyName("TempAssembly" + typeSigniture);
  204.             AssemblyBuilder assemblyBuilder =
  205.                 AppDomain.CurrentDomain.DefineDynamicAssembly(
  206.                     an, AssemblyBuilderAccess.Run);
  207.             ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
  208.  
  209.             TypeBuilder tb = moduleBuilder.DefineType("TempType" + typeSigniture
  210.                                 , TypeAttributes.Public |
  211.                                 TypeAttributes.Class |
  212.                                 TypeAttributes.AutoClass |
  213.                                 TypeAttributes.AnsiClass |
  214.                                 TypeAttributes.BeforeFieldInit |
  215.                                 TypeAttributes.AutoLayout
  216.                                 , typeof(object));
  217.             return tb;
  218.         }
  219.  
  220.         private static void CreateProperty(
  221.                         TypeBuilder tb, string propertyName, Type propertyType)
  222.         {
  223.             FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName,
  224.                                                         propertyType,
  225.                                                         FieldAttributes.Private);
  226.  
  227.  
  228.             PropertyBuilder propertyBuilder =
  229.                 tb.DefineProperty(
  230.                     propertyName, PropertyAttributes.HasDefault, propertyType, null);
  231.             MethodBuilder getPropMthdBldr =
  232.                 tb.DefineMethod("get_" + propertyName,
  233.                     MethodAttributes.Public |
  234.                     MethodAttributes.SpecialName |
  235.                     MethodAttributes.HideBySig,
  236.                     propertyType, Type.EmptyTypes);
  237.  
  238.             ILGenerator getIL = getPropMthdBldr.GetILGenerator();
  239.  
  240.             getIL.Emit(OpCodes.Ldarg_0);
  241.             getIL.Emit(OpCodes.Ldfld, fieldBuilder);
  242.             getIL.Emit(OpCodes.Ret);
  243.  
  244.             MethodBuilder setPropMthdBldr =
  245.                 tb.DefineMethod("set_" + propertyName,
  246.                   MethodAttributes.Public |
  247.                   MethodAttributes.SpecialName |
  248.                   MethodAttributes.HideBySig,
  249.                   null, new Type[] { propertyType });
  250.  
  251.             ILGenerator setIL = setPropMthdBldr.GetILGenerator();
  252.  
  253.             setIL.Emit(OpCodes.Ldarg_0);
  254.             setIL.Emit(OpCodes.Ldarg_1);
  255.             setIL.Emit(OpCodes.Stfld, fieldBuilder);
  256.             setIL.Emit(OpCodes.Ret);
  257.  
  258.             propertyBuilder.SetGetMethod(getPropMthdBldr);
  259.             propertyBuilder.SetSetMethod(setPropMthdBldr);
  260.         }
  261.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement