-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Util.cs
1730 lines (1399 loc) · 58.2 KB
/
Util.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
//------------------------------------------------------------------------------
// <copyright file="Util.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Implements various utility functions used by the template code
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Management;
using System.Web.Security;
using System.Web.Security.Cryptography;
using System.Web.UI.WebControls;
using System.Web.Util;
using Microsoft.Win32;
using Debug = System.Web.Util.Debug;
internal static class Util {
private static string[] s_invalidCultureNames = new string[] { "aspx", "ascx", "master" };
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "This is being tracked as DevDiv #21217 (http://vstfdevdiv:8080/DevDiv2/web/wi.aspx?id=21217).")]
internal static string SerializeWithAssert(IStateFormatter formatter, object stateGraph) {
return formatter.Serialize(stateGraph);
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "This is being tracked as DevDiv #21217 (http://vstfdevdiv:8080/DevDiv2/web/wi.aspx?id=21217).")]
internal static string SerializeWithAssert(IStateFormatter2 formatter, object stateGraph, Purpose purpose) {
return formatter.Serialize(stateGraph, purpose);
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "This is being tracked as DevDiv #21217 (http://vstfdevdiv:8080/DevDiv2/web/wi.aspx?id=21217).")]
internal static object DeserializeWithAssert(IStateFormatter2 formatter, string serializedState, Purpose purpose) {
return formatter.Deserialize(serializedState, purpose);
}
internal static bool CanConvertToFrom(TypeConverter converter, Type type) {
return (converter != null && converter.CanConvertTo(type) &&
converter.CanConvertFrom(type) && !(converter is ReferenceConverter));
}
internal static void CopyBaseAttributesToInnerControl(WebControl control, WebControl child) {
short oldTab = control.TabIndex;
string oldAccess = control.AccessKey;
try {
control.AccessKey = String.Empty;
control.TabIndex = 0;
child.CopyBaseAttributes(control);
}
finally {
control.TabIndex = oldTab;
control.AccessKey = oldAccess;
}
}
internal static long GetRecompilationHash(PagesSection ps)
{
HashCodeCombiner recompilationHash = new HashCodeCombiner();
NamespaceCollection namespaces;
TagPrefixCollection controls;
TagMapCollection tagMapping;
// Combine items from Pages section
recompilationHash.AddObject(ps.Buffer);
recompilationHash.AddObject(ps.EnableViewState);
recompilationHash.AddObject(ps.EnableViewStateMac);
recompilationHash.AddObject(ps.EnableEventValidation);
recompilationHash.AddObject(ps.SmartNavigation);
recompilationHash.AddObject(ps.ValidateRequest);
recompilationHash.AddObject(ps.AutoEventWireup);
if (ps.PageBaseTypeInternal != null) {
recompilationHash.AddObject(ps.PageBaseTypeInternal.FullName);
}
if (ps.UserControlBaseTypeInternal != null) {
recompilationHash.AddObject(ps.UserControlBaseTypeInternal.FullName);
}
if (ps.PageParserFilterTypeInternal != null) {
recompilationHash.AddObject(ps.PageParserFilterTypeInternal.FullName);
}
recompilationHash.AddObject(ps.MasterPageFile);
recompilationHash.AddObject(ps.Theme);
recompilationHash.AddObject(ps.StyleSheetTheme);
recompilationHash.AddObject(ps.EnableSessionState);
recompilationHash.AddObject(ps.CompilationMode);
recompilationHash.AddObject(ps.MaxPageStateFieldLength);
recompilationHash.AddObject(ps.ViewStateEncryptionMode);
recompilationHash.AddObject(ps.MaintainScrollPositionOnPostBack);
// Combine items from Namespaces collection
namespaces = ps.Namespaces;
recompilationHash.AddObject(namespaces.AutoImportVBNamespace);
if (namespaces.Count == 0) {
recompilationHash.AddObject("__clearnamespaces");
}
else {
foreach (NamespaceInfo ni in namespaces) {
recompilationHash.AddObject(ni.Namespace);
}
}
// Combine items from the Controls collection
controls = ps.Controls;
if (controls.Count == 0) {
recompilationHash.AddObject("__clearcontrols");
}
else {
foreach (TagPrefixInfo tpi in controls) {
recompilationHash.AddObject(tpi.TagPrefix);
if (tpi.TagName != null && tpi.TagName.Length != 0) {
recompilationHash.AddObject(tpi.TagName);
recompilationHash.AddObject(tpi.Source);
}
else {
recompilationHash.AddObject(tpi.Namespace);
recompilationHash.AddObject(tpi.Assembly);
}
}
}
// Combine items from the TagMapping Collection
tagMapping = ps.TagMapping;
if (tagMapping.Count == 0) {
recompilationHash.AddObject("__cleartagmapping");
}
else {
foreach (TagMapInfo tmi in tagMapping) {
recompilationHash.AddObject(tmi.TagType);
recompilationHash.AddObject(tmi.MappedTagType);
}
}
return recompilationHash.CombinedHash;
}
internal static Encoding GetEncodingFromConfigPath(VirtualPath configPath) {
Debug.Assert(configPath != null, "configPath != null");
// Check if a file encoding is specified in the config
Encoding fileEncoding = null;
GlobalizationSection globConfig = RuntimeConfig.GetConfig(configPath).Globalization;
fileEncoding = globConfig.FileEncoding;
// If not, use the default encoding
if (fileEncoding == null)
fileEncoding = Encoding.Default;
return fileEncoding;
}
/*
* Return a reader which holds the contents of a file. If a configPath is passed
* in, try to get an encoding for it
*/
internal /*public*/ static StreamReader ReaderFromFile(string filename, VirtualPath configPath) {
StreamReader reader;
// Check if a file encoding is specified in the config
Encoding fileEncoding = Encoding.Default;
if (configPath != null) fileEncoding = GetEncodingFromConfigPath(configPath);
try {
// Create a reader on the file, using the encoding
// Throws an exception if the file can't be opened.
reader = new StreamReader(filename, fileEncoding,
true /*detectEncodingFromByteOrderMarks*/, 4096);
}
catch (UnauthorizedAccessException) {
// AccessException might mean two very different things: it could be a real
// access problem, or it could be that it's actually a directory.
// It's a directory: give a specific error.
if (FileUtil.DirectoryExists(filename)) {
throw new HttpException(
SR.GetString(SR.Unexpected_Directory, HttpRuntime.GetSafePath(filename)));
}
// It's a real access problem, so just rethrow it
throw;
}
return reader;
}
/*
* Attempt to delete a file, but don't throw if it can't be done
*/
internal static void DeleteFileNoException(string path) {
Debug.Assert(File.Exists(path), path);
try {
File.Delete(path);
}
catch { } // Ignore all exceptions
}
internal static void DeleteFileIfExistsNoException(string path) {
if (File.Exists(path))
DeleteFileNoException(path);
}
/*
* Return true if the directory exists and is not empty.
*/
internal static bool IsNonEmptyDirectory(string dir) {
// Does it exist
if (!Directory.Exists(dir))
return false;
// It exists, but maybe it's empty
try {
string[] entries = Directory.GetFileSystemEntries(dir);
return entries.Length > 0;
}
catch {
// If it throws, assume it's non-empty
return true;
}
}
/*
* Return true if string is a valid simple file name (with no path or wild cards)
*/
private static char[] invalidFileNameChars = new char[] { '/', '\\', '?', '*', ':' } ;
internal static bool IsValidFileName(string fileName) {
// Check for the special names "." and ".."
if (fileName == "." || fileName == "..")
return false;
// Check for invalid characters
if (fileName.IndexOfAny(invalidFileNameChars) >= 0)
return false;
return true;
}
/*
* Replace all invalid chars in a filename by underscores.
*/
internal static string MakeValidFileName(string fileName) {
// If it's already valid, nothing to do
if (IsValidFileName(fileName))
return fileName;
// Replace all the invalid chars by '_'
for (int i = 0; i < invalidFileNameChars.Length; ++i) {
fileName = fileName.Replace(invalidFileNameChars[i], '_');
}
// Shoud always be valid now
Debug.Assert(IsValidFileName(fileName));
return fileName;
}
/*
* Return true if the current user has write access to the directory
*/
internal static bool HasWriteAccessToDirectory(string dir) {
// If it doesn't even exist (or we can't determine that it does), return false
if (!Directory.Exists(dir))
return false;
// Get the path to a dummy file in that directory
string dummyFile = Path.Combine(dir, "~AspAccessCheck_" +
HostingEnvironment.AppDomainUniqueInteger.ToString(
"x", CultureInfo.InvariantCulture) + SafeNativeMethods.GetCurrentThreadId() + ".tmp");
FileStream fs = null;
bool success = false;
try {
// Attempt to create the file
fs = new FileStream(dummyFile, FileMode.Create);
}
catch {
}
finally {
if (fs != null) {
// If successfully created, close and delete it
fs.Close();
File.Delete(dummyFile);
success = true;
}
}
return success;
}
internal static VirtualPath GetScriptLocation() {
// prepare script include
// Dev10 Bug564221: we need to detect if app level web.config overwrites the root web.config
string location = (string) RuntimeConfig.GetAppConfig().WebControls["clientScriptsLocation"];
// If there is a formatter, as there will be for the default machine.config, insert the assembly name and version.
if (location.IndexOf("{0}", StringComparison.Ordinal) >= 0) {
string assembly = "system_web";
// QFE number is not included in client path
string version = VersionInfo.SystemWebVersion.Substring(0, VersionInfo.SystemWebVersion.LastIndexOf('.')).Replace('.', '_');
location = String.Format(CultureInfo.InvariantCulture, location, assembly, version);
}
return VirtualPath.Create(location);
}
/*
* Return a reader which holds the contents of a file. If a configPath is passed
* in, try to get a encoding for it
*/
internal /*public*/ static StreamReader ReaderFromStream(Stream stream, VirtualPath configPath) {
// Check if a file encoding is specified in the config
Encoding fileEncoding = GetEncodingFromConfigPath(configPath);
// Create a reader on the file, using the encoding
return new StreamReader(stream, fileEncoding,
true /*detectEncodingFromByteOrderMarks*/, 4096);
}
/*
* Return a String which holds the contents of a file
*/
internal /*public*/ static String StringFromVirtualPath(VirtualPath virtualPath) {
using (Stream stream = virtualPath.OpenFile()) {
// Create a reader on the file, and read the whole thing
TextReader reader = Util.ReaderFromStream(stream, virtualPath);
return reader.ReadToEnd();
}
}
/*
* Return a String which holds the contents of a file
*/
internal /*public*/ static String StringFromFile(string path) {
Encoding encoding = Encoding.Default;
return StringFromFile(path, ref encoding);
}
/*
* Return a String which holds the contents of a file with specific encoding.
*/
internal /*public*/ static String StringFromFile(string path, ref Encoding encoding) {
// Create a reader on the file.
// Generates an exception if the file can't be opened.
StreamReader reader = new StreamReader(path, encoding, true /*detectEncodingFromByteOrderMarks*/);
try {
string content = reader.ReadToEnd();
encoding = reader.CurrentEncoding;
return content;
}
finally {
// Make sure we always close the stream
if (reader != null)
reader.Close();
}
}
/*
* Return a String which holds the contents of a file, or null if the file
* doesn't exist.
*/
internal /*public*/ static String StringFromFileIfExists(string path) {
if (!File.Exists(path)) return null;
return StringFromFile(path);
}
/*
* If the file doesn't exist, do nothing. If it does try to delete it if possible.
* If that fails, rename it with by appending a .delete extension to it
*/
internal static void RemoveOrRenameFile(string filename) {
FileInfo fi = new FileInfo(filename);
RemoveOrRenameFile(fi);
}
/*
* If the file doesn't exist, do nothing. If it does try to delete it if possible.
* If that fails, rename it with by appending a .delete extension to it
*/
internal static bool RemoveOrRenameFile(FileInfo f) {
try {
// First, just try to delete the file
f.Delete();
// It was successfully deleted, so return true
return true;
}
catch {
try {
// If the delete failed, rename it to ".delete"
// Don't do that if it already has the delete extension
if (f.Extension != ".delete") {
// include a unique token as part of the new name, to avoid
// conflicts with previous renames (VSWhidbey 79996)
string uniqueToken = DateTime.Now.Ticks.GetHashCode().ToString("x", CultureInfo.InvariantCulture);
string newName = f.FullName + "." + uniqueToken + ".delete";
f.MoveTo(newName);
}
}
catch {
// Ignore all exceptions
}
}
// Return false because we couldn't delete it, and had to rename it
return false;
}
/*
* Clears a file's readonly attribute if it has one
*/
internal static void ClearReadOnlyAttribute(string path) {
FileAttributes attribs = File.GetAttributes(path);
if ((attribs & FileAttributes.ReadOnly) != 0) {
File.SetAttributes(path, attribs & ~FileAttributes.ReadOnly);
}
}
internal static void CheckVirtualFileExists(VirtualPath virtualPath) {
if (!virtualPath.FileExists()) {
throw new HttpException(
HttpStatus.NotFound,
SR.GetString(SR.FileName_does_not_exist,
virtualPath.VirtualPathString));
}
}
internal static bool VirtualFileExistsWithAssert(VirtualPath virtualPath) {
string physicalDir = virtualPath.MapPathInternal();
if (physicalDir != null) {
(InternalSecurityPermissions.PathDiscovery(physicalDir)).Assert();
}
return virtualPath.FileExists();
}
internal static void CheckThemeAttribute(string themeName) {
if (themeName.Length > 0) {
if (!FileUtil.IsValidDirectoryName(themeName)) {
throw new HttpException(SR.GetString(SR.Page_theme_invalid_name, themeName));
}
if (!ThemeExists(themeName)) {
throw new HttpException(SR.GetString(SR.Page_theme_not_found, themeName));
}
}
}
internal static bool ThemeExists(string themeName) {
VirtualPath virtualDir = ThemeDirectoryCompiler.GetAppThemeVirtualDir(themeName);
if (!VirtualDirectoryExistsWithAssert(virtualDir)) {
virtualDir = ThemeDirectoryCompiler.GetGlobalThemeVirtualDir(themeName);
if (!VirtualDirectoryExistsWithAssert(virtualDir)) {
return false;
}
}
return true;
}
private static bool VirtualDirectoryExistsWithAssert(VirtualPath virtualDir) {
try {
String physicalDir = virtualDir.MapPathInternal();
if (physicalDir != null) {
new FileIOPermission(FileIOPermissionAccess.Read, physicalDir).Assert();
}
return virtualDir.DirectoryExists();
}
catch {
return false;
}
}
internal static void CheckAssignableType(Type baseType, Type type) {
if (!baseType.IsAssignableFrom(type)) {
throw new HttpException(
SR.GetString(SR.Type_doesnt_inherit_from_type,
type.FullName, baseType.FullName));
}
}
internal /*public*/ static int LineCount(string text, int offset, int newoffset) {
Debug.Assert(offset <= newoffset);
int linecount = 0;
while (offset < newoffset) {
if (text[offset] == '\r' || (text[offset] == '\n' && (offset == 0 || text[offset - 1] != '\r')))
linecount++;
offset++;
}
return linecount;
}
/*
* Calls Invoke on a MethodInfo. If an exception happens during the
* method call, catch it and throw it back.
*/
internal static object InvokeMethod(
MethodInfo methodInfo,
object obj,
object[] parameters) {
try {
return methodInfo.Invoke(obj, parameters);
}
catch (TargetInvocationException e) {
throw e.InnerException;
}
}
/*
* If the passed in Type has a non-private field with the passed in name,
* return the field's Type.
*/
internal static Type GetNonPrivateFieldType(Type classType, string fieldName) {
FieldInfo fieldInfo = classType.GetField(fieldName,
BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (fieldInfo == null || fieldInfo.IsPrivate)
return null;
return fieldInfo.FieldType;
}
/*
* If the passed in Type has a non-private property with the passed in name,
* return the property's Type.
*/
internal static Type GetNonPrivatePropertyType(Type classType, string propName) {
PropertyInfo propInfo = null;
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance
| BindingFlags.IgnoreCase | BindingFlags.NonPublic;
try {
propInfo = classType.GetProperty(propName, flags);
}
catch (AmbiguousMatchException) {
// We could get an AmbiguousMatchException if the property exists on two
// different ancestor classes (VSWhidbey 216957). When that happens, attempt
// a lookup on the Type itself, ignoring its ancestors.
flags |= BindingFlags.DeclaredOnly;
propInfo = classType.GetProperty(propName, flags);
}
if (propInfo == null)
return null;
// If it doesn't have a setter, ot if it's private, fail
MethodInfo methodInfo = propInfo.GetSetMethod(true /*nonPublic*/);
if (methodInfo == null || methodInfo.IsPrivate)
return null;
return propInfo.PropertyType;
}
/*
* Checks whether the property has a TemplateInstanceAttribute, and returns true if
* its value is TemplateInstance.Multiple.
*/
internal static bool IsMultiInstanceTemplateProperty(PropertyInfo pInfo) {
object[] instanceAttrs = pInfo.GetCustomAttributes(typeof(TemplateInstanceAttribute), /*inherits*/ false);
// Default value for TemplateInstanceAttribute is TemplateInstance.Multiple
if (instanceAttrs == null || instanceAttrs.Length == 0) {
return true;
}
return ((TemplateInstanceAttribute)instanceAttrs[0]).Instances == TemplateInstance.Multiple;
}
/*
* Return the first key of the dictionary as a string. Throws if it's
* empty or if the key is not a string.
*/
private static string FirstDictionaryKey(IDictionary dict) {
IDictionaryEnumerator e = dict.GetEnumerator();
e.MoveNext();
return (string)e.Key;
}
/*
* Get a value from a dictionary, and remove it from the dictionary if
* it exists.
*/
private static string GetAndRemove(IDictionary dict, string key) {
string val = (string) dict[key];
if (val != null) {
dict.Remove(key);
val = val.Trim();
}
return val;
}
/*
* Get a value from a dictionary, and remove it from the dictionary if
* it exists. Throw an exception if the value is a whitespace string.
* However, don't complain about null, which simply means the value is not
* in the dictionary.
*/
internal static string GetAndRemoveNonEmptyAttribute(IDictionary directives, string key, bool required) {
string val = Util.GetAndRemove(directives, key);
if (val == null) {
if (required)
throw new HttpException(SR.GetString(SR.Missing_attr, key));
return null;
}
return GetNonEmptyAttribute(key, val);
}
// Return the value, after checking that it's not empty
internal static string GetNonEmptyAttribute(string name, string value) {
value = value.Trim();
if (value.Length == 0) {
throw new HttpException(
SR.GetString(SR.Empty_attribute, name));
}
return value;
}
// Return the value, after checking that it doesn't contain spaces
internal static string GetNoSpaceAttribute(string name, string value) {
if (Util.ContainsWhiteSpace(value)) {
throw new HttpException(
SR.GetString(SR.Space_attribute, name));
}
return value;
}
internal static string GetAndRemoveNonEmptyAttribute(IDictionary directives, string key) {
return GetAndRemoveNonEmptyAttribute(directives, key, false /*required*/);
}
internal static VirtualPath GetAndRemoveVirtualPathAttribute(IDictionary directives, string key) {
return GetAndRemoveVirtualPathAttribute(directives, key, false /*required*/);
}
internal static VirtualPath GetAndRemoveVirtualPathAttribute(IDictionary directives, string key, bool required) {
string val = GetAndRemoveNonEmptyAttribute(directives, key, required);
if (val == null)
return null;
return VirtualPath.Create(val);
}
/*
* Parse a DeviceName:AttribName string into its components
*/
internal const char DeviceFilterSeparator = ':';
internal const string XmlnsAttribute = "xmlns:";
public static string ParsePropertyDeviceFilter(string input, out string propName) {
string deviceName = String.Empty;
// If the string has no device filter, the whole string is the property name
if (input.IndexOf(DeviceFilterSeparator) < 0) {
propName = input;
}
// Don't treat xmlns as filters, this needs to be treated differently.
// VSWhidbey 495125
else if (StringUtil.StringStartsWithIgnoreCase(input, XmlnsAttribute)) {
propName = input;
}
else {
// There is a filter: parse it out
string[] tmp = input.Split(DeviceFilterSeparator);
if (tmp.Length > 2) {
throw new HttpException(
SR.GetString(SR.Too_many_filters, input));
}
if (MTConfigUtil.GetPagesConfig().IgnoreDeviceFilters[tmp[0]] != null) {
propName = input;
}
else {
deviceName = tmp[0];
propName = tmp[1];
}
}
return deviceName;
}
/// <devdoc>
/// Combines the filter and name
/// </devdoc>
public static string CreateFilteredName(string deviceName, string name) {
if (deviceName.Length > 0) {
return deviceName + DeviceFilterSeparator + name;
}
return name;
}
internal static string GetAndRemoveRequiredAttribute(IDictionary directives, string key) {
return GetAndRemoveNonEmptyAttribute(directives, key, true /*required*/);
}
/*
* Same as GetAndRemoveNonEmptyAttribute, but make sure the value does not
* contain any whitespace characters.
*/
internal static string GetAndRemoveNonEmptyNoSpaceAttribute(IDictionary directives,
string key, bool required) {
string val = Util.GetAndRemoveNonEmptyAttribute(directives, key, required);
if (val == null)
return null;
return GetNonEmptyNoSpaceAttribute(key, val);
}
internal static string GetAndRemoveNonEmptyNoSpaceAttribute(IDictionary directives,
string key) {
return GetAndRemoveNonEmptyNoSpaceAttribute(directives, key, false /*required*/);
}
// Return the value, after checking that it's not empty and has no spaces
internal static string GetNonEmptyNoSpaceAttribute(string name, string value) {
value = GetNonEmptyAttribute(name, value);
return GetNoSpaceAttribute(name, value);
}
/*
* Same as GetAndRemoveNonEmptyNoSpaceAttribute, but make sure the value is a
* valid language identifier
*/
internal static string GetAndRemoveNonEmptyIdentifierAttribute(IDictionary directives,
string key, bool required) {
string val = Util.GetAndRemoveNonEmptyNoSpaceAttribute(directives, key, required);
if (val == null)
return null;
return GetNonEmptyIdentifierAttribute(key, val);
}
// Return the value, after checking that it's a valid id
internal static string GetNonEmptyIdentifierAttribute(string name, string value) {
value = GetNonEmptyNoSpaceAttribute(name, value);
if (!System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(value)) {
throw new HttpException(
SR.GetString(SR.Invalid_attribute_value, value, name));
}
return value;
}
// Return the class and the namespace
internal static string GetNonEmptyFullClassNameAttribute(string name, string value,
ref string ns) {
value = GetNonEmptyNoSpaceAttribute(name, value);
// The value can be of the form NS1.NS2.MyClassName. Split it into its parts.
string[] parts = value.Split('.');
// Check that all the parts are valid identifiers
foreach (string part in parts) {
if (!System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(part)) {
throw new HttpException(
SR.GetString(SR.Invalid_attribute_value, value, name));
}
}
// If there is a namespace, return it
if (parts.Length > 1)
ns = String.Join(".", parts, 0, parts.Length-1);
// Return the class name (which is the last part)
return parts[parts.Length-1];
}
internal static void CheckUnknownDirectiveAttributes(string directiveName, IDictionary directive) {
CheckUnknownDirectiveAttributes(directiveName, directive, SR.Attr_not_supported_in_directive);
}
internal static void CheckUnknownDirectiveAttributes(string directiveName, IDictionary directive,
string resourceKey) {
// If there are some attributes left, fail
if (directive.Count > 0) {
throw new HttpException(
SR.GetString(resourceKey,
Util.FirstDictionaryKey(directive), directiveName));
}
}
/*
* Get a string value from a dictionary, and convert it to bool. Throw an
* exception if it's not a valid bool string.
* However, don't complain about null, which simply means the value is not
* in the dictionary.
* The value is returned through a REF param (unchanged if null)
* Return value: true if attrib exists, false otherwise
*/
internal static bool GetAndRemoveBooleanAttribute(IDictionary directives,
string key, ref bool val) {
string s = Util.GetAndRemove(directives, key);
if (s == null)
return false;
val = GetBooleanAttribute(key, s);
return true;
}
// Parse a string attribute into a bool
internal static bool GetBooleanAttribute(string name, string value) {
try {
return bool.Parse(value);
}
catch {
throw new HttpException(
SR.GetString(SR.Invalid_boolean_attribute, name));
}
}
/*
* Get a string value from a dictionary, and convert it to integer. Throw an
* exception if it's not a valid positive integer string.
* However, don't complain about null, which simply means the value is not
* in the dictionary.
* The value is returned through a REF param (unchanged if null)
* Return value: true if attrib exists, false otherwise
*/
internal static bool GetAndRemoveNonNegativeIntegerAttribute(IDictionary directives,
string key, ref int val) {
string s = Util.GetAndRemove(directives, key);
if (s == null)
return false;
val = GetNonNegativeIntegerAttribute(key, s);
return true;
}
// Parse a string attribute into a non-negative integer
internal static int GetNonNegativeIntegerAttribute(string name, string value) {
int ret;
try {
ret = int.Parse(value, CultureInfo.InvariantCulture);
}
catch {
throw new HttpException(
SR.GetString(SR.Invalid_nonnegative_integer_attribute, name));
}
// Make sure it's not negative
if (ret < 0) {
throw new HttpException(
SR.GetString(SR.Invalid_nonnegative_integer_attribute, name));
}
return ret;
}
internal static bool GetAndRemovePositiveIntegerAttribute(IDictionary directives,
string key, ref int val) {
string s = Util.GetAndRemove(directives, key);
if (s == null)
return false;
try {
val = int.Parse(s, CultureInfo.InvariantCulture);
}
catch {
throw new HttpException(
SR.GetString(SR.Invalid_positive_integer_attribute, key));
}
// Make sure it's positive
if (val <= 0) {
throw new HttpException(
SR.GetString(SR.Invalid_positive_integer_attribute, key));
}
return true;
}
internal static object GetAndRemoveEnumAttribute(IDictionary directives, Type enumType,
string key) {
string s = Util.GetAndRemove(directives, key);
if (s == null)
return null;
return GetEnumAttribute(key, s, enumType);
}
internal static object GetEnumAttribute(string name, string value, Type enumType) {
return GetEnumAttribute(name, value, enumType, false);
}
internal static object GetEnumAttribute(string name, string value, Type enumType, bool allowMultiple) {
object val;
try {
// Don't allow numbers to be specified (ASURT 71851)
// Also, don't allow several values (e.g. "red,blue")
if (Char.IsDigit(value[0]) || value[0] == '-' || ((!allowMultiple) && (value.IndexOf(',') >= 0)))
throw new FormatException(SR.GetString(SR.EnumAttributeInvalidString, value, name, enumType.FullName));
val = Enum.Parse(enumType, value, true /*ignoreCase*/);
}
catch {
string names = null;
foreach (string n in Enum.GetNames(enumType)) {
if (names == null)
names = n;
else
names += ", " + n;
}
throw new HttpException(
SR.GetString(SR.Invalid_enum_attribute, name, names));
}
return val;
}
/*
* Return true iff the string is made of all white space characters
*/
internal static bool IsWhiteSpaceString(string s) {
return (s.Trim().Length == 0);
}
/*
* Return true iff the string contains some white space characters
*/
internal static bool ContainsWhiteSpace(string s) {
for (int i=s.Length-1; i>=0; i--) {
if (Char.IsWhiteSpace(s[i]))
return true;
}