File: SqlPersonalizationProvider.cs

package info (click to toggle)
mono 5.18.0.240%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,253,216 kB
  • sloc: cs: 10,925,936; xml: 2,804,987; ansic: 643,970; cpp: 120,384; perl: 59,272; asm: 21,383; sh: 20,162; makefile: 18,157; python: 4,715; pascal: 924; sql: 859; sed: 16; php: 1
file content (972 lines) | stat: -rw-r--r-- 43,488 bytes parent folder | download | duplicates (9)
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
//------------------------------------------------------------------------------
// <copyright file="SqlPersonalizationProvider.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls.WebParts {

    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Configuration.Provider;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.Web;
    using System.Web.DataAccess;
    using System.Web.Util;

    /// <devdoc>
    /// The provider used to access the personalization store for WebPart pages from a SQL Server
    /// database.
    /// </devdoc>
    public class SqlPersonalizationProvider : PersonalizationProvider {

        private enum ResetUserStateMode {
            PerInactiveDate,
            PerPaths,
            PerUsers
        }

        private const int maxStringLength = 256;

        private string _applicationName;
        private int    _commandTimeout;
        private string _connectionString;
        private int    _SchemaVersionCheck;

        /// <devdoc>
        /// Initializes an instance of SqlPersonalizationProvider.
        /// </devdoc>
        public SqlPersonalizationProvider() {
        }

        public override string ApplicationName {
            get {
                if (String.IsNullOrEmpty(_applicationName)) {
                    _applicationName = SecUtility.GetDefaultAppName();
                }
                return _applicationName;
            }
            set {
                if (value != null && value.Length > maxStringLength) {
                    throw new ProviderException(SR.GetString(SR.PersonalizationProvider_ApplicationNameExceedMaxLength, maxStringLength.ToString(CultureInfo.CurrentCulture)));
                }
                _applicationName = value;
            }
        }

        /// <devdoc>
        /// </devdoc>
        private SqlParameter CreateParameter(string name, SqlDbType dbType, object value) {
            SqlParameter param = new SqlParameter(name, dbType);

            param.Value = value;
            return param;
        }

        private PersonalizationStateInfoCollection FindSharedState(string path,
                                                                   int pageIndex,
                                                                   int pageSize,
                                                                   out int totalRecords) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            SqlDataReader reader = null;
            totalRecords = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_FindState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit));
                    parameter.Value = true;

                    parameters.AddWithValue("ApplicationName", ApplicationName);
                    parameters.AddWithValue("PageIndex", pageIndex);
                    parameters.AddWithValue("PageSize", pageSize);

                    SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    returnValue.Direction = ParameterDirection.ReturnValue;
                    parameters.Add(returnValue);

                    parameter = parameters.Add("Path", SqlDbType.NVarChar);
                    if (path != null) {
                        parameter.Value = path;
                    }

                    parameter = parameters.Add("UserName", SqlDbType.NVarChar);
                    parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime);

                    reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                    PersonalizationStateInfoCollection sharedStateInfoCollection = new PersonalizationStateInfoCollection();

                    if (reader != null) {
                        if (reader.HasRows) {
                            while(reader.Read()) {
                                string returnedPath = reader.GetString(0);

                                // Data can be null if there is no data associated with the path
                                DateTime lastUpdatedDate = (reader.IsDBNull(1)) ? DateTime.MinValue :
                                                                DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc);
                                int size = (reader.IsDBNull(2)) ? 0 : reader.GetInt32(2);
                                int userDataSize = (reader.IsDBNull(3)) ? 0 : reader.GetInt32(3);
                                int userCount = (reader.IsDBNull(4)) ? 0 : reader.GetInt32(4);
                                sharedStateInfoCollection.Add(new SharedPersonalizationStateInfo(
                                    returnedPath, lastUpdatedDate, size, userDataSize, userCount));
                            }
                        }

                        // The reader needs to be closed so return value can be accessed
                        // See MSDN doc for SqlParameter.Direction for details.
                        reader.Close();
                        reader = null;
                    }

                    // Set the total count at the end after all operations pass
                    if (returnValue.Value != null && returnValue.Value is int) {
                        totalRecords = (int)returnValue.Value;
                    }

                    return sharedStateInfoCollection;
                }
                finally {
                    if (reader != null) {
                        reader.Close();
                    }

                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }
        }

        public override PersonalizationStateInfoCollection FindState(PersonalizationScope scope,
                                                                     PersonalizationStateQuery query,
                                                                     int pageIndex, int pageSize,
                                                                     out int totalRecords) {
            PersonalizationProviderHelper.CheckPersonalizationScope(scope);
            PersonalizationProviderHelper.CheckPageIndexAndSize(pageIndex, pageSize);

            if (scope == PersonalizationScope.Shared) {
                string pathToMatch = null;
                if (query != null) {
                    pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength);
                }
                return FindSharedState(pathToMatch, pageIndex, pageSize, out totalRecords);
            }
            else {
                string pathToMatch = null;
                DateTime inactiveSinceDate = PersonalizationAdministration.DefaultInactiveSinceDate;
                string usernameToMatch = null;
                if (query != null) {
                    pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength);
                    inactiveSinceDate = query.UserInactiveSinceDate;
                    usernameToMatch = StringUtil.CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", false, maxStringLength);
                }

                return FindUserState(pathToMatch, inactiveSinceDate, usernameToMatch,
                                     pageIndex, pageSize, out totalRecords);
            }
        }

        private PersonalizationStateInfoCollection FindUserState(string path,
                                                                 DateTime inactiveSinceDate,
                                                                 string username,
                                                                 int pageIndex,
                                                                 int pageSize,
                                                                 out int totalRecords) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            SqlDataReader reader = null;
            totalRecords = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_FindState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit));
                    parameter.Value = false;

                    parameters.AddWithValue("ApplicationName", ApplicationName);
                    parameters.AddWithValue("PageIndex", pageIndex);
                    parameters.AddWithValue("PageSize", pageSize);

                    SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    returnValue.Direction = ParameterDirection.ReturnValue;
                    parameters.Add(returnValue);

                    parameter = parameters.Add("Path", SqlDbType.NVarChar);
                    if (path != null) {
                        parameter.Value = path;
                    }

                    parameter = parameters.Add("UserName", SqlDbType.NVarChar);
                    if (username != null) {
                        parameter.Value = username;
                    }

                    parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime);
                    if (inactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) {
                        parameter.Value = inactiveSinceDate.ToUniversalTime();
                    }

                    reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                    PersonalizationStateInfoCollection stateInfoCollection = new PersonalizationStateInfoCollection();

                    if (reader != null) {
                        if (reader.HasRows) {
                            while(reader.Read()) {
                                string returnedPath = reader.GetString(0);
                                DateTime lastUpdatedDate = DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc);
                                int size = reader.GetInt32(2);
                                string returnedUsername = reader.GetString(3);
                                DateTime lastActivityDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
                                stateInfoCollection.Add(new UserPersonalizationStateInfo(
                                                                returnedPath, lastUpdatedDate,
                                                                size, returnedUsername, lastActivityDate));
                            }
                        }

                        // The reader needs to be closed so return value can be accessed
                        // See MSDN doc for SqlParameter.Direction for details.
                        reader.Close();
                        reader = null;                        
                    }

                    // Set the total count at the end after all operations pass
                    if (returnValue.Value != null && returnValue.Value is int) {
                        totalRecords = (int)returnValue.Value;
                    }

                    return stateInfoCollection;
                }
                finally {
                    if (reader != null) {
                        reader.Close();
                    }

                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }
        }

        /// <devdoc>
        /// </devdoc>
        private SqlConnectionHolder GetConnectionHolder() {
            SqlConnection connection = null;
            SqlConnectionHolder connectionHolder = SqlConnectionHelper.GetConnection(_connectionString, true);

            if (connectionHolder != null) {
                connection = connectionHolder.Connection;
            }
            if (connection == null) {
                throw new ProviderException(SR.GetString(SR.PersonalizationProvider_CantAccess, Name));
            }

            return connectionHolder;
        }

        private int GetCountOfSharedState(string path) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            int count = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_GetCountOfState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int));
                    parameter.Direction = ParameterDirection.Output;

                    parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit));
                    parameter.Value = true;

                    parameters.AddWithValue("ApplicationName", ApplicationName);

                    parameter = parameters.Add("Path", SqlDbType.NVarChar);
                    if (path != null) {
                        parameter.Value = path;
                    }

                    parameter = parameters.Add("UserName", SqlDbType.NVarChar);
                    parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime);

                    command.ExecuteNonQuery();
                    parameter = command.Parameters[0];
                    if (parameter != null && parameter.Value != null && parameter.Value is Int32) {
                        count = (Int32) parameter.Value;
                    }
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }

            return count;
        }

        public override int GetCountOfState(PersonalizationScope scope, PersonalizationStateQuery query) {
            PersonalizationProviderHelper.CheckPersonalizationScope(scope);
            if (scope == PersonalizationScope.Shared) {
                string pathToMatch = null;
                if (query != null) {
                    pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength);
                }
                return GetCountOfSharedState(pathToMatch);
            }
            else {
                string pathToMatch = null;
                DateTime userInactiveSinceDate = PersonalizationAdministration.DefaultInactiveSinceDate;
                string usernameToMatch = null;
                if (query != null) {
                    pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength);
                    userInactiveSinceDate = query.UserInactiveSinceDate;
                    usernameToMatch = StringUtil.CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", false, maxStringLength);
                }
                return GetCountOfUserState(pathToMatch, userInactiveSinceDate, usernameToMatch);
            }
        }

        private int GetCountOfUserState(string path, DateTime inactiveSinceDate, string username) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            int count = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_GetCountOfState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int));
                    parameter.Direction = ParameterDirection.Output;

                    parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit));
                    parameter.Value = false;

                    parameters.AddWithValue("ApplicationName", ApplicationName);

                    parameter = parameters.Add("Path", SqlDbType.NVarChar);
                    if (path != null) {
                        parameter.Value = path;
                    }

                    parameter = parameters.Add("UserName", SqlDbType.NVarChar);
                    if (username != null) {
                        parameter.Value = username;
                    }

                    parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime);
                    if (inactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) {
                        parameter.Value = inactiveSinceDate.ToUniversalTime();
                    }

                    command.ExecuteNonQuery();
                    parameter = command.Parameters[0];
                    if (parameter != null && parameter.Value != null && parameter.Value is Int32) {
                        count = (Int32) parameter.Value;
                    }
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }

            return count;
        }

        public override void Initialize(string name, NameValueCollection configSettings) {
            HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level);

            // configSettings cannot be null because there are required settings needed below
            if (configSettings == null) {
                throw new ArgumentNullException("configSettings");
            }

            if (String.IsNullOrEmpty(name)) {
                name = "SqlPersonalizationProvider";
            }

            // description will be set from the base class' Initialize method
            if (string.IsNullOrEmpty(configSettings["description"])) {
                configSettings.Remove("description");
                configSettings.Add("description", SR.GetString(SR.SqlPersonalizationProvider_Description));
            }
            base.Initialize(name, configSettings);

            _SchemaVersionCheck = 0;

            // If not available, the default value is set in the get accessor of ApplicationName
            _applicationName = configSettings["applicationName"];
            if (_applicationName != null) {
                configSettings.Remove("applicationName");

                if (_applicationName.Length > maxStringLength) {
                    throw new ProviderException(SR.GetString(SR.PersonalizationProvider_ApplicationNameExceedMaxLength, maxStringLength.ToString(CultureInfo.CurrentCulture)));
                }
            }

            string connectionStringName = configSettings["connectionStringName"];
            if (String.IsNullOrEmpty(connectionStringName)) {
                throw new ProviderException(SR.GetString(SR.PersonalizationProvider_NoConnection));
            }
            configSettings.Remove("connectionStringName");

            string connectionString = SqlConnectionHelper.GetConnectionString(connectionStringName, true, true);
            if (String.IsNullOrEmpty(connectionString)) {
                throw new ProviderException(SR.GetString(SR.PersonalizationProvider_BadConnection, connectionStringName));
            }
            _connectionString = connectionString;

            _commandTimeout = SecUtility.GetIntValue(configSettings, "commandTimeout", -1, true, 0);
            configSettings.Remove("commandTimeout");

            if (configSettings.Count > 0) {
                string invalidAttributeName = configSettings.GetKey(0);
                throw new ProviderException(SR.GetString(SR.PersonalizationProvider_UnknownProp, invalidAttributeName, name));
            }
        }

        private void CheckSchemaVersion( SqlConnection connection )
        {
            string[] features = { "Personalization" };
            string   version  = "1";

            SecUtility.CheckSchemaVersion( this,
                                           connection,
                                           features,
                                           version,
                                           ref _SchemaVersionCheck );
        }

        /// <devdoc>
        /// </devdoc>
        private byte[] LoadPersonalizationBlob(SqlConnection connection, string path, string userName) {
            Debug.Assert(connection != null);
            Debug.Assert(!String.IsNullOrEmpty(path));

            SqlCommand command;

            if (userName != null) {
                command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_GetPageSettings", connection);
            }
            else {
                command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_GetPageSettings", connection);
            }

            SetCommandTypeAndTimeout(command);
            command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName));
            command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path));
            if (userName != null) {
                command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName));
                command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));
            }

            SqlDataReader reader = null;
            try {
                reader = command.ExecuteReader(CommandBehavior.SingleRow);
                if (reader.Read()) {
                    int length = (int)reader.GetBytes(0, 0, null, 0, 0);
                    byte[] state = new byte[length];

                    reader.GetBytes(0, 0, state, 0, length);
                    return state;
                }
            }
            finally {
                if (reader != null) {
                    reader.Close();
                }
            }

            return null;
        }

        /// <internalonly />
        protected override void LoadPersonalizationBlobs(WebPartManager webPartManager, string path, string userName, ref byte[] sharedDataBlob, ref byte[] userDataBlob) {
            sharedDataBlob = null;
            userDataBlob = null;

            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;

                    CheckSchemaVersion( connection );

                    sharedDataBlob = LoadPersonalizationBlob(connection, path, null);
                    if (!String.IsNullOrEmpty(userName)) {
                        userDataBlob = LoadPersonalizationBlob(connection, path, userName);
                    }
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }
        }

        /// <devdoc>
        /// </devdoc>
        private void ResetPersonalizationState(SqlConnection connection, string path, string userName) {
            Debug.Assert(connection != null);
            Debug.Assert(!String.IsNullOrEmpty(path));

            SqlCommand command;

            if (userName != null) {
                command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_ResetPageSettings", connection);
            }
            else {
                command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_ResetPageSettings", connection);
            }

            SetCommandTypeAndTimeout(command);
            command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
            command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path));
            if (userName != null) {
                command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName));
                command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));
            }

            command.ExecuteNonQuery();
        }

        /// <internalonly />
        protected override void ResetPersonalizationBlob(WebPartManager webPartManager, string path, string userName) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;

                    CheckSchemaVersion( connection );

                    ResetPersonalizationState(connection, path, userName);
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }
        }

        private int ResetAllState(PersonalizationScope scope) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            int count = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_DeleteAllState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit));
                    parameter.Value = (scope == PersonalizationScope.Shared);

                    parameters.AddWithValue("ApplicationName", ApplicationName);

                    parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int));
                    parameter.Direction = ParameterDirection.Output;

                    command.ExecuteNonQuery();
                    parameter = command.Parameters[2];
                    if (parameter != null && parameter.Value != null && parameter.Value is Int32) {
                        count = (Int32) parameter.Value;
                    }
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }

            return count;
        }

        private int ResetSharedState(string[] paths) {
            int resultCount = 0;

            if (paths == null) {
                resultCount = ResetAllState(PersonalizationScope.Shared);
            }
            else {
                SqlConnectionHolder connectionHolder = null;
                SqlConnection connection = null;

                // Extra try-catch block to prevent elevation of privilege attack via exception filter
                try {
                    bool beginTranCalled = false;
                    try {
                        connectionHolder = GetConnectionHolder();
                        connection = connectionHolder.Connection;
                        Debug.Assert(connection != null);

                        CheckSchemaVersion( connection );

                        SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_ResetSharedState", connection);
                        SetCommandTypeAndTimeout(command);
                        SqlParameterCollection parameters = command.Parameters;

                        SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int));
                        parameter.Direction = ParameterDirection.Output;

                        parameters.AddWithValue("ApplicationName", ApplicationName);

                        parameter = parameters.Add("Path", SqlDbType.NVarChar);
                        foreach (string path in paths) {
                            if (!beginTranCalled && paths.Length > 1) {
                                (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery();
                                beginTranCalled = true;
                            }

                            parameter.Value = path;
                            command.ExecuteNonQuery();
                            SqlParameter countParam = command.Parameters[0];
                            if (countParam != null && countParam.Value != null && countParam.Value is Int32) {
                                resultCount += (Int32) countParam.Value;
                            }
                        }

                        if (beginTranCalled) {
                            (new SqlCommand("COMMIT TRANSACTION", connection)).ExecuteNonQuery();
                            beginTranCalled = false;
                        }
                    }
                    catch {
                        if (beginTranCalled) {
                            (new SqlCommand("ROLLBACK TRANSACTION", connection)).ExecuteNonQuery();
                            beginTranCalled = false;
                        }
                        throw;
                    }
                    finally {
                       if (connectionHolder != null) {
                            connectionHolder.Close();
                            connectionHolder = null;
                        }
                    }
                }
                catch {
                    throw;
                }
            }

            return resultCount;
        }

        public override int ResetUserState(string path, DateTime userInactiveSinceDate) {
            path = StringUtil.CheckAndTrimString(path, "path", false, maxStringLength);
            string [] paths = (path == null) ? null : new string [] {path};
            return ResetUserState(ResetUserStateMode.PerInactiveDate,
                                  userInactiveSinceDate, paths, null);
        }

        public override int ResetState(PersonalizationScope scope, string[] paths, string[] usernames) {
            PersonalizationProviderHelper.CheckPersonalizationScope(scope);
            paths = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(paths, "paths", false, false, maxStringLength);
            usernames = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(usernames, "usernames", false, true, maxStringLength);

            if (scope == PersonalizationScope.Shared) {
                PersonalizationProviderHelper.CheckUsernamesInSharedScope(usernames);
                return ResetSharedState(paths);
            }
            else {
                PersonalizationProviderHelper.CheckOnlyOnePathWithUsers(paths, usernames);
                return ResetUserState(paths, usernames);
            }
        }

        private int ResetUserState(string[] paths, string[] usernames) {
            int count = 0;
            bool hasPaths = !(paths == null || paths.Length == 0);
            bool hasUsernames = !(usernames == null || usernames.Length == 0);

            if (!hasPaths && !hasUsernames) {
                count = ResetAllState(PersonalizationScope.User);
            }
            else if (!hasUsernames) {
                count = ResetUserState(ResetUserStateMode.PerPaths,
                                       PersonalizationAdministration.DefaultInactiveSinceDate,
                                       paths, usernames);
            }
            else {
                count = ResetUserState(ResetUserStateMode.PerUsers,
                                       PersonalizationAdministration.DefaultInactiveSinceDate,
                                       paths, usernames);
            }

            return count;
        }

        private int ResetUserState(ResetUserStateMode mode,
                                   DateTime userInactiveSinceDate,
                                   string[] paths,
                                   string[] usernames) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;
            int count = 0;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                bool beginTranCalled = false;
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;
                    Debug.Assert(connection != null);

                    CheckSchemaVersion( connection );

                    SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_ResetUserState", connection);
                    SetCommandTypeAndTimeout(command);
                    SqlParameterCollection parameters = command.Parameters;

                    SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int));
                    parameter.Direction = ParameterDirection.Output;

                    parameters.AddWithValue("ApplicationName", ApplicationName);

                    string firstPath = (paths != null && paths.Length > 0) ? paths[0] : null;

                    if (mode == ResetUserStateMode.PerInactiveDate) {
                        if (userInactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) {
                            // Special note: DateTime object cannot be added to collection
                            // via AddWithValue for some reason.
                            parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime);
                            parameter.Value = userInactiveSinceDate.ToUniversalTime();
                        }

                        if (firstPath != null) {
                            parameters.AddWithValue("Path", firstPath);
                        }

                        command.ExecuteNonQuery();
                        SqlParameter countParam = command.Parameters[0];
                        if (countParam != null && countParam.Value != null && countParam.Value is Int32) {
                            count = (Int32) countParam.Value;
                        }
                    }
                    else if (mode == ResetUserStateMode.PerPaths) {
                        Debug.Assert(paths != null);
                        parameter = parameters.Add("Path", SqlDbType.NVarChar);
                        foreach (string path in paths) {
                            if (!beginTranCalled && paths.Length > 1) {
                                (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery();
                                beginTranCalled = true;
                            }

                            parameter.Value = path;
                            command.ExecuteNonQuery();
                            SqlParameter countParam = command.Parameters[0];
                            if (countParam != null && countParam.Value != null && countParam.Value is Int32) {
                                count += (Int32) countParam.Value;
                            }
                        }
                    }
                    else {
                        Debug.Assert(mode == ResetUserStateMode.PerUsers);
                        if (firstPath != null) {
                            parameters.AddWithValue("Path", firstPath);
                        }

                        parameter = parameters.Add("UserName", SqlDbType.NVarChar);
                        foreach (string user in usernames) {
                            if (!beginTranCalled && usernames.Length > 1) {
                                (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery();
                                beginTranCalled = true;
                            }

                            parameter.Value = user;
                            command.ExecuteNonQuery();
                            SqlParameter countParam = command.Parameters[0];
                            if (countParam != null && countParam.Value != null && countParam.Value is Int32) {
                                count += (Int32) countParam.Value;
                            }
                        }
                    }

                    if (beginTranCalled) {
                        (new SqlCommand("COMMIT TRANSACTION", connection)).ExecuteNonQuery();
                        beginTranCalled = false;
                    }
                }
                catch {
                    if (beginTranCalled) {
                        (new SqlCommand("ROLLBACK TRANSACTION", connection)).ExecuteNonQuery();
                        beginTranCalled = false;
                    }
                    throw;
                }
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }

            return count;
        }

        /// <devdoc>
        /// </devdoc>
        private void SavePersonalizationState(SqlConnection connection, string path, string userName, byte[] state) {
            Debug.Assert(connection != null);
            Debug.Assert(!String.IsNullOrEmpty(path));
            Debug.Assert((state != null) && (state.Length != 0));
            SqlCommand command;

            if (userName != null) {
                command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_SetPageSettings", connection);
            }
            else {
                command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_SetPageSettings", connection);
            }

            SetCommandTypeAndTimeout(command);
            command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
            command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path));
            command.Parameters.Add(CreateParameter("@PageSettings", SqlDbType.Image, state));
            command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));
            if (userName != null) {
                command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName));
            }

            command.ExecuteNonQuery();
        }

        /// <internalonly />
        protected override void SavePersonalizationBlob(WebPartManager webPartManager, string path, string userName, byte[] dataBlob) {
            SqlConnectionHolder connectionHolder = null;
            SqlConnection connection = null;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    connectionHolder = GetConnectionHolder();
                    connection = connectionHolder.Connection;

                    CheckSchemaVersion( connection );

                    SavePersonalizationState(connection, path, userName, dataBlob);
                } catch(SqlException  sqlEx) {
                    // Check if it failed due to duplicate user name
                    if (userName != null && (sqlEx.Number == 2627 || sqlEx.Number == 2601 || sqlEx.Number == 2512)) {
                        // Try again, because it failed first time with duplicate user name
                        SavePersonalizationState(connection, path, userName, dataBlob);
                    } else {
                        throw;
                    }
                } 
                finally {
                    if (connectionHolder != null) {
                        connectionHolder.Close();
                        connectionHolder = null;
                    }
                }
            }
            catch {
                throw;
            }
        }

        private void SetCommandTypeAndTimeout(SqlCommand command) {
            command.CommandType = CommandType.StoredProcedure;
            if (_commandTimeout != -1) {
                command.CommandTimeout = _commandTimeout;
            }
        }
    }
}