File: ChartHttpHandler.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (2158 lines) | stat: -rw-r--r-- 83,252 bytes parent folder | download | duplicates (6)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158

//--------------------------------------------------------------------------------------------------------------------------
// <copyright company=Microsoft Corporation>
//   Copyright  Microsoft Corporation. All Rights Reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------------------
// @owner=alexgor, deliant
//==========================================================================================================================
//  File:		ChartHttpHandler.cs
//
//  Namespace:	Microsoft.Reporting.Chart.WebForms
//
//	Classes:	ChartHttpHandler
//
//  Purpose:	ChartHttpHandler is a static class which is responsible to handle with 
//              chart images, interactive images, scripts and other resources.
//              
//              
//	Reviewed:	DT
//	Reviewed:	deliant on 4/14/2011 			
//              MSRC#10470, VSTS#941768 http://vstfdevdiv:8080/web/wi.aspx?id=941768
//              Please review information associated with MSRC#10470 before making any changes to this file.
//              - Fixes:
//                  - Fixed Directory Traversal/Arbitrary File Read, Delete with malformed image key.
//                  - Honor HttpContext.Current.Trace.IsEnabled when generate and deliver chart trace info.
//                  - Handle empty guid parameter ("?g=") as invalid when enforcing privacy.
//                  - Replaced the privacy byte array comparison with custom check (otherwise posible EOS marker can return 0 length string).
//                  - Added fixed string to session key to avoid direct session access.
//
//   Added:  deliant on 4/48/2011 fix for VSTS: 3593 - ASP.Net chart under web farm exhibit fast performace degradation
//           Summary: Under large web farm setup ( ~16 processes and up) chart control image handler 
//                    soon starts to show performace degradation up to denial of service, when a file system is used as storage.
//            Issues: 
//                  - The image files in count over 2000 in one single folder causes exponentially growing slow response, 
//                    especially on the remote server. The fix places the Image files  in separate subfolders for each process. 
//                  - Private protection seeks and read several times in the image file istead reading the image at once 
//                    and then check for privacy marker.  Separate small network reads are expensive.
//                  - Due missing lock in initialization stage the chart lock files number can grow more that process max 
//                    number which can create abandon chart image files
//==========================================================================================================================

#region Namespaces

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.Caching;
using System.Collections;
using System.Web.Configuration;
using System.Resources;
using System.Reflection;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Web.Hosting;
using System.Web.SessionState;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.Security;
using System.Security.Cryptography;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;

#endregion //Namespaces

namespace System.Web.UI.DataVisualization.Charting
{
    /// <summary>
    /// ChartHttpHandler processes HTTP Web requests using, handles chart images, scripts and other resources.
    /// </summary>
#if ASPPERM_35
	[AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
#endif
    public class ChartHttpHandler : Page, IRequiresSessionState, IHttpHandler
    {

        #region Fields

        // flag that indicates whether this chart handler is installed
        private static bool _installed = false;
        
        // flag that indicates whether this chart handler is installed
        private static bool _installChecked = false;

        // storage settings
        private static ChartHttpHandlerSettings _parameters = null;
        

        // machine hash key which is part in chart image file name
        private static string _machineHash = "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture) + "_";

        // web gadren controller file. stays locked diring process lifetime.
		private static FileStream _controllerFileStream = null;
		private static string _controllerDirectory = null;
        private static object _initHandlerLock = new object();
        // used for storing Guid key in context;
        internal static string ContextGuidKey = "{89FA5660-BD13-4f1b-8C7C-355CEC92CC7E}";

        // web gadren controller file. stays locked diring process lifetime.
        private const string handlerCheckQry = "check";

        #endregion //Fields

        #region Consts
        
        internal const string ChartHttpHandlerName = "ChartImg.axd";
        internal const string ChartHttpHandlerAppSection = "ChartImageHandler";
        internal const string DefaultConfigSettings = @"storage=file;timeout=20;dir=c:\TempImageFiles\;";
        internal const string WebDevServerUseConfigSettings = "WebDevServerUseConfigSettings";
        #endregion //Consts

        #region Constructors

        /// <summary>
        /// Ensures that the handler is initialized.
        /// </summary>
        /// <param name="hardCheck">if set to <c>true</c> then will be thrown all excepitons.</param>
        private static void EnsureInitialized(bool hardCheck)
        {
            if (_installChecked)
            {
                return;
            }
            lock (_initHandlerLock)
            {
                if (_installChecked)
                {
                    return;
                }
                if (HttpContext.Current != null)
                {
                    try
                    {
                        using (TextWriter w = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            HttpContext.Current.Server.Execute(ChartHttpHandlerName + "?" + handlerCheckQry + "=0", w);
                        }
                        _installed = true;
                    }
                    catch (HttpException)
                    {
                        if (hardCheck) throw;
                    }
                    catch (SecurityException)
                    {
                        // under minimal configuration we assume that the hanlder is installed if app settings are present.
                        _installed = !String.IsNullOrEmpty(WebConfigurationManager.AppSettings[ChartHttpHandlerAppSection]);
                    }
                }
                if (_installed || hardCheck)
                {
                    InitializeControllerFile();
                }
                _installChecked = true;
            }
        }
        
        /// <summary>
        /// Initializes the storage settings
        /// </summary>
        //static ChartHttpHandler()
        private static ChartHttpHandlerSettings InitializeParameters()
        {

            ChartHttpHandlerSettings result = new ChartHttpHandlerSettings();
            if (HttpContext.Current != null)
            {
                // Read settings from config; use DefaultConfigSettings in case when setting is not found
                string configSettings = WebConfigurationManager.AppSettings[ChartHttpHandlerAppSection];
                if (String.IsNullOrEmpty(configSettings))
                    configSettings = DefaultConfigSettings;
                
                result = new ChartHttpHandlerSettings(configSettings);
            }
            else
            {
                result.PrepareDesignTime();
            }

            return result;
        }

        private static void ResetControllerStream()
        {
            if (_controllerFileStream != null)
                _controllerFileStream.Dispose();
            _controllerFileStream = null;
            _controllerDirectory = null;
        }

        private static void InitializeControllerFile()
        {
            if (Settings.StorageType == ChartHttpHandlerStorageType.File && _controllerFileStream == null)
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes("chart io controller file");
                // 2048 processes max.
                for (Int32 i = 0; i < 2048; i++)
                {
                    try
                    {
                        ResetControllerStream();
                        string controllerFileName = String.Format(CultureInfo.InvariantCulture, "{0}msc_cntr_{1}.txt", Settings.Directory, i);
                        _controllerDirectory = String.Format(CultureInfo.InvariantCulture, "charts_{0}", i);
                        _controllerFileStream = new System.IO.FileStream(controllerFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                        _controllerFileStream.Lock(0, data.Length);
                        _controllerFileStream.Write(data, 0, data.Length);
                        _machineHash = "_" + i + "_";
                        if (!Directory.Exists(Settings.Directory + _controllerDirectory))
                        {
                            Directory.CreateDirectory(Settings.Directory + _controllerDirectory);
                        }
                        else
                        {
                            TimeSpan lastWrite = DateTime.Now - Directory.GetLastWriteTime(Settings.Directory + _controllerDirectory);
                            if (lastWrite.Seconds < Settings.Timeout.Seconds)
                            {
                                continue;
                            }
                        }
                        return;
                    }
                    catch (IOException)
                    {
                        continue;
                    }
                    catch (Exception)
                    {
                        ResetControllerStream();
                        throw;
                    }
                }
                ResetControllerStream(); 
                throw new UnauthorizedAccessException(SR.ExceptionHttpHandlerTempDirectoryUnaccesible(Settings.Directory));
            }
        }
        
        #endregion //Constructors

        #region Methods

        #region ChartImage

        /// <summary>
        /// Processes the saved image.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>false if the image cannot be processed</returns>
        private static bool ProcessSavedChartImage(HttpContext context)
        {
            // image delivery doesn't depend if handler is intitilzed or not.
            String key = context.Request["i"];
            CurrentGuidKey = context.Request["g"];
            IChartStorageHandler handler = GetHandler();
            try
            {
                Byte[] data = handler.Load(KeyToUnc(key));
                if (data != null && data.Length > 0)
                {
                    context.Response.Charset = "";
                    context.Response.ContentType = GetMime(key);
                    context.Response.BinaryWrite(data);
                    Diagnostics.TraceWrite(SR.DiagnosticChartImageServed(key), null);
                    if (Settings.StorageType == ChartHttpHandlerStorageType.Session || Settings.DeleteAfterServicing)
                    {
                        handler.Delete(key);
                        Diagnostics.TraceWrite(SR.DiagnosticChartImageDeleted(key), null);
                    }
                    return true;
                }
                if (!(handler is DefaultImageHandler))
                {
                    // the default handler will write more detailed message
                    Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailNotFound), null);
                }
            }
            catch (NullReferenceException nre)
            {
                Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, String.Empty), nre);
                throw;
            }
            catch (IOException ioe)
            {
                Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, String.Empty), ioe);
                throw;
            }
            catch (SecurityException se)
            {
                Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, String.Empty), se);
                throw;
            }
            return false;
        }

        #endregion //ChartImage

        #region Utilities


        /// <summary>
        /// Gets or sets the current GUID key.
        /// </summary>
        /// <value>The current GUID key.</value>
        internal static string CurrentGuidKey
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    return (string)HttpContext.Current.Items[ContextGuidKey];
                }
                return String.Empty;
            }
            set
            {
                if (HttpContext.Current != null)
                {
                    if (String.IsNullOrEmpty(value))
                    {
                        HttpContext.Current.Items.Remove(ContextGuidKey);
                    }
                    else
                    {
                        HttpContext.Current.Items[ContextGuidKey] = value;
                    }
                }
            }
        }

        /// <summary>
        /// Gets the chart image handler interface reference.
        /// </summary>
        /// <returns></returns>
        private static IChartStorageHandler GetHandler()
        {
            return ChartHttpHandler.Settings.GetHandler();
        }

        /// <summary>
        /// Determines whether this instance is installed.
        /// </summary>
        internal static void EnsureInstalled()
        {
            EnsureInitialized(true);
            EnsureSessionIsClean();
        }

        /// <summary>
        /// Gets the handler URL.
        /// </summary>
        /// <returns></returns>
        private static String GetHandlerUrl()
        {
            // the handler have to be executed in current cxecution path in order to get proper user identity
            String appDir = Path.GetDirectoryName(HttpContext.Current.Request.CurrentExecutionFilePath ?? "").Replace("\\","/");
            if (!appDir.EndsWith("/", StringComparison.Ordinal))
            {
                appDir += "/";
            }
            return appDir + ChartHttpHandlerName + "?";
		}


        /// <summary>
        /// Gets the MIME type by resource url.
        /// </summary>
        /// <param name="resourceUrl">The resource URL.</param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Globalization", "CA1308",
            Justification = "No security decision is being made on the ToLowerInvariant() call. It is being used to ensure the file extension is lowercase")]
        private static String GetMime(String resourceUrl)
        {
            String ext = Path.GetExtension(resourceUrl);

            ext = ext.ToLowerInvariant();

            if (ext == ".js")
            {
                return "text/javascript";
            }
            else if (ext == ".htm")
            {
                return "text/html";
            }
            else if (".css,.html,.xml".IndexOf(ext, StringComparison.Ordinal) != -1)
            {
                return "text/" + ext.Substring(1);
            }
            else if (".jpg;.jpeg;.gif;.png;.emf".IndexOf(ext, StringComparison.Ordinal) != -1)
            {
                string fmt = ext.Substring(1).Replace("jpg", "jpeg");
                return "image/" + fmt;
            }
            return "text/plain";
        }

        /// <summary>
        /// Generates the chart image file name (key).
        /// </summary>
        /// <param name="ext">The ext.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        private static String GenerateKey(String ext)
        {
            String fmtKey = "chart" + _machineHash + "{0}." + ext;
            RingTimeTracker rt = RingTimeTrackerFactory.GetRingTracker(fmtKey);
			if (!String.IsNullOrEmpty(_controllerDirectory) && String.IsNullOrEmpty(Settings.FolderName))
			{
				return _controllerDirectory + @"\" + rt.GetNextKey();
			}
            return Settings.FolderName + rt.GetNextKey();
        }

		private static String KeyToUnc(String key)
		{
			if (!String.IsNullOrEmpty(key))
			{
				return key.Replace("/", @"\");
			}
			return key;
		}
		
		private static String KeyFromUnc(String key)
		{
			if (!String.IsNullOrEmpty(key))
			{
				return key.Replace(@"\", "/");
			}
			return key;
		}

        /// <summary>
        /// Gets a URL by specified request query, file key.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="fileKey">The file key.</param>
        /// <param name="currentGuid">The current GUID.</param>
        /// <returns></returns>
        private static String GetUrl(String query, String fileKey, string currentGuid)
        {
			return GetHandlerUrl() + query + "=" + KeyFromUnc(fileKey) + "&g=" + currentGuid;
        }

        /// <summary>
        /// Gets the image url.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="imageExt">The image extention.</param>
        /// <returns>Generated the image source URL</returns>
        [SuppressMessage("Microsoft.Globalization", "CA1308", 
            Justification="No security decision is being made on the ToLowerInvariant() call. It is being used to ensure the file extension is lowercase")]
        internal static String GetChartImageUrl(MemoryStream stream, String imageExt)
        {
            EnsureInitialized(true);
            // generates new guid
            string guidKey = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            // set new guid in context
            CurrentGuidKey = guidKey;
            
            Int32 tryCounts = 10;
            while (tryCounts > 0)
            {
                tryCounts--;
                try
                {
                    String key = GenerateKey(imageExt.ToLowerInvariant());
                    IChartStorageHandler handler = Settings.GetHandler();
                    handler.Save(key, stream.ToArray());
                    if (!(handler is DefaultImageHandler))
                    {
                        Diagnostics.TraceWrite(SR.DiagnosticChartImageSaved(key), null);
                    }
                    Settings.FolderName = String.Empty;
                    // clear guid so is not accessable out of the scope;
                    CurrentGuidKey = String.Empty;
                    return ChartHttpHandler.GetUrl("i", key, guidKey);
                }
                catch (IOException) { }
                catch { throw;}
            }
            throw new IOException(SR.ExceptionHttpHandlerCanNotSave);
        }

        /// <summary>
        /// Ensures the session is clean.
        /// </summary>
        private static void EnsureSessionIsClean()
        {
            if (!_installed) return;
            if (Settings.StorageType == ChartHttpHandlerStorageType.Session)
            {
                IChartStorageHandler handler = ChartHttpHandler.Settings.GetHandler();
                foreach (RingTimeTracker tracker in RingTimeTrackerFactory.OpenedRingTimeTrackers())
                {
                        tracker.ForEach(true, delegate(RingItem item)
                        {
                            if (item.InUse && String.CompareOrdinal(Settings.ReadSessionKey(), item.SessionID) == 0)
                            {
                                handler.Delete(tracker.GetKey(item));
                                Diagnostics.TraceWrite(SR.DiagnosticChartImageDeleted(tracker.GetKey(item)), null);
                                item.InUse = false;
                            }
                        }
                    );
                }
            }
        }
        #endregion //Utilities

        #region Diagnostics
        
        private static void DiagnosticWriteAll(HttpContext context)
        {
            HtmlTextWriter writer;
            using (TextWriter w = new StringWriter(CultureInfo.CurrentCulture))
            {
                
                if (context.Request.Browser != null)
                    writer = context.Request.Browser.CreateHtmlTextWriter(w);
                else
                    writer = new Html32TextWriter(w);
                writer.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\r<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\r");
                writer.Write("<head>\r\n");
                writer.Write("<style type=\"text/css\">\r\n body, span, table, td, th, div, caption {font-family: Tahoma, Arial, Helvetica, sans-serif;font-size: 10pt;} caption {background-color:Black; color: White; font-weight:bold; padding: 4px; text-align:left; } \r\n</style>\r\n");
                writer.Write("</head>\r\n<body style=\"width:978px\">\r\n");
                writer.Write("<h2>" + SR.DiagnosticHeader + "</h2>\r\n<hr/><br/>\n\r");
                DiagnosticWriteSettings(writer);
                writer.Write("<hr/>");
                DiagnosticWriteActivity(writer);
                writer.Write("<br/><hr/>\n\r<span>");
                try
                {
                    writer.Write(typeof(Chart).AssemblyQualifiedName);
                }
                catch ( SecurityException ) {}
                writer.Write("</span></body>\r\n</html>\r\n");
                context.Response.Write(w.ToString());
            }
        }

        private static void DiagnosticWriteSettings(HtmlTextWriter writer)
        {
            writer.Write("<h4>" + SR.DiagnosticSettingsConfig(WebConfigurationManager.AppSettings[ChartHttpHandlerAppSection]) + "</h4>");
            GridView grid = CreateGridView( true);
            grid.Caption = SR.DiagnosticSettingsHeader;
            BoundField field = new BoundField();
            field.DataField = "Key";
            field.HeaderText = SR.DiagnosticSettingsKey;
            field.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            grid.Columns.Add(field);

            field = new BoundField();
            field.DataField = "Value";
            field.HeaderText = SR.DiagnosticSettingsValue;
            field.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

            grid.Columns.Add(field);
            Dictionary<String, String> settings = new Dictionary<String, String>();
            
            settings.Add("StorageType", Settings.StorageType.ToString());
            settings.Add("TimeOut", Settings.Timeout.ToString());
            if (Settings.StorageType == ChartHttpHandlerStorageType.File)
            {
                settings.Add("Directory", Settings.Directory);
            }
            settings.Add("DeleteAfterServicing", Settings.DeleteAfterServicing.ToString());
            settings.Add("PrivateImages", Settings.PrivateImages.ToString());
            settings.Add("ImageOwnerKey", Settings.ImageOwnerKey.ToString());
            settings.Add("CustomHandlerName", Settings.CustomHandlerName);
            settings.Add(ChartHttpHandler.WebDevServerUseConfigSettings, String.Equals(Settings[ChartHttpHandler.WebDevServerUseConfigSettings], "true", StringComparison.OrdinalIgnoreCase).ToString());

            grid.DataSource = settings;
            grid.DataBind();
            
            grid.RenderControl(writer);
            
        }

        private static void DiagnosticWriteActivity(HtmlTextWriter writer)
        {
            GridView grid = CreateGridView( true);
            grid.Caption = SR.DiagnosticActivityHeader;
            BoundField field = new BoundField();
            field.DataField = "DateStamp";
            field.ItemStyle.VerticalAlign = VerticalAlign.Top;
            field.HeaderText = SR.DiagnosticActivityTime;
            field.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            field.HeaderStyle.Width = 150;
            grid.Columns.Add(field);

            field = new BoundField();
            field.DataField = "Url";
            field.HeaderText = SR.DiagnosticActivityMessage;
            field.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

            grid.Columns.Add(field);

            grid.RowDataBound += new GridViewRowEventHandler(DiagnosticActivityGrid_RowDataBound);

            grid.DataSource = Diagnostics.Messages;
            grid.DataBind();
            grid.RenderControl(writer);

        }

        static void DiagnosticActivityGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Diagnostics.HandlerPageTraceInfo currentInfo = (Diagnostics.HandlerPageTraceInfo)e.Row.DataItem;
                TableCell cell = e.Row.Cells[1];

                cell.Controls.Add(new Label() { Text = currentInfo.Verb + "," + currentInfo.Url });

                GridView grid = CreateGridView(false);
                grid.Style[HtmlTextWriterStyle.MarginLeft] = "20px";

                grid.ShowHeader = false;
                
                BoundField field = new BoundField();
                field.DataField = "Text";
                field.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
                grid.Columns.Add(field);

                grid.DataSource = currentInfo.Events;
                grid.DataBind();
                cell.Controls.Add(grid);
            }
        }

        private static GridView CreateGridView(bool withAlternateStyle)
        {
            GridView result = new GridView();

            result.AutoGenerateColumns = false;
            result.CellPadding = 4;
            result.Font.Names = new string[] { "Tahoma", "Ariel" };
            result.Font.Size = new FontUnit(10, UnitType.Point);
            result.BorderWidth = 0;
            result.GridLines = GridLines.None;
            result.Width = new Unit(100, UnitType.Percentage);

            if (withAlternateStyle)
            {
                result.AlternatingRowStyle.BackColor = Color.White;
                result.RowStyle.BackColor = ColorTranslator.FromHtml("#efefef");
                result.RowStyle.ForeColor = Color.Black;
                result.AlternatingRowStyle.ForeColor = Color.Black;
            }

            result.HeaderStyle.BackColor = Color.Gray;
            result.HeaderStyle.ForeColor = Color.White;
            result.HeaderStyle.Font.Bold = true;
            return result;
        }

        #endregion //Diagnostics

        #endregion //Methods

        #region Properties

        /// <summary>
        /// Gets the chart image storage settings registred in web.config file under ChartHttpHandler key.
        /// </summary>
        /// <value>The settings.</value>
        public static ChartHttpHandlerSettings Settings
        {
            get
            {
                if (_parameters == null)
                {
                    _parameters = InitializeParameters();
                }
                return _parameters;
            }
        }

        #endregion //Properties

        #region IHttpHandler Members

        /// <summary>
        /// Gets a value indicating whether the <see cref="T:System.Web.UI.Page"/> object can be reused.
        /// </summary>
        /// <value></value>
        /// <returns>false in all cases. </returns>
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            if (context.Request["i"] != null && ProcessSavedChartImage(context))
            {
                return;
            }
            else if (context.Request["trace"] != null && Diagnostics.IsTraceEnabled)
            {
                DiagnosticWriteAll(context);
                return;
            }
            else if (context.Request[handlerCheckQry] != null)
            {
                // handler execute test - returns no errors.
                return;
            }
            context.Response.StatusCode = 404;
            context.Response.StatusDescription = SR.ExceptionHttpHandlerImageNotFound;
        }

        #endregion

    }

    #region Enumerations

    /// <summary>
    /// Determines chart image storage medium
    /// </summary>
    public enum ChartHttpHandlerStorageType
    {
        /// <summary>
        /// Static into application memory
        /// </summary>
        InProcess,

        /// <summary>
        /// File system
        /// </summary>
        File,
        /// <summary>
        /// Using session as storage
        /// </summary>
        Session

    }
    /// <summary>
    /// Determines the image owner key for privacy protection.
    /// </summary>
    internal enum ImageOwnerKeyType
    {
        /// <summary>
        /// No privacy protection.
        /// </summary>
        None,
        /// <summary>
        /// The key will be automatically determined.
        /// </summary>
        Auto,
        /// <summary>
        /// The user name will be used as key.
        /// </summary>
        UserID,
        /// <summary>
        /// The AnonymousID will be used as key.
        /// </summary>
        AnonymousID,
        /// <summary>
        /// The SessionID will be used as key.
        /// </summary>
        SessionID
    }

    #endregion

    #region IChartStorageHandler interface

    /// <summary>
    /// Defines methods to manage rendered chart images in a storage.
    /// </summary>
    public interface IChartStorageHandler
    {
        /// <summary>
        /// Saves the data into external medium.
        /// </summary>
        /// <param name="key">Index key.</param>
        /// <param name="data">Image data.</param>
        void Save(String key, Byte[] data);


        /// <summary>
        /// Loads the data from external medium.
        /// </summary>
        /// <param name="key">Index key.</param>
        /// <returns>A byte array with image data</returns>
        Byte[] Load(String key);


        /// <summary>
        /// Deletes the data from external medium.
        /// </summary>
        /// <param name="key">Index key.</param>
        void Delete(String key);

        /// <summary>
        /// Checks for existence of data under specified key.
        /// </summary>
        /// <param name="key">Index key.</param>
        /// <returns>True if data exists under specified key</returns>
        bool Exists(String key);
    }

    #endregion

    #region ChartHttpHandlerSettings Class

    /// <summary>
    /// Enables access to the chart image storage settings.
    /// </summary>
#if ASPPERM_35
	[AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
#endif
    public class ChartHttpHandlerSettings
    {
        #region Fields

        private StorageSettingsCollection _ssCollection = new StorageSettingsCollection();
        
        private string _sesionKey   = "chartKey-" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);

        #endregion //Fields

        #region Properties

        private ChartHttpHandlerStorageType _chartImageStorage = ChartHttpHandlerStorageType.File;

        /// <summary>
        /// Gets or sets the chart image storage type.
        /// </summary>
        /// <value>The chart image storage.</value>
        public ChartHttpHandlerStorageType StorageType
        {
            get { return _chartImageStorage; }
            set { _chartImageStorage = value; }
        }

        private TimeSpan _timeout = TimeSpan.FromSeconds(30);

        /// <summary>
        /// Gets or sets the timeout.
        /// </summary>
        /// <value>The timeout.</value>
        public TimeSpan Timeout
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        private String _url = "~/";
        /// <summary>
        /// Gets or sets the URL.
        /// </summary>
        /// <value>The URL.</value>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
        public String Url
        {
            get { return _url; }
            set { _url = value; }
        }

        private String _directory = String.Empty;
        /// <summary>
        /// Gets or sets the directory.
        /// </summary>
        /// <value>The directory.</value>
        public String Directory
        {
            get { return _directory; }
            set { _directory = value; }
        }

        private const String _folderKeyName = "{5FF3B636-70BA-4180-B7C5-FDD77D8FA525}";
        /// <summary>
        /// Gets or sets the folder which will be used for storing images under <see cref="Directory"/>.
        /// </summary>
        /// <value>The folder name.</value>
        public String FolderName
        {
            get 
            {
                if (HttpContext.Current != null && HttpContext.Current.Items.Contains(_folderKeyName))
                {
                    return (string)HttpContext.Current.Items[_folderKeyName];
                }
                return String.Empty; 
            }
            set 
            { 
                if (!String.IsNullOrEmpty(value))
                {
                    if (!(value.EndsWith("/", StringComparison.Ordinal) || value.EndsWith("\\", StringComparison.Ordinal)))
                    {
                        value += "\\";
                    }
                    this.ValidateUri(value);
                }
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items[_folderKeyName] = value;
                }
            }
        }

        internal void ValidateUri(string key)
        {
            if (this.StorageType == ChartHttpHandlerStorageType.File)
            {
                FileInfo fi = new FileInfo(this.Directory + key);
                Uri directory = new Uri(this.Directory);
                Uri combinedDirectory = new Uri(fi.FullName); 
                if (directory.IsBaseOf(combinedDirectory))
                {
                    // it is fine.
                    return;
                }
                throw new UnauthorizedAccessException(SR.ExceptionHttpHandlerInvalidLocation);  
            }
        }

        private String _customHandlerName = typeof(DefaultImageHandler).FullName;
        /// <summary>
        /// Gets or sets the name of the custom handler.
        /// </summary>
        /// <value>The name of the custom handler.</value>
        public String CustomHandlerName
        {
            get { return _customHandlerName; }
            set { _customHandlerName = value; }
        }


        private Type _customHandlerType = null;
        /// <summary>
        /// Gets the type of the custom handler.
        /// </summary>
        /// <value>The type of the custom handler.</value>
        public Type HandlerType
        {
            get
            {
                if (this._customHandlerType == null)
                {
                    this._customHandlerType = Type.GetType(this.CustomHandlerName, true);
                }
                return this._customHandlerType;
            }
        }
        
        /// <summary>
        /// Gets a value indicating whether the handler will utilize private images.
        /// </summary>
        /// <value><c>true</c> if the handler will utilize private images; otherwise, <c>false</c>.</value>
        /// <remarks>
        /// When PrivateImages is set the handler will not return images out of session scope and 
        /// the client will not be able to download somebody else's images. This is default behavoiur.
        /// </remarks>
        public bool PrivateImages
        {
            get
            {
                return ImageOwnerKey != ImageOwnerKeyType.None;
            }
        }



        /// <summary>
        /// Gets a settings parameter with the specified name registred in web.config file under ChartHttpHandler key.
        /// </summary>
        /// <value></value>
        public string this[string name]
        {
            get
            {
                return this._ssCollection[name];
            }
        }
        
        #endregion //Properties

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="T:StorageSettings"/> class.
        /// </summary>
        internal ChartHttpHandlerSettings()
        {
            ImageOwnerKey = ImageOwnerKeyType.Auto;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:ChartHttpHandlerParameters"/> class.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        internal ChartHttpHandlerSettings(String parameters) : this()
        {
            this.ParseParams(parameters);
            this._ssCollection.SetReadOnly(true);
        }

        #endregion //Constructors

        #region Methods

        private ConstructorInfo _handlerConstructor = null;
        IChartStorageHandler _storageHandler = null;
        /// <summary>
        /// Creates the handler instance.
        /// </summary>
        /// <returns></returns>
        internal IChartStorageHandler GetHandler()
        {
            if (_storageHandler == null)
            {
                if (this._handlerConstructor == null)
                {
                    this.InspectHandlerLoader();
                }
                _storageHandler = this._handlerConstructor.Invoke(new object[0]) as IChartStorageHandler;
            }
            return _storageHandler;
        }

        /// <summary>
        /// Inspects the handler if it is valid.
        /// </summary>
        private void InspectHandlerLoader()
        {
            this._handlerConstructor = this.HandlerType.GetConstructor(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new Type[0],
                new ParameterModifier[0]);
            if (this._handlerConstructor == null)
            {
                throw new InvalidOperationException( SR.ExceptionHttpHandlerCanNotLoadType( this.HandlerType.FullName ));
            }
            if (this.GetHandler() == null)
            {
                throw new InvalidOperationException(SR.ExceptionHttpHandlerImageHandlerInterfaceUnsupported(ChartHttpHandler.Settings.HandlerType.FullName));
            }
        }

        /// <summary>
        /// Parses the params from web.config file key.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        private void ParseParams(String parameters)
        {
            if (!String.IsNullOrEmpty(parameters))
            {

                String[] pairs = parameters.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int index = 0; index < pairs.Length; index++)
                {
                    String item = pairs[index].Trim();
                    int eqPositon = item.IndexOf('=');
                    if (eqPositon != -1)
                    {
                        String name = item.Substring(0, eqPositon).Trim();
                        String value = item.Substring(eqPositon + 1).Trim();
                        this._ssCollection.Add(name, value);
                        if (name.StartsWith("stor", StringComparison.OrdinalIgnoreCase))
                        {
                            if (value.StartsWith("inproc", StringComparison.OrdinalIgnoreCase) || value.StartsWith("memory", StringComparison.OrdinalIgnoreCase))
                            {
                                this.StorageType = ChartHttpHandlerStorageType.InProcess;
                            }
                            else if (value.StartsWith("file", StringComparison.OrdinalIgnoreCase))
                            {
                                this.StorageType = ChartHttpHandlerStorageType.File;
                            }
                            else if (value.StartsWith("session", StringComparison.OrdinalIgnoreCase))
                            {
                                this.StorageType = ChartHttpHandlerStorageType.Session;
                            }
                            else
                            {
                                throw new System.Configuration.SettingsPropertyWrongTypeException(SR.ExceptionHttpHandlerParameterUnknown(name, value));
                            }
                        }
                        else if (name.StartsWith("url", StringComparison.OrdinalIgnoreCase))
                        {
                            if (!value.EndsWith("/", StringComparison.Ordinal))
                            {
                                value += "/";
                            }
                            this.Url = value;
                        }
                        else if (name.StartsWith("dir", StringComparison.OrdinalIgnoreCase))
                        {
                            this.Directory = value;
                        }
                        else if (name.StartsWith("time", StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                int seconds = Int32.Parse(value, CultureInfo.InvariantCulture);
                                if (seconds < -1)
                                {
                                    throw new System.Configuration.SettingsPropertyWrongTypeException(SR.ExceptionHttpHandlerValueInvalid);
                                }
                                if (seconds == -1)
                                {
                                    this.Timeout = TimeSpan.MaxValue;
                                }
                                else
                                {
                                    this.Timeout = TimeSpan.FromSeconds(seconds);
                                }
                            }
                            catch (Exception exception)
                            {
                                throw new System.Configuration.SettingsPropertyWrongTypeException(SR.ExceptionHttpHandlerTimeoutParameterInvalid, exception);
                            }
                        }
                        else if (name.StartsWith("handler", StringComparison.OrdinalIgnoreCase))
                        {
                            this.CustomHandlerName = value;
                        }
                        else if (name.StartsWith("privateImages", StringComparison.OrdinalIgnoreCase))
                        {
                            bool privateImg = true;
                            if (Boolean.TryParse(value, out privateImg) && !privateImg)
                            {
                                ImageOwnerKey = ImageOwnerKeyType.None;
                            }
                        }
                        else if (name.StartsWith("imageOwnerKey", StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                ImageOwnerKey = (ImageOwnerKeyType)Enum.Parse(typeof(ImageOwnerKeyType), value, true);
                            }
                            catch (ArgumentException)
                            {
                                throw new System.Configuration.SettingsPropertyWrongTypeException(SR.ExceptionHttpHandlerParameterInvalid(name, value));
                            }
                        }

                    }
                }
            }
            this.Inspect();
        }

        /// <summary>
        /// Determines whether web dev server is active.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if web dev server active; otherwise, <c>false</c>.
        /// </returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "GetCurrentProcess will fail if there is no access. This is by design. ")]
        // VSTS: 5176	Security annotation violations in System.Web.DataVisualization.dll
        [SecuritySafeCritical]
        private static bool IsWebDevActive()
        {
            try
            {
                Process process = Process.GetCurrentProcess();
                if (process.ProcessName.StartsWith("WebDev.WebServer", StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
                if (process.ProcessName.StartsWith("ii----press", StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            catch (SecurityException)
            {
            }
            return false;
        }
        /// <summary>
        /// Inspects and validates this instance after loading params.
        /// </summary>
        internal void Inspect()
        {
            switch (this.StorageType)
            {
                case ChartHttpHandlerStorageType.InProcess:

                    break;

                case ChartHttpHandlerStorageType.File:

                    if (IsWebDevActive() && !( String.Compare(this[ChartHttpHandler.WebDevServerUseConfigSettings], "true", StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        this.StorageType = ChartHttpHandlerStorageType.InProcess;
                        break;
                    }

                    if (String.IsNullOrEmpty(this.Url))
                    {
                        throw new ArgumentException(SR.ExceptionHttpHandlerUrlMissing);
                    }
                    
                    String fileDirectory = this.Directory;
                    if (String.IsNullOrEmpty(fileDirectory))
                    {
                        try
                        {
                            fileDirectory = HttpContext.Current.Server.MapPath(this.Url);
                        }
                        catch (Exception exception)
                        {
                            throw new InvalidOperationException(SR.ExceptionHttpHandlerUrlInvalid, exception);
                        }
                    }
                    fileDirectory = fileDirectory.Replace("/", "\\");
                    if (!fileDirectory.EndsWith("\\", StringComparison.Ordinal))
                    {
                        fileDirectory += "\\";
                    }

                    if (!System.IO.Directory.Exists(fileDirectory))
                    {
                        throw new DirectoryNotFoundException(SR.ExceptionHttpHandlerTempDirectoryInvalid(fileDirectory));
                    }
                    Exception thrown = null;
                    try
                    {
                        String testFileName = fileDirectory + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                        using (FileStream fileStream = File.Create(testFileName)) { }
                        File.Delete(testFileName);

                    }
                    catch (DirectoryNotFoundException exception)
                    {
                        thrown = exception;
                    }
                    catch (NotSupportedException exception)
                    {
                        thrown = exception;
                    }
                    catch (PathTooLongException exception)
                    {
                        thrown = exception;
                    }
                    catch (UnauthorizedAccessException exception)
                    {
                        thrown = exception;
                    }

                    if (thrown != null)
                    {
                        throw new UnauthorizedAccessException(SR.ExceptionHttpHandlerTempDirectoryUnaccesible(fileDirectory));
                    }

                    this.Directory = fileDirectory;
                    break;


            }
            if (!String.IsNullOrEmpty(this.CustomHandlerName))
            {
                this.InspectHandlerLoader();
            }
        }

        /// <summary>
        /// Prepares the design time params.
        /// </summary>
        internal void PrepareDesignTime()
        {
            this.StorageType = ChartHttpHandlerStorageType.File;
            this.Timeout = TimeSpan.FromSeconds(3); ;
            this.Url = Path.GetTempPath();
            this.Directory = Path.GetTempPath();
        }

        internal string ReadSessionKey()
        {
            if (HttpContext.Current.Session != null)
            {
                // initialize session (if is empty any postsequent request will have different id);
                if (HttpContext.Current.Session.IsNewSession)
                {
                    if (HttpContext.Current.Session.IsReadOnly)
                    {
                        return string.Empty;
                    }
                    HttpContext.Current.Session[this._sesionKey] = 0;
                }
                return HttpContext.Current.Session.SessionID;
            }
            return String.Empty;
        }
        
        internal string GetPrivacyKey( out ImageOwnerKeyType keyType )
        {
            if (ImageOwnerKey == ImageOwnerKeyType.None)
            {
                keyType = ImageOwnerKeyType.None;                
                return String.Empty;
            }
            if (HttpContext.Current != null)
            {
                switch (ImageOwnerKey)
                {
                    case ImageOwnerKeyType.Auto:
                        if (HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            keyType = ImageOwnerKeyType.UserID;
                            return HttpContext.Current.User.Identity.Name;
                        }
                        if (!String.IsNullOrEmpty(HttpContext.Current.Request.AnonymousID))
                        {
                            keyType = ImageOwnerKeyType.AnonymousID;
                            return HttpContext.Current.Request.AnonymousID;
                        }
                        string sessionId = ReadSessionKey();
                        keyType = String.IsNullOrEmpty(sessionId) ? ImageOwnerKeyType.None : ImageOwnerKeyType.SessionID;
                        return sessionId;

                    case ImageOwnerKeyType.UserID:
                        if (!HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            throw new InvalidOperationException(SR.ExceptionHttpHandlerPrivacyKeyInvalid("ImageOwnerKey", ImageOwnerKey.ToString()));
                        }
                        keyType = ImageOwnerKeyType.UserID;
                        return HttpContext.Current.User.Identity.Name;

                    case ImageOwnerKeyType.AnonymousID:
                        if (String.IsNullOrEmpty(HttpContext.Current.Request.AnonymousID))
                        {
                            throw new InvalidOperationException(SR.ExceptionHttpHandlerPrivacyKeyInvalid("ImageOwnerKey", ImageOwnerKey.ToString()));
                        }
                        keyType = ImageOwnerKeyType.AnonymousID;
                        return HttpContext.Current.Request.AnonymousID;

                    case ImageOwnerKeyType.SessionID:
                        if (HttpContext.Current.Session == null)
                        {
                            throw new InvalidOperationException(SR.ExceptionHttpHandlerPrivacyKeyInvalid("ImageOwnerKey", ImageOwnerKey.ToString()));
                        }
                        keyType = ImageOwnerKeyType.SessionID;
                        return ReadSessionKey();

                    default:
                        Debug.Fail("Unknown ImageOwnerKeyType.");
                        break;
                }
            }
            keyType = ImageOwnerKeyType.None;
            return string.Empty;
        }

        internal string PrivacyKey
        {
            get
            {
                ImageOwnerKeyType keyType;
                return GetPrivacyKey(out keyType);
            }
        }

        internal bool DeleteAfterServicing
        {
            get
            {
                // default, if is missing in config,  is true.
                return !(String.Compare(this["DeleteAfterServicing"], "false", StringComparison.OrdinalIgnoreCase) == 0); 
            }
        }

        /// <summary>
        /// Gets or sets the image owner key type.
        /// </summary>
        /// <value>The image owner key.</value>
        internal ImageOwnerKeyType ImageOwnerKey { get; set; }

        #endregion //Methods

        #region SettingsCollection Class

        private class StorageSettingsCollection : NameValueCollection
        {
            public StorageSettingsCollection()
                : base(StringComparer.OrdinalIgnoreCase)
            {
            }
            internal void SetReadOnly(bool flag)
            {
                this.IsReadOnly = flag;
            }
        }

        #endregion //SettingsCollection Class
    }

    #endregion ChartHttpHandlerParameters

    #region DefaultImageHandler Class

    /// <summary>
    /// Default implementation of ChartHttpHandler.IImageHandler interface
    /// </summary>
    internal class DefaultImageHandler : IChartStorageHandler
    {

        #region Fields
        // Hashtable for storage
        private static Hashtable _storageData = new Hashtable();
        // lock object
        private static ReaderWriterLock _rwl = new ReaderWriterLock();
        // max access timeout
        private const int accessTimeout = 10000;

        static string _privacyKeyName = "_pk";
        static byte[] _privacyMarker = (new Guid("332E3AB032904bceA82B249C25E65CB6")).ToByteArray();
        static string _sessionKeyPrefix = "chart-3ece47b3-9481-4b22-ab45-ab669972eb79";

        #endregion //Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="T:DefaultImageHandler"/> class.
        /// </summary>
        internal DefaultImageHandler()
        {
        }
        #endregion //Constructors

        #region Members
        /// <summary>
        /// Nots the type of the supported storage.
        /// </summary>
        /// <param name="settings">The settings.</param>
        private void NotSupportedStorageType(ChartHttpHandlerSettings settings)
        {
            throw new NotSupportedException( SR.ExceptionHttpHandlerStorageTypeUnsupported( settings.StorageType.ToString() ));
        }

        #endregion //Members

        #region Methods

        /// <summary>
        /// Returns privacy hash which will be save in the file.
        /// </summary>
        /// <returns>A byte array of hash data</returns>
        private static byte[] GetHashData()
        {
                string currentGuid = ChartHttpHandler.CurrentGuidKey;
                string sessionID = ChartHttpHandler.Settings.PrivacyKey;

                if (String.IsNullOrEmpty(sessionID))
                {
                    return new byte[0];
                }

                byte[] data = Encoding.UTF8.GetBytes(sessionID + "/" + currentGuid);

                using (SHA1 sha = new SHA1CryptoServiceProvider())
                {
                    return sha.ComputeHash(data);
                }

        }

        private static bool CompareBytes(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)  return false;
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i]) return false;
            }
            return true;
        }

        private static string GetSessionImageKey(string key)
        {
            // all session variables starts with _sessionKeyPrefix to avoid direct access to session by passing image key in Url query.
            return _sessionKeyPrefix + key;
        }

        #endregion //Methods

        #region ImageHandler Members

        /// <summary>
        /// Stores the data into external medium.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="data">The data.</param>
        void IChartStorageHandler.Save(String key, Byte[] data)
        {
            ChartHttpHandlerSettings settings = ChartHttpHandler.Settings;
            ImageOwnerKeyType imageOwnerKeyType = ImageOwnerKeyType.None;
            string privacyKey = settings.GetPrivacyKey(out imageOwnerKeyType);
            if (settings.StorageType == ChartHttpHandlerStorageType.InProcess)
            {
                _rwl.AcquireWriterLock(accessTimeout);
                try
                {
                    _storageData[key] = data;
                    if (settings.PrivateImages && !String.IsNullOrEmpty(privacyKey))
                    {
                        _storageData[key + _privacyKeyName] = privacyKey;
                        Diagnostics.TraceWrite( SR.DiagnosticChartImageSavedPrivate(key, imageOwnerKeyType.ToString()), null);
                    }
                    else
                        Diagnostics.TraceWrite(SR.DiagnosticChartImageSaved(key), null);
                }
                finally
                {
                    _rwl.ReleaseWriterLock();
                }
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.File)
            {
                using (FileStream stream = File.Create(settings.Directory + key))
                {
                    stream.Write(data, 0, data.Length);
                    if (settings.PrivateImages && !String.IsNullOrEmpty(privacyKey))
                    {
                        byte[] privacyData = GetHashData();
                        stream.Write(privacyData, 0, privacyData.Length);
                        // we will put a marker at the end of the file;
                        stream.Write(_privacyMarker, 0, _privacyMarker.Length);
                        Diagnostics.TraceWrite(SR.DiagnosticChartImageSavedPrivate(key, imageOwnerKeyType.ToString()), null);
                    }
                    else
                        Diagnostics.TraceWrite(SR.DiagnosticChartImageSaved(key), null);
                }
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.Session)
            {
                HttpContext.Current.Session[GetSessionImageKey(key)] = data;
                Diagnostics.TraceWrite(SR.DiagnosticChartImageSaved(key), null);
            }
            else this.NotSupportedStorageType(settings);
        }


        /// <summary>
        /// Retrieves the data from external medium.
        /// </summary>
        /// <param name="key">The key.</param>
        Byte[] IChartStorageHandler.Load( String key)
        {
            ChartHttpHandlerSettings settings = ChartHttpHandler.Settings;
            ImageOwnerKeyType imageOwnerKeyType = ImageOwnerKeyType.None;
            string privacyKey = settings.GetPrivacyKey(out imageOwnerKeyType);
            Byte[] data = new Byte[0];
            if (settings.StorageType == ChartHttpHandlerStorageType.InProcess)
            {
                 _rwl.AcquireReaderLock(accessTimeout);
                 try
                 {
                     if (settings.PrivateImages)
                     {
                         if (!String.IsNullOrEmpty(privacyKey))
                         {
                             if (!String.Equals((string)_storageData[key + _privacyKeyName], privacyKey, StringComparison.Ordinal))
                             {
                                 Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailPrivacyFail(imageOwnerKeyType.ToString())), null);
                                 return data;
                             }
                         }
                         else
                         {
                             if (!String.IsNullOrEmpty((string)_storageData[key + _privacyKeyName]))
                             {
                                 Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailPrivacyFail(imageOwnerKeyType.ToString())), null);
                                 return data;
                             }
                         }
                     }
                     data = (Byte[])_storageData[key];
                     if (data == null)
                     {
                         Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailNotFound), null);
                     }
                 }
                 finally
                 {
                     _rwl.ReleaseReaderLock();
                 }
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.File)
            {
                settings.ValidateUri(key);
                if (File.Exists(settings.Directory + key))
                {
                    using (FileStream fileStream = File.OpenRead(settings.Directory + key))
                    {
                        byte[] fileData = new byte[fileStream.Length];
                        fileStream.Read(fileData, 0, fileData.Length);
                        using (MemoryStream stream = new MemoryStream(fileData))
                        {
                            int streamCut = 0;
                            if (settings.PrivateImages)
                            {
                                // read the marker first
                                byte[] privacyMarkerStream = new Byte[_privacyMarker.Length];

                                streamCut += _privacyMarker.Length;
                                stream.Seek(stream.Length - streamCut, SeekOrigin.Begin);
                                stream.Read(privacyMarkerStream, 0, privacyMarkerStream.Length);

                                if (!String.IsNullOrEmpty(privacyKey))
                                {
                                    byte[] privacyData = GetHashData();
                                    streamCut += privacyData.Length;
                                    byte[] privacyDataFromStream = new Byte[privacyData.Length];
                                    stream.Seek(stream.Length - streamCut, SeekOrigin.Begin);
                                    stream.Read(privacyDataFromStream, 0, privacyDataFromStream.Length);

                                    if (!CompareBytes(privacyDataFromStream, privacyData))
                                    {
                                        Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailPrivacyFail(imageOwnerKeyType.ToString())), null);
                                        return data;
                                    }
                                }
                                else
                                {
                                    // this image is marked as private - check end return null if fails
                                    if (String.Equals(
                                        Encoding.Unicode.GetString(privacyMarkerStream),
                                        Encoding.Unicode.GetString(_privacyMarker),
                                        StringComparison.Ordinal))
                                    {
                                        Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailPrivacyFail(imageOwnerKeyType.ToString())), null);
                                        return data;
                                    }
                                    // its fine ( no user is stored )
                                    streamCut = 0;
                                }
                            }
                            stream.Seek(0, SeekOrigin.Begin);
                            data = new Byte[(int)stream.Length - streamCut];
                            stream.Read(data, 0, (int)data.Length);
                        }
                    }
                }
                else
                    Diagnostics.TraceWrite(SR.DiagnosticChartImageServedFail(key, SR.DiagnosticChartImageServedFailNotFound), null);
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.Session)
            {
                data = (Byte[])HttpContext.Current.Session[GetSessionImageKey(key)];
            }
            else this.NotSupportedStorageType(settings);
            return data;

        }


        /// <summary>
        /// Removes the data from external medium.
        /// </summary>
        /// <param name="key">The key.</param>
        void IChartStorageHandler.Delete(String key)
        {
            ChartHttpHandlerSettings settings = ChartHttpHandler.Settings;
            if (settings.StorageType == ChartHttpHandlerStorageType.InProcess)
            {

                _rwl.AcquireWriterLock(accessTimeout);
                try
                {
                    _storageData.Remove(key);
                    _storageData.Remove(key + _privacyKeyName);
                }
                finally
                {
                    _rwl.ReleaseWriterLock();
                }
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.File)
            {
                File.Delete(settings.Directory + key);
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.Session)
            {
                HttpContext.Current.Session.Remove(GetSessionImageKey(key));
            }
            else this.NotSupportedStorageType(settings);
        }

        /// <summary>
        /// Checks for existence the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        bool IChartStorageHandler.Exists(String key)
        {
            ChartHttpHandlerSettings settings = ChartHttpHandler.Settings;
            if (settings.StorageType == ChartHttpHandlerStorageType.InProcess)
            {
                _rwl.AcquireReaderLock(accessTimeout);
                try
                {
                    return _storageData.Contains(key);
                }
                finally
                {
                    _rwl.ReleaseReaderLock();
                }
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.File)
            {
                return File.Exists(settings.Directory + key);
            }
            else if (settings.StorageType == ChartHttpHandlerStorageType.Session)
            {
                return HttpContext.Current.Session[GetSessionImageKey(key)] is Byte[];
            }
            else this.NotSupportedStorageType(settings);
            return false;
        }

        #endregion

    }

    #endregion //DefaultImageHandler Class

    #region RingTimeTracker class

    /// <summary>
    /// RingItem contains time span of creation timedate and  index for key generation.
    /// </summary>
    internal class RingItem
    {
        internal Int32 Index;
        internal DateTime Created = DateTime.Now;
        internal string   SessionID = String.Empty;
        internal bool InUse;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:RingItem"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        internal RingItem( int index)
        {
            this.Index = index;
        }
    }
    /// <summary>
    /// RingTimeTracker is a helper class for generating keys and tracking RingItem. 
    /// Contains linked list queue and tracks exprired items.
    /// </summary>
    internal class RingTimeTracker
    {
        #region Fields
        // the item life span
        private TimeSpan _itemLifeTime = TimeSpan.FromSeconds(360);
        // last requested RingItem
        private LinkedListNode<RingItem> _current;
        // default key format to format names
        private String _keyFormat = String.Empty;
        // LinkedList with ring items
        private LinkedList<RingItem> _list = new LinkedList<RingItem>();
        // Record session ID
        private bool _recordSessionID = false;

        #endregion //Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="T:RingTimeTracker"/> class.
        /// </summary>
        /// <param name="itemLifeTime">The item life time.</param>
        /// <param name="keyFormat">The key format.</param>
        /// <param name="recordSessionID">if set to <c>true</c> the session ID will be recorded.</param>
        internal RingTimeTracker(TimeSpan itemLifeTime, String keyFormat, bool recordSessionID)
        {
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(keyFormat));
            this._itemLifeTime = itemLifeTime;
            this._keyFormat = keyFormat;
            this._list.AddLast(new RingItem(_list.Count));
            this._current = this._list.First;
            this._current.Value.Created = DateTime.Now - this._itemLifeTime - TimeSpan.FromSeconds(1);
            this._recordSessionID = recordSessionID;
        }

        #endregion //Constructors

        #region Methods

        

        /// <summary>
        /// Determines whether the specified item is expired.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="now">The now.</param>
        /// <returns>
        /// 	<c>true</c> if the specified item is expired; otherwise, <c>false</c>.
        /// </returns>
        internal bool IsExpired(RingItem item, DateTime now)
        {
            TimeSpan elapsed = (now - item.Created);
            return elapsed > this._itemLifeTime;
        }


        /// <summary>
        /// Gets the next key.
        /// </summary>
        /// <returns></returns>
        internal String GetNextKey()
        {
            DateTime now = DateTime.Now;
            lock (this)
            {
                if ( !this.IsExpired(this._current.Value, now))
                {
                    if (this._current.Next == null)
                    {
                        if (!this.IsExpired(this._list.First.Value, now))
                        {
                            this._list.AddLast(new RingItem(_list.Count));
                            this._current = this._list.Last;
                        }
                        else
                        {
                            this._current = this._list.First;
                        }
                    }
                    else
                    {
                        if (!this.IsExpired(this._current.Next.Value, now))
                        {
                            this._list.AddAfter(this._current, new RingItem(_list.Count));
                        }
                        this._current = this._current.Next;
                    }
                }
                this._current.Value.Created = now;
                if (this._recordSessionID)
                {
                    this._current.Value.SessionID = ChartHttpHandler.Settings.ReadSessionKey();
                    this._current.Value.InUse = true;
                }
                return this.GetCurrentKey();
            }
        }

        /// <summary>
        /// Gets the current key.
        /// </summary>
        /// <returns></returns>
        internal String GetCurrentKey()
        {
            return String.Format( CultureInfo.InvariantCulture, this._keyFormat, this._current.Value.Index);
        }

        /// <summary>
        /// Gets the key.
        /// </summary>
        /// <param name="ringItem">The ring item.</param>
        /// <returns></returns>
        internal String GetKey(RingItem ringItem)
        {
            return String.Format(CultureInfo.InvariantCulture, this._keyFormat, ringItem.Index);
        }

        /// <summary>
        /// Do Action for each item.
        /// </summary>
        /// <param name="onlyExpired">if set to <c>true</c> do action for only expired items.</param>
        /// <param name="action">The action.</param>
        public void ForEach(bool onlyExpired, Action<RingItem> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            DateTime now = DateTime.Now;
            lock (this)
            {
                foreach (RingItem item in this._list)
                {
                    if (onlyExpired)
                    {
                        if (this.IsExpired(item, now))
                        {
                            action(item);
                        }
                    }
                    else
                    {
                        action(item);
                    }
                }
            }
        }

        #endregion //Methods

    }
    #endregion //RingTracker class

    #region  RingTimeTrackerFactory Class

    /// <summary>
    /// RingTimeTrackerFactory contains static list of RingTimeTracker for each key formats
    /// </summary>
    internal static class RingTimeTrackerFactory
    {
        
        private static ListDictionary _ringTrackers = new ListDictionary();
        private static Object _lockObject = new Object();

        /// <summary>
        /// Gets the ring tracker by specified key format.
        /// </summary>
        /// <param name="keyFormat">The key format.</param>
        /// <returns></returns>
        internal static RingTimeTracker GetRingTracker(String keyFormat)
        {
            if (_ringTrackers.Contains(keyFormat))
            {
                return (RingTimeTracker)_ringTrackers[keyFormat];
            }
            lock (_lockObject)
            {
                if (_ringTrackers.Contains(keyFormat))
                {
                    return (RingTimeTracker)_ringTrackers[keyFormat];
                }
                RingTimeTracker result = new RingTimeTracker(ChartHttpHandler.Settings.Timeout, keyFormat,ChartHttpHandler.Settings.StorageType == ChartHttpHandlerStorageType.Session);
                _ringTrackers.Add(keyFormat, result);
                return result;
            }
        }

        internal static IList OpenedRingTimeTrackers()
        {
            lock (_lockObject)
            {
                return new ArrayList(_ringTrackers.Values);
            }
        }
        
    }

    #endregion  //RingTimeTrackerFactory Class

    #region Diagnostics class

    /// <summary>
    /// Contains helpres methods for diagnostics.
    /// </summary>
    internal static class Diagnostics
    {
        /// <summary>
        /// Trace category
        /// </summary>
        const string ChartCategory = "chart.handler";
        /// <summary>
        /// Name of context item which contain the current trace item 
        /// </summary>
        const string ContextID = "Trace-{89FA5660-BD13-4f1b-8C7C-355CEC92CC7E}";
        /// <summary>
        /// Used for syncronizing.
        /// </summary>
        static object _lockObject = new object();
        /// <summary>
        /// Limit of trace messages in the history.
        /// </summary>
        const int MessageLimit = 20;
        /// <summary>
        /// Collection of request messages.
        /// </summary>
        static List<HandlerPageTraceInfo> _messages = new List<HandlerPageTraceInfo>(MessageLimit);

        /// <summary>
        /// Contains request info
        /// </summary>
        public class HandlerPageTraceInfo
        {
            /// <summary>
            /// Events collection in this request.
            /// </summary>
            private List<ChartHandlerEvents> _events = new List<ChartHandlerEvents>();
            /// <summary>
            /// Initializes a new instance of the <see cref="HandlerPageTraceInfo"/> class.
            /// </summary>
            public HandlerPageTraceInfo()
            {
                if (HttpContext.Current != null)
                {
                    DateStamp = DateTime.Now;
                    if (HttpContext.Current.Request != null)
                    {
                        Url = HttpContext.Current.Request.Url.ToString();
                        Verb = HttpContext.Current.Request.HttpMethod;
                    }
                }
            }
            /// <summary>
            /// Gets or sets the date stamp.
            /// </summary>
            /// <value>The date stamp.</value>
            public DateTime DateStamp { get; private set; }
            /// <summary>
            /// Gets or sets the URL.
            /// </summary>
            /// <value>The URL.</value>
            public string Url { get; private set; }
            /// <summary>
            /// Gets or sets the verb.
            /// </summary>
            /// <value>The verb.</value>
            public string Verb { get; private set; }
            /// <summary>
            /// Gets the events.
            /// </summary>
            /// <value>The events.</value>
            public IList<ChartHandlerEvents> Events
            {
                get
                {
                    return _events.AsReadOnly();
                }
            }
            /// <summary>
            /// Adds a trace info item.
            /// </summary>
            /// <param name="message">The message.</param>
            /// <param name="errorInfo">The error info.</param>
            internal void AddTraceInfo(string message, string errorInfo)
            {
                lock (_events)
                {
                    _events.Add(new ChartHandlerEvents()
                        {
                            Message = message,
                            ErrorInfo = errorInfo
                        }
                     );
                }
            }
        }

        /// <summary>
        /// Contains an event in particural request.
        /// </summary>
        public class ChartHandlerEvents
        {
            /// <summary>
            /// Gets or sets the message.
            /// </summary>
            /// <value>The message.</value>
            public string Message { get; set; }
            /// <summary>
            /// Gets or sets the error info.
            /// </summary>
            /// <value>The error info.</value>
            public string ErrorInfo { get; set; }
            /// <summary>
            /// Gets the text.
            /// </summary>
            /// <value>The text.</value>
            public string Text { get { return Message + ErrorInfo; } }
        }

        /// <summary>
        /// Writes message in the trace.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="errorInfo">The error info.</param>
        internal static void TraceWrite( string message, Exception errorInfo)
        {
            if (IsTraceEnabled)
            {
                HttpContext.Current.Trace.Write(ChartCategory, message, errorInfo);
                if (CurrentTraceInfo != null)
                {
                    CurrentTraceInfo.AddTraceInfo(message, errorInfo != null ? errorInfo.ToString() : String.Empty);
                }
            }
        }

        /// <summary>
        /// Gets the current trace info.
        /// </summary>
        /// <value>The current trace info.</value>
        private static HandlerPageTraceInfo CurrentTraceInfo
        {
            get
            {
                lock (_lockObject)
                {
                    if (HttpContext.Current != null)
                    {
                        if (HttpContext.Current.Items[Diagnostics.ContextID] == null)
                        {
                            HandlerPageTraceInfo pageTrace = new HandlerPageTraceInfo();
                            _messages.Add(pageTrace);
                            if (_messages.Count > MessageLimit)
                            {
                                _messages.RemoveRange(0, _messages.Count - MessageLimit);
                            }
                            HttpContext.Current.Items[Diagnostics.ContextID] = pageTrace;
                        }
                        return (HandlerPageTraceInfo)HttpContext.Current.Items[Diagnostics.ContextID];
                    }
                }
                return null;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is trace enabled.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is trace enabled; otherwise, <c>false</c>.
        /// </value>
        internal static bool IsTraceEnabled
        {
            get
            {
                return HttpContext.Current != null && HttpContext.Current.Trace.IsEnabled;
            }
        }

        /// <summary>
        /// Gets the messages collection.
        /// </summary>
        /// <value>The messages.</value>
        internal static ReadOnlyCollection<HandlerPageTraceInfo> Messages
        {
            get
            {
                List<HandlerPageTraceInfo> result;
                lock (_lockObject)
                {
                    result = new List<HandlerPageTraceInfo>(_messages);
                }
                return result.AsReadOnly();
            }
        }
    }

    #endregion //Diagnostics class
}