1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
|
using System;
using System.Reflection.Emit;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace go
{
public enum BindingType
{
Handler,
DynamicHandler,
PropertyBinding
}
public class Binding{
public MemberInfo SourceMember;
public string Expression;
public PropertyInfo Property { get { return SourceMember as PropertyInfo; } }
public EventInfo Event { get { return SourceMember as EventInfo; } }
public Binding(){
}
public Binding(MemberInfo _sourceMember, string _expression)
{
SourceMember = _sourceMember;
Expression = _expression;
}
}
public class ResolvedBinding
{
public object Target;
public MemberInfo Member;
public Binding Binding;
public ResolvedBinding(){
}
public ResolvedBinding(Binding _binding){
Binding = _binding;
}
public bool FindTarget(GraphicObject source){
string member = null;
//if binding exp = '{}' => binding is done on datasource
if (string.IsNullOrEmpty (Binding.Expression)) {
Target = source;
Member = null;
return true;
}
//if (Binding.SourceMember.MemberType == MemberTypes.Event)
string[] bindingExp = Binding.Expression.Split ('/');
if (bindingExp.Length == 1) {
//datasource binding
Target = source.DataSource;
member = bindingExp [0];
} else {
int ptr = 0;
ILayoutable tmp = source;
if (string.IsNullOrEmpty (bindingExp [0])) {
//if exp start with '/' => Graphic tree parsing start at top container
tmp = source.TopContainer as ILayoutable;
ptr++;
}
while (ptr < bindingExp.Length - 1) {
if (tmp == null)
return false;
if (bindingExp [ptr] == "..")
tmp = tmp.Parent as GraphicObject;
else if (bindingExp [ptr] == ".") {
if (ptr > 0)
throw new Exception ("Syntax error in binding, './' may only appear in first position");
tmp = source;
}else
tmp = (tmp as GraphicObject).FindByName (bindingExp [ptr]);
ptr++;
}
string[] bindTrg = bindingExp [ptr].Split ('.');
if (bindTrg.Length == 1)
member = bindTrg [0];
else if (bindTrg.Length == 2){
tmp = (tmp as GraphicObject).FindByName (bindTrg [0]);
member = bindTrg [1];
} else
throw new Exception ("Syntax error in binding, expected 'go dot member'");
Target = tmp;
}
if (Target == null) {
Debug.WriteLine ("Binding Source is null: " + Binding.Expression);
return false;
}
Type targetType = Target.GetType ();
Member = targetType.GetMember (member).FirstOrDefault ();
#region search for extensions methods if member not found in type
if (Member == null && !string.IsNullOrEmpty(member))
{
Assembly a = Assembly.GetExecutingAssembly();
Member = CompilerServices.GetExtensionMethods(a, targetType).FirstOrDefault();
}
#endregion
if (member == null) {
Debug.WriteLine ("Binding member not found: " + member);
return false;
}
return true;
}
}
public static class CompilerServices2
{
static int dynHandleCpt = 0;
/// <summary>
/// Compile events expression in GOML attributes
/// </summary>
/// <param name="es">Event binding details</param>
public static void ResolveBinding(DynAttribute es)
{
Type srcType = es.Source.GetType ();
#region Retrieve EventHandler parameter type
EventInfo ei = srcType.GetEvent (es.MemberName);
MethodInfo invoke = ei.EventHandlerType.GetMethod ("Invoke");
ParameterInfo[] pars = invoke.GetParameters ();
Type handlerArgsType = pars [1].ParameterType;
#endregion
Type[] args = {typeof(object), handlerArgsType};
DynamicMethod dm = new DynamicMethod("dynHandle_" + dynHandleCpt,
typeof(void),
args,
srcType.Module);
es.Source.DynamicMethodIds.Add (dynHandleCpt);
dynHandleCpt++;
#region IL generation
ILGenerator il = dm.GetILGenerator(256);
string src = es.Value.Trim();
if (! (src.StartsWith("{") || src.EndsWith ("}")))
throw new Exception (string.Format("GOML:Malformed {0} Event handler: {1}", es.MemberName, es.Value));
src = src.Substring (1, src.Length - 2);
string[] srcLines = src.Split (new char[] { ';' });
foreach (string srcLine in srcLines) {
string statement = srcLine.Trim ();
string[] operandes = statement.Split (new char[] { '=' });
if (operandes.Length < 2) //not an affectation
{
continue;
}
string lop = operandes [0].Trim ();
string rop = operandes [operandes.Length-1].Trim ();
#region LEFT OPERANDES
GraphicObject lopObj = es.Source; //default left operand base object is
//the first arg (object sender) of the event handler
string[] lopParts = lop.Split (new char[] { '.' });
if (lopParts.Length == 2) {//should search also for member of es.Source
lopObj = es.Source.FindByName (lopParts [0]);
if (lopObj==null)
throw new Exception (string.Format("GOML:Unknown name: {0}", lopParts[0]));
//TODO: should create private member holding ref of lopObj, and emit
//a call to FindByName(lopObjName) during #ctor or in a onLoad func or evt handler
throw new Exception (string.Format("GOML:obj tree ref not yet implemented", lopParts[0]));
}else
il.Emit(OpCodes.Ldarg_0); //load sender ref onto the stack
int i = lopParts.Length -1;
MemberInfo lopMbi = lopObj.GetType().GetMember (lopParts[i])[0];
OpCode lopSetOC;
dynamic lopSetMbi;
Type lopT = null;
switch (lopMbi.MemberType) {
case MemberTypes.Property:
PropertyInfo lopPi = srcType.GetProperty (lopParts[i]);
MethodInfo dstMi = lopPi.GetSetMethod ();
lopT = lopPi.PropertyType;
lopSetMbi = dstMi;
lopSetOC = OpCodes.Callvirt;
break;
case MemberTypes.Field:
FieldInfo dstFi = srcType.GetField(lopParts[i]);
lopT = dstFi.FieldType;
lopSetMbi = dstFi;
lopSetOC = OpCodes.Stfld;
break;
default:
throw new Exception (string.Format("GOML:member type not handle: {0}", lopParts[i]));
}
#endregion
#region RIGHT OPERANDES
if (rop.StartsWith("\'")){
if (!rop.EndsWith("\'"))
throw new Exception (string.Format
("GOML:malformed string constant in handler: {0}", rop));
string strcst = rop.Substring (1, rop.Length - 2);
il.Emit(OpCodes.Ldstr,strcst);
}else{
//search for a static field in left operand type named 'rop name'
FieldInfo ropFi = lopT.GetField (rop, BindingFlags.Static|BindingFlags.Public);
if (ropFi != null)
{
il.Emit (OpCodes.Ldsfld, ropFi);
}else{
//search if parsing methods are present
MethodInfo lopTryParseMi = lopT.GetMethod("TryParse");
}
}
#endregion
//emit left operand assignment
il.Emit(lopSetOC, lopSetMbi);
}
il.Emit(OpCodes.Ret);
#endregion
Delegate del = dm.CreateDelegate(ei.EventHandlerType);
MethodInfo addHandler = ei.GetAddMethod ();
addHandler.Invoke(es.Source, new object[] {del});
}
}
public static class CompilerServices
{
public static void CreateBindingHandler()
{
}
static int dynHandleCpt = 0;
/// <summary>
/// Compile events expression in GOML attributes
/// </summary>
/// <param name="es">Event binding details</param>
public static void CompileEventSource(DynAttribute es)
{
Type srcType = es.Source.GetType ();
#region Retrieve EventHandler parameter type
EventInfo ei = srcType.GetEvent (es.MemberName);
MethodInfo invoke = ei.EventHandlerType.GetMethod ("Invoke");
ParameterInfo[] pars = invoke.GetParameters ();
Type handlerArgsType = pars [1].ParameterType;
#endregion
Type[] args = {typeof(object), handlerArgsType};
DynamicMethod dm = new DynamicMethod("dynHandle",
typeof(void),
args,
srcType.Module);
#region IL generation
ILGenerator il = dm.GetILGenerator(256);
string src = es.Value.Trim();
if (! (src.StartsWith("{") || src.EndsWith ("}")))
throw new Exception (string.Format("GOML:Malformed {0} Event handler: {1}", es.MemberName, es.Value));
src = src.Substring (1, src.Length - 2);
string[] srcLines = src.Split (new char[] { ';' });
foreach (string srcLine in srcLines) {
string statement = srcLine.Trim ();
string[] operandes = statement.Split (new char[] { '=' });
if (operandes.Length < 2) //not an affectation
{
continue;
}
string lop = operandes [0].Trim ();
string rop = operandes [operandes.Length-1].Trim ();
#region LEFT OPERANDES
GraphicObject lopObj = es.Source; //default left operand base object is
//the first arg (object sender) of the event handler
string[] lopParts = lop.Split (new char[] { '.' });
if (lopParts.Length == 2) {//should search also for member of es.Source
lopObj = es.Source.FindByName (lopParts [0]);
if (lopObj==null)
throw new Exception (string.Format("GOML:Unknown name: {0}", lopParts[0]));
//TODO: should create private member holding ref of lopObj, and emit
//a call to FindByName(lopObjName) during #ctor or in a onLoad func or evt handler
throw new Exception (string.Format("GOML:obj tree ref not yet implemented", lopParts[0]));
}else
il.Emit(OpCodes.Ldarg_0); //load sender ref onto the stack
int i = lopParts.Length -1;
MemberInfo lopMbi = lopObj.GetType().GetMember (lopParts[i])[0];
OpCode lopSetOC;
dynamic lopSetMbi;
Type lopT = null;
switch (lopMbi.MemberType) {
case MemberTypes.Property:
PropertyInfo lopPi = srcType.GetProperty (lopParts[i]);
MethodInfo dstMi = lopPi.GetSetMethod ();
lopT = lopPi.PropertyType;
lopSetMbi = dstMi;
lopSetOC = OpCodes.Callvirt;
break;
case MemberTypes.Field:
FieldInfo dstFi = srcType.GetField(lopParts[i]);
lopT = dstFi.FieldType;
lopSetMbi = dstFi;
lopSetOC = OpCodes.Stfld;
break;
default:
throw new Exception (string.Format("GOML:member type not handle: {0}", lopParts[i]));
}
#endregion
#region RIGHT OPERANDES
if (rop.StartsWith("\'")){
if (!rop.EndsWith("\'"))
throw new Exception (string.Format
("GOML:malformed string constant in handler: {0}", rop));
string strcst = rop.Substring (1, rop.Length - 2);
il.Emit(OpCodes.Ldstr,strcst);
}else{
//search for a static field in left operand type named 'rop name'
FieldInfo ropFi = lopT.GetField (rop, BindingFlags.Static|BindingFlags.Public);
if (ropFi != null)
{
il.Emit (OpCodes.Ldsfld, ropFi);
}else{
//search if parsing methods are present
MethodInfo lopTryParseMi = lopT.GetMethod("TryParse");
//TODO
}
}
#endregion
//emit left operand assignment
il.Emit(lopSetOC, lopSetMbi);
}
il.Emit(OpCodes.Ret);
#endregion
Delegate del = dm.CreateDelegate(ei.EventHandlerType);
MethodInfo addHandler = ei.GetAddMethod ();
addHandler.Invoke(es.Source, new object[] {del});
}
/// <summary>
/// Resolves GOML property bindings afler loading
/// </summary>
/// <param name="binding">Binding details</param>
/// <param name="_source">Data source for binding</param>
public static void ResolveBinding(DynAttribute binding, object _source)
{
object srcGO = null;
string statement = binding.Value;
if (statement.StartsWith ("/"))//binding is done in graphic object tree, _source param is ignore
srcGO = binding.Source;
else
srcGO = _source;
string[] bindingExp = binding.Value.Split ('/');
if (bindingExp.Length > 1){
int i = 0;
srcGO = binding.Source; //starts parsing from current GO
while (i < bindingExp.Length - 1) {
if (bindingExp [i] == "..")
srcGO = (srcGO as ILayoutable).Parent as GraphicObject;
else
srcGO = (srcGO as GraphicObject).FindByName (bindingExp [i]);
i++;
}
string[] bindTrg = bindingExp [i].Split ('.');
if (bindTrg.Length == 2) {
srcGO = (srcGO as GraphicObject).FindByName (bindTrg [0]);
statement = bindTrg [1];
} else
throw new Exception ("Syntax error in binding, expected 'go dot member'");
}
if (srcGO == null) {
Debug.WriteLine ("Invalid Binding Source: " + binding.Value);
return;
}
Type srcType = srcGO.GetType ();
Type dstType = binding.Source.GetType ();
MemberInfo miSrc = srcType.GetMember (statement).FirstOrDefault ();
MemberInfo miDst = dstType.GetMember (binding.MemberName).FirstOrDefault ();
object srcVal = null; //value in source member
#region search for extensions methods if member not found in type
if (miSrc == null && !string.IsNullOrEmpty(statement))
{
Assembly a = Assembly.GetExecutingAssembly();
miSrc = CompilerServices.GetExtensionMethods(a, srcType).FirstOrDefault();
}
#endregion
#region initialize target with actual value
if (string.IsNullOrEmpty(binding.Value))
srcVal = srcGO;//if no member is provided for binding, source raw value is taken
else if (miSrc != null){
if (miSrc.MemberType == MemberTypes.Property)
srcVal = (miSrc as PropertyInfo).GetGetMethod ().Invoke (srcGO, null);
else if (miSrc.MemberType == MemberTypes.Field)
srcVal = (miSrc as FieldInfo).GetValue (srcGO);
else if (miSrc.MemberType == MemberTypes.Method){
MethodInfo mthSrc = miSrc as MethodInfo;
if (mthSrc.IsDefined(typeof(ExtensionAttribute), false))
srcVal = mthSrc.Invoke(null, new object[] {srcGO});
else
srcVal = mthSrc.Invoke(srcGO, null);
}else
throw new Exception ("unandled source member type for binding");
}
// if (miSrc != null){
if (miDst.MemberType == MemberTypes.Property) {
PropertyInfo piDst = miDst as PropertyInfo;
//TODO: handle other dest type conversions
if (piDst.PropertyType == typeof(string)){
if (srcVal != null)
srcVal = srcVal.ToString ();
}
piDst.GetSetMethod ().Invoke (binding.Source, new object[] { srcVal });
} else if (miDst.MemberType == MemberTypes.Field) {
FieldInfo fiDst = miDst as FieldInfo;
if (fiDst.FieldType == typeof(string))
srcVal = srcVal.ToString ();
fiDst.SetValue (binding.Source, srcVal );
}else
throw new Exception("unandled destination member type for binding");
// }
#endregion
#region Retrieve EventHandler parameter type
EventInfo ei = srcType.GetEvent ("ValueChanged");
if (ei == null)
return; //no dynamic update if ValueChanged interface is not implemented
MethodInfo evtInvoke = ei.EventHandlerType.GetMethod ("Invoke");
ParameterInfo[] evtParams = evtInvoke.GetParameters ();
Type handlerArgsType = evtParams [1].ParameterType;
#endregion
Type[] args = {typeof(object), handlerArgsType};
DynamicMethod dm = new DynamicMethod("dynHandle_" + dynHandleCpt,
typeof(void),
args,
srcType.Module, true);
(binding.Source as GraphicObject).DynamicMethodIds.Add (dynHandleCpt);
dynHandleCpt++;
//register target object reference
int dstIdx = Interface.Reference(binding.Source);
#region IL generation
ILGenerator il = dm.GetILGenerator(256);
System.Reflection.Emit.Label labFailed = il.DefineLabel();
System.Reflection.Emit.Label labContinue = il.DefineLabel();
#region test if valueChange event is the correct one
il.Emit (OpCodes.Ldstr, statement);
//push name from arg
il.Emit(OpCodes.Ldarg_1);
FieldInfo fiMbName = typeof(ValueChangeEventArgs).GetField("MemberName");
il.Emit(OpCodes.Ldfld, fiMbName);
MethodInfo miStrEqu = typeof(string).GetMethod("op_Inequality", new Type[] {typeof(string),typeof(string)});
il.Emit(OpCodes.Call, miStrEqu);
il.Emit(OpCodes.Brfalse_S, labContinue);
il.Emit(OpCodes.Br_S, labFailed);
il.MarkLabel(labContinue);
#endregion
// string[] srcLines = binding.Value.Trim().Split (new char[] { ';' });
// foreach (string srcLine in srcLines) {
//MethodInfo infoWriteLine = typeof(System.Diagnostics.Debug).GetMethod("WriteLine", new Type[] { typeof(string) });
//load target ref onto the stack
FieldInfo fiRefs = typeof(Interface).GetField("References");
il.Emit(OpCodes.Ldsfld, fiRefs);
il.Emit(OpCodes.Ldc_I4, dstIdx);
MethodInfo miGetRef = Interface.References.GetType().GetMethod("get_Item");
il.Emit(OpCodes.Callvirt, miGetRef);
il.Emit(OpCodes.Isinst, dstType);
//push new value
il.Emit(OpCodes.Ldarg_1);
FieldInfo fiNewValue = typeof(ValueChangeEventArgs).GetField("NewValue");
il.Emit(OpCodes.Ldfld, fiNewValue);
//Target is expected always to be a Property
PropertyInfo piTarget = dstType.GetProperty(binding.MemberName);
//type of the source value
Type srcValueType = null;
//member info of the source value
MemberInfo miSrcVal = miSrc;
//this allow memberless binding with only a name passed as MemberName
//the type of the source value is determined by the destination member
if (miSrcVal == null)
miSrcVal = miDst;
if (miSrcVal.MemberType == MemberTypes.Property)
srcValueType = (miSrcVal as PropertyInfo).PropertyType;
else if (miSrcVal.MemberType == MemberTypes.Field)
srcValueType = (miSrcVal as FieldInfo).FieldType;
else
throw new Exception("unandled source member type for binding");
if (!srcValueType.IsValueType)
il.Emit(OpCodes.Castclass, srcValueType);
else if (piTarget.PropertyType != srcValueType)
il.Emit(OpCodes.Callvirt, GetConvertMethod( piTarget.PropertyType ));
else
il.Emit(OpCodes.Unbox_Any, piTarget.PropertyType);
il.Emit(OpCodes.Callvirt, piTarget.GetSetMethod());
il.MarkLabel(labFailed);
il.Emit(OpCodes.Ret);
#endregion
Delegate del = dm.CreateDelegate(ei.EventHandlerType);
MethodInfo addHandler = ei.GetAddMethod ();
addHandler.Invoke(srcGO, new object[] {del});
}
#region conversions
internal static MethodInfo GetConvertMethod( Type targetType )
{
string name;
if( targetType == typeof( bool ) )
name = "ToBoolean";
else if( targetType == typeof( byte ) )
name = "ToByte";
else if( targetType == typeof( short ) )
name = "ToInt16";
else if( targetType == typeof( int ) )
name = "ToInt32";
else if( targetType == typeof( long ) )
name = "ToInt64";
else if( targetType == typeof( double ) )
name = "ToDouble";
else if (targetType == typeof (string ) )
return typeof(object).GetMethod("ToString", Type.EmptyTypes);
else
throw new NotImplementedException( string.Format( "Conversion to {0} is not implemented.", targetType.Name ) );
return typeof( Convert ).GetMethod( name, BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof( object ) }, null );
}
#endregion
public static FieldInfo GetEventHandlerField(Type type, string eventName)
{
FieldInfo fi;
Type ty = type;
do {
fi = ty.GetField (eventName,
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.GetField);
ty = ty.BaseType;
if (ty == null)
break;
} while(fi == null);
return fi;
}
/// <summary>
/// Gets extension methods defined in assembley for extendedType
/// </summary>
/// <returns>Extension methods enumerable</returns>
/// <param name="assembly">Assembly</param>
/// <param name="extendedType">Extended type to search for</param>
public static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly,
Type extendedType)
{
IEnumerable<MethodInfo> query = null;
Type curType = extendedType;
do {
query = from type in assembly.GetTypes ()
where type.IsSealed && !type.IsGenericType && !type.IsNested
from method in type.GetMethods (BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic)
where method.IsDefined (typeof(ExtensionAttribute), false)
where method.GetParameters () [0].ParameterType == curType
select method;
if (query.Count() > 0)
break;
curType = curType.BaseType;
} while (curType != null);
return query;
}
}
}
|