-
Notifications
You must be signed in to change notification settings - Fork 0
/
rmp.cs
1234 lines (744 loc) · 29.6 KB
/
rmp.cs
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Http;
/*
==================================================
routemap pages (rmp)
This namespace contains the classes that are used
to implement website routemap pages.
A [routemap] attribute is placed above any method
in a static or instance class that can process an
HTTP request.
USAGE
1. Include this file (rpm.cs) in your project.
2. Include the following using statement in any
file that defines a class to handle HTTP
requests:
using rmp;
3. Define a class with the methods that will
handle HTTP requests. In the example below,
the class "my_pages" contains two methods
"page1_render" and "page2_render". A [routemap]
attribute is placed above each method and
includes the route pattern used to invoke the
method:
using rmp;
public class my_pages
{
private int m_page1_render_count;
private int m_page2_render_count;
public my_pages()
{
int m_page1_render_count = 0;
int m_page2_render_count = 0;
}
[routemap( "/page1" ) ]
private async Task page1_render( HttpContext http_context )
{
m_page1_render_count++;
await http_context.Response.WriteAsync( $@"Page 1, render count: {m_page1_render_count}" );
return;
}
[routemap( "/page2" ) ]
private async Task page2_render( HttpContext http_context )
{
m_page2_render_count++;
await http_context.Response.WriteAsync( $@"Page 2, render count: {m_page2_render_count}" );
return;
}
}
4. Within the ConfigureServices method of the Startup class,
include the routmap pages service, as shown below:
using rmp;
public void ConfigureServices( IServiceCollection services )
{
// Add routemap pages service ...
services.add_rmp();
}
5. In the Configure method of the Startup class, include the
following lines to use routmap pages, as shown below:
public void Configure( IApplicationBuilder app )
{
// Use Routing (required) ...
app.UseRouting();
// Use routemap pages ...
app.use_rmp();
}
6. Build and launch the website. The [routemap] patterns
defined will be mapped to the appropriate handler, for
example:
/page1 => will invoke the my_pages.page1_render method
/page2 => will invoke the my_pages.page2_render method
NOTES / REFERENCES
- Routing in ASP.NET Core (specifically, Route template reference):
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0
- EndpointRouteBuilderExtensions.MapMethods Method:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.endpointroutebuilderextensions.mapmethods?view=aspnetcore-5.0
- Use Attributes in C# (specifically, How to create your own attribute):
https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/attributes
- Retrieving Information Stored in Attributes:
https://docs.microsoft.com/en-us/dotnet/standard/attributes/retrieving-information-stored-in-attributes
- How to: Hook Up a Delegate Using Reflection
https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-hook-up-a-delegate-using-reflection
==================================================
*/
namespace rmp
{
/*
==================================================
The routemap (attribute) class is used to define
the paths and HTTP methods that a RequestDelegate
handles.
==================================================
*/
[AttributeUsage( AttributeTargets.Method, AllowMultiple = true, Inherited = true )]
public class routemap : Attribute
{
/*
HTTP methods / verbs enumeration.
https://datatracker.ietf.org/doc/html/rfc7231#section-4.3
Used to indicate the HTTP methods that a routemap
supports. Method verbs are additive, for example
to specify that GET and POST are supported use:
routemap.http_methods.GET | routemap.http_methods.POST
*/
// Public HTTP methods / verbs enumeration ...
[System.Flags]
public enum http_methods : int
{
GET = 1,
HEAD = 2,
POST = 4,
PUT = 8,
DELETE = 16,
CONNECT = 32,
OPTIONS = 64,
TRACE = 128
}
// Private fields ...
// The route pattern ...
readonly private String m_route_pattern;
// The HTTP method verbs this route will allow ...
readonly private http_methods m_http_methods;
// The route order. Lower numeric value of order have higher priority ...
readonly private Int32 m_order;
// The source file path for this routemap ...
readonly private String m_file_path;
// The member name (handler) for this routemap ...
readonly private String m_member_name;
// The source file line number for this routemap ...
readonly private int m_line_number;
/*
--------------------------------------------------
Constructor with route pattern, HTTP methods, and
order.
PARAMETERS:
route_pattern
- The route template or pattern that provides a
route to a route handler.
http_methods
- An enumeration of HTTP methods that this route
will support. By default, if none are specified,
then the GET and POST methods are supported.
order
- The order for this routemap. May be any value
greater than or equal to zero. Default is zero.
A lower value will have higher priority.
EXAMPLE 1:
The following "my_pages" class has a method called
"page1_render". To map the path "/page1/" to the
method, the following routemap attribute is included:
public class my_pages
{
...
[routemap( "/page1" )]
public static async Task page1_render( HttpContext context )
{
await context.Response.WriteAsync( "Hello World!" );
}
}
When a GET or POST request is made using the "/page1" path, the
"page1_render" method will be invoked to return "Hello World!".
EXAMPLE 2:
The following "my_api" class has two methods with the same
routemap pattern, i.e.: /api/v1/test
The "page1_render" method will be executed because the order
is set to 1, which would take priority:
public class my_api
{
...
[routemap( "/api/v1/test", order: 1 )]
public static async Task page1_render( HttpContext context )
{
// This routemap would take priority as order is lower
}
[routemap( "/api/v1/test", order: 2 )]
public static async Task page2_render( HttpContext context )
{
...
}
}
--------------------------------------------------
*/
public routemap( String route_pattern,
http_methods allowed_http_methods = http_methods.GET | http_methods.POST,
Int32 order = 0,
[CallerFilePath] string file_path = "",
[CallerMemberName] string member_name = "",
[CallerLineNumber] int line_number = 0 )
{
// A route pattern is required ...
if ( string.IsNullOrEmpty( route_pattern ) )
{
throw new ArgumentNullException( nameof( route_pattern ) );
}
m_route_pattern = route_pattern;
m_http_methods = allowed_http_methods;
if ( order >= 0 )
{
m_order = order;
}
else
{
m_order = 0;
}
m_file_path = file_path;
m_member_name = member_name;
m_line_number = line_number;
}
/*
--------------------------------------------------
Returns the route pattern for this routemap.
--------------------------------------------------
*/
public virtual string route_pattern
{
get
{
return m_route_pattern;
}
}
/*
--------------------------------------------------
Returns the allowed HTTP methods enumeration for
this routemap.
--------------------------------------------------
*/
public virtual http_methods allowed_http_methods
{
get
{
return m_http_methods;
}
}
/*
--------------------------------------------------
Returns a list of allowed HTTP method verb strings
for this routemap.
--------------------------------------------------
*/
public virtual System.Collections.Generic.List<String> allowed_http_method_list
{
get
{
String http_verb;
System.Collections.Generic.List<String> method_list;
method_list = new System.Collections.Generic.List<String>();
// Loop through http_methods enum to see which flags are set ...
foreach ( Enum method_val in Enum.GetValues( m_http_methods.GetType() ) )
{
// If a flag is set, add HTTP verb name to list ...
if ( m_http_methods.HasFlag( method_val ) )
{
http_verb = method_val.ToString().ToUpper();
method_list.Add( http_verb );
}
}
return method_list;
}
}
/*
--------------------------------------------------
Returns the order for the routemap. Endpoints
with a lower numeric value of order have higher
priority.
--------------------------------------------------
*/
public virtual Int32 order
{
get
{
return m_order;
}
}
/*
--------------------------------------------------
Returns the source file path for this routemap.
--------------------------------------------------
*/
public virtual String file_path
{
get
{
return m_file_path;
}
}
/*
--------------------------------------------------
Returns the member name (handler) for this routemap.
--------------------------------------------------
*/
public virtual String member_name
{
get
{
return m_member_name;
}
}
/*
--------------------------------------------------
Returns the source line number for this routemap.
--------------------------------------------------
*/
public virtual int line_number
{
get
{
return m_line_number;
}
}
}
/*
==================================================
A helper class used to hold data associated with a
routemap pattern.
==================================================
*/
public class routemap_data
{
// The name of the method invoked for a routemap ...
private readonly String m_method_name;
// The routemap attribute object ...
private readonly routemap m_routemap_attribute;
/*
--------------------------------------------------
Constructor
--------------------------------------------------
*/
public routemap_data( String method_name, routemap routemap_attribute )
{
m_method_name = method_name;
m_routemap_attribute = routemap_attribute;
}
/*
--------------------------------------------------
Returns a string containing the method name that
is invoked to handle a routemap pattern / path ...
--------------------------------------------------
*/
public String method_name
{
get
{
return m_method_name;
}
}
/*
--------------------------------------------------
Returns a [routemap] attribute object ...
--------------------------------------------------
*/
public routemap routemap_attribute
{
get
{
return m_routemap_attribute;
}
}
}
/*
==================================================
Routemap endpoints class used to add endpoints for
all methods that have one or more [routemap]
declarations associated with them.
==================================================
*/
public class routemap_endpoints
{
/*
A dictionary used to keep track of the routemap's
created; key is the route pattern ...
*/
private readonly System.Collections.Generic.Dictionary<String, routemap_data> m_routemap_dict;
/*
--------------------------------------------------
Constructor.
--------------------------------------------------
*/
public routemap_endpoints()
{
m_routemap_dict = new System.Collections.Generic.Dictionary<String, routemap_data>();
}
/*
--------------------------------------------------
Writes all routemaps to the given output file.
Useful when debugging.
--------------------------------------------------
*/
public void log_to_file( String output_file_spec )
{
StringBuilder sb;
routemap_data routemap_data;
routemap routemap_attribute;
// Exit if no output file spec supplied ...
if ( String.IsNullOrEmpty( output_file_spec ) )
{
return;
}
// Build list of routemap endpoints ...
sb = new StringBuilder();
sb.AppendLine( $@"Number of [routemap] endpoints defined: {m_routemap_dict.Count}" );
foreach ( String route_pattern_key in m_routemap_dict.Keys )
{
routemap_data = m_routemap_dict[ route_pattern_key ];
routemap_attribute = routemap_data.routemap_attribute;
sb.AppendLine( "" );
sb.AppendLine( $@"Route pattern: {routemap_attribute.route_pattern}" );
foreach ( String http_method_verb in routemap_attribute.allowed_http_method_list )
{
sb.AppendLine( $@"- HTTP method: {http_method_verb}" );
}
sb.AppendLine( $@"- Order: {routemap_attribute.order}" );
sb.AppendLine( $@"- Mapped to method: {routemap_data.method_name}" );
sb.AppendLine( $@"- Source file: {routemap_attribute.file_path}, line number: {routemap_attribute.line_number}" );
}
// Write to output file ...
try
{
System.IO.File.WriteAllText( output_file_spec, sb.ToString() );
}
catch ( Exception ex )
{
throw new Exception( $@"* Output file: {output_file_spec}, {ex}" );
}
}
/*
--------------------------------------------------
Returns the defined routemaps as a dictionary of
route patterns (the Key) and routemap_data objects.
--------------------------------------------------
*/
public System.Collections.Generic.Dictionary<String, routemap_data> routemaps
{
get
{
return m_routemap_dict;
}
}
/*
--------------------------------------------------
Given a MethodInfo object, return a string that
contains the declaring type and method name, that
is, the fully qualified method name ...
NOTE: This will throw an exception if the given
MethodInfo objects DeclaringType property
is null.
--------------------------------------------------
*/
private static String qualified_method_name( MethodInfo method_info )
{
if ( method_info.DeclaringType is null )
{
throw new ArgumentException( $"{nameof( method_info )} does not have a declaring type." );
}
return method_info.DeclaringType.FullName + "." + method_info.Name;
}
/*
--------------------------------------------------
Returns a list of MethodInfo objects for all methods
within the executing assembly that have one or more
[routemap] declarations.
--------------------------------------------------
*/
private static System.Collections.Generic.List<MethodInfo> methods_with_routemap_attributes()
{
String method_name;
ParameterInfo[] parameter_info_array;
System.Reflection.MethodInfo[] method_info_array;
System.Type[] assembly_types_array;
System.Collections.Generic.List<MethodInfo> method_info_list;
// Init ...
method_info_list = new System.Collections.Generic.List<MethodInfo>();
// Find all the methods that have [routemap] attribute(s) ...
assembly_types_array = Assembly.GetExecutingAssembly().GetTypes();
foreach ( Type t in assembly_types_array )
{
// If the type is a class or delegate, then get its methods ...
if ( t.IsClass )
{
method_info_array = t.GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
// Loop through the methods and save any methods with a [routemap] attribute in our list ...
foreach ( MethodInfo method_info in method_info_array )
{
if ( System.Attribute.GetCustomAttributes( method_info, typeof( routemap ) ).Length > 0 )
{
// Get qualified method name for error reporting ...
method_name = qualified_method_name( method_info );
// If the method has a single parameter of type HttpContext, save in our list ...
parameter_info_array = method_info.GetParameters();
if ( parameter_info_array.Length == 1 && parameter_info_array[ 0 ].ParameterType == typeof( Microsoft.AspNetCore.Http.HttpContext ) )
{
method_info_list.Add( method_info );
}
else
{
throw new InvalidOperationException( $@"Method: {method_name}, must have a single parameter of type: Microsoft.AspNetCore.Http.HttpContext" );
}
}
}
}
}
return method_info_list;
}
/*
--------------------------------------------------
Given a list of MethodInfo objects, return a
dictionary of fully qualified method names (key)
and the associated route handler (value) for each.
--------------------------------------------------
*/
private static System.Collections.Generic.Dictionary<String, Microsoft.AspNetCore.Http.RequestDelegate> route_handlers_create( System.Collections.Generic.List<MethodInfo> method_info_list )
{
object class_object;
String method_name;
System.Collections.Generic.Dictionary<String, Microsoft.AspNetCore.Http.RequestDelegate> method_name_dict;
/*
The instance list is used to keep track of instances created when creating
Microsoft.AspNetCore.Http.RequestDelegate objects for methods in non-static
classes. We need to keep track of the instances so that only a single instance
will be created in the case where an instance has multiple methods that have
[routemap] attributes. If we did not do this, a new instance would be created
each time!
*/
System.Collections.Generic.List<object> instance_list;
Microsoft.AspNetCore.Http.RequestDelegate route_handler;
// method_info_list is required ...
if ( method_info_list is null )
{
throw new ArgumentNullException( nameof( method_info_list ) );
}
// Init ...
instance_list = new System.Collections.Generic.List<object>();
method_name_dict = new System.Collections.Generic.Dictionary<String, Microsoft.AspNetCore.Http.RequestDelegate>();
// Loop to create a route handler for each method in the list ...
foreach ( MethodInfo method_info in method_info_list )
{
// Get fully qualified method name (for exception reporting and dictionary key) ...
method_name = qualified_method_name( method_info );
route_handler = null;
/*
Tried using RequestDelegateFactory.Create to create the RequestDelegate, for example:
route_handler = RequestDelegateFactory.Create( method_info ).RequestDelegate;
It works, BUT for methods of a non-static class, it will create a new instance
of the class EACH TIME it is called (calls Activator.CreateInstance internally).
Using the MethodInfo.CreateDelegate method works and allows us to create a single
instance instead.
*/
// If a static method, create a delegate that can process an HTTP request ...
if ( method_info.IsStatic )
{
try
{
route_handler = method_info.CreateDelegate<Microsoft.AspNetCore.Http.RequestDelegate>();
}
catch ( Exception ex )
{
throw new Exception( $"* Unable to create delegate for [routemap] static method: {method_name}, {ex}" );
}
}
else
{
/*
For a non-static method, we first check if an instance of the class
that contains the method exists in our list. If so, then we use
the instance to create the delegate ...
*/
try
{
class_object = null;
foreach ( object instance in instance_list )
{
if ( instance.GetType() == method_info.DeclaringType )
{
class_object = instance;
break;
}
}
/*
If a class object (instance) was not found above, it means we need to
create an instance of the class that contains the given method, so
attempt to do so ...
*/
if ( class_object is null )
{
// Create an instance of the class; this will trigger the class constructor ...
class_object = System.Activator.CreateInstance( method_info.DeclaringType );
// Add the class instance in our list ...
instance_list.Add( class_object );
}
// Create the route handler ...
route_handler = method_info.CreateDelegate<Microsoft.AspNetCore.Http.RequestDelegate>( class_object );
}
catch ( Exception ex )
{
throw new Exception( $"* Unable to create delegate for [routemap] method: {method_name}, {ex}" );
}
}
// Save the method name and route handler in our dictionary ...
method_name_dict.Add( method_name, route_handler );
}
return method_name_dict;
}
/*
--------------------------------------------------
Given a routemap attribute object, returns a string