Ms 57 Solved Assignment Cs

//------------------------------------------------------------------------------// <copyright file="DataSet.cs" company="Microsoft">// Copyright (c) Microsoft Corporation. All rights reserved.// </copyright>// <owner current="true" primary="true">Microsoft</owner>// <owner current="true" primary="false">Microsoft</owner>//------------------------------------------------------------------------------namespace System.Data { using System; using System.Text; using System.Runtime.Serialization; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Xml; using System.Xml.Serialization; using System.Xml.Serialization.Advanced; using System.Xml.Schema; using System.Runtime.Serialization.Formatters.Binary; //Binary Formatterusing System.CodeDom; using System.CodeDom.Compiler; using System.Configuration; using System.Data.Common; using System.Runtime.Versioning; using System.Runtime.CompilerServices; ///<devdoc>///<para>/// Represents an in-memory cache of data.///</para>///</devdoc> [ ResDescriptionAttribute(Res.DataSetDescr), DefaultProperty("DataSetName"), ToolboxItem("Microsoft.VSDesigner.Data.VS.DataSetToolboxItem, " + AssemblyRef.MicrosoftVSDesigner), Designer("Microsoft.VSDesigner.Data.VS.DataSetDesigner, " + AssemblyRef.MicrosoftVSDesigner), Serializable, XmlSchemaProvider("GetDataSetSchema"), XmlRoot("DataSet") ] public classDataSet : MarshalByValueComponent, System.ComponentModel.IListSource, IXmlSerializable, ISupportInitializeNotification, ISerializable { privateDataViewManagerdefaultViewManager; // Public Collectionsprivate readonlyDataTableCollectiontableCollection; private readonlyDataRelationCollectionrelationCollection; internalPropertyCollectionextendedProperties = null; private stringdataSetName = "NewDataSet"; private string_datasetPrefix = String.Empty; internal stringnamespaceURI = string.Empty; private boolenforceConstraints = true; private constStringKEY_XMLSCHEMA = "XmlSchema"; private constStringKEY_XMLDIFFGRAM = "XmlDiffGram"; // globalization stuffprivate bool_caseSensitive; privateCultureInfo_culture; private bool_cultureUserSet; // Internal definitionsinternal boolfInReadXml = false; internal boolfInLoadDiffgram = false; internal boolfTopLevelTable = false; internal boolfInitInProgress = false; internal boolfEnableCascading = true; internal boolfIsSchemaLoading = false; private boolfBoundToDocument; // for XmlDataDocument// EventsprivatePropertyChangedEventHandleronPropertyChangingDelegate; privateMergeFailedEventHandleronMergeFailed; privateDataRowCreatedEventHandleronDataRowCreated; // Internal for XmlDataDocument onlyprivateDataSetClearEventhandleronClearFunctionCalled; // Internal for XmlDataDocument onlyprivate System.EventHandleronInitialized; internal readonly staticDataTable[] zeroTables = newDataTable[0]; internal stringmainTableName = ""; //default remoting format is XMLprivateSerializationFormat_remotingFormat = SerializationFormat.Xml; private object_defaultViewManagerLock = newObject(); private static int_objectTypeCount; // Bid counterprivate readonly int_objectID = System.Threading.Interlocked.Increment(ref_objectTypeCount); private staticXmlSchemaComplexTypeschemaTypeForWSDL = null; internal boolUseDataSetSchemaOnly; // UseDataSetSchemaOnly , for YUKONinternal boolUdtIsWrapped; // if UDT is wrapped , for YUKON///<devdoc>///<para>Initializes a new instance of the <seecref='System.Data.DataSet'/> class.</para>///</devdoc>publicDataSet() { GC.SuppressFinalize(this); Bid.Trace("<ds.DataSet.DataSet|API> %d#\n", ObjectID); // others will call this constr// Set default localethis.tableCollection = newDataTableCollection(this); this.relationCollection = newDataRelationCollection.DataSetRelationCollection(this); _culture = CultureInfo.CurrentCulture; // Set default locale } ///<devdoc>///<para>Initializes a new instance of a <seecref='System.Data.DataSet'/>/// class with the given name.</para>///</devdoc>publicDataSet(stringdataSetName) : this() { this.DataSetName = dataSetName; } [ DefaultValue(SerializationFormat.Xml) ] publicSerializationFormatRemotingFormat { get { return_remotingFormat; } set { if (value != SerializationFormat.Binary && value != SerializationFormat.Xml) { throwExceptionBuilder.InvalidRemotingFormat(value); } _remotingFormat = value; // this property is inherited to DataTable from DataSet.So we set this value to DataTable alsofor (inti = 0; i < Tables.Count; i++) { Tables[i].RemotingFormat = value; } } } [BrowsableAttribute(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtualSchemaSerializationModeSchemaSerializationMode { //Typed DataSet calls into thisget { returnSchemaSerializationMode.IncludeSchema; } set { if (value != SchemaSerializationMode.IncludeSchema) { throwExceptionBuilder.CannotChangeSchemaSerializationMode(); } } } // Check whether the stream is binary serialized.// 'static' function that consumes SerializationInfoprotected boolIsBinarySerialized(SerializationInfoinfo, StreamingContextcontext) {// mainly for typed DS// our default remoting format is XMLSerializationFormatremotingFormat = SerializationFormat.Xml; SerializationInfoEnumeratore = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name == "DataSet.RemotingFormat") {//DataSet.RemotingFormat does not exist in V1/V1.1 versionsremotingFormat = (SerializationFormat)e.Value; break; } } return (remotingFormat == SerializationFormat.Binary); } // Should Schema be included during Serialization// 'static' function that consumes SerializationInfoprotectedSchemaSerializationModeDetermineSchemaSerializationMode(SerializationInfoinfo, StreamingContextcontext) { //Typed DataSet calls into thisSchemaSerializationModeschemaSerializationMode = SchemaSerializationMode.IncludeSchema; SerializationInfoEnumeratore = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name == "SchemaSerializationMode.DataSet") { //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versionsschemaSerializationMode = (SchemaSerializationMode)e.Value; break; } } returnschemaSerializationMode; } protectedSchemaSerializationModeDetermineSchemaSerializationMode(XmlReaderreader) { //Typed DataSet calls into thisSchemaSerializationModeschemaSerializationMode = SchemaSerializationMode.IncludeSchema; reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Element) { if (reader.HasAttributes) { stringattribValue = reader.GetAttribute(Keywords.MSD_SCHEMASERIALIZATIONMODE, Keywords.MSDNS); if ((String.Compare(attribValue, Keywords.MSD_EXCLUDESCHEMA, StringComparison.OrdinalIgnoreCase) == 0)) { schemaSerializationMode = SchemaSerializationMode.ExcludeSchema; } else if ((String.Compare(attribValue, Keywords.MSD_INCLUDESCHEMA, StringComparison.OrdinalIgnoreCase) == 0)) { schemaSerializationMode = SchemaSerializationMode.IncludeSchema; } else if (attribValue != null) { // if attrib does not exist, then don't throwthrowExceptionBuilder.InvalidSchemaSerializationMode(typeof(SchemaSerializationMode), attribValue); } } } returnschemaSerializationMode; } // Deserialize all the tables data of the dataset from binary/xml stream.// 'instance' method that consumes SerializationInfoprotected voidGetSerializationData(SerializationInfoinfo, StreamingContextcontext) {// mainly for typed DSSerializationFormatremotingFormat = SerializationFormat.Xml; SerializationInfoEnumeratore = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name == "DataSet.RemotingFormat") { //DataSet.RemotingFormat does not exist in V1/V1.1 versionsremotingFormat = (SerializationFormat)e.Value; break; } } DeserializeDataSetData(info, context, remotingFormat); } // Deserialize all the tables schema and data of the dataset from binary/xml stream.protectedDataSet(SerializationInfoinfo, StreamingContextcontext) : this(info, context, true) { } protectedDataSet(SerializationInfoinfo, StreamingContextcontext, boolConstructSchema) : this() { SerializationFormatremotingFormat = SerializationFormat.Xml; SchemaSerializationModeschemaSerializationMode = SchemaSerializationMode.IncludeSchema; SerializationInfoEnumeratore = info.GetEnumerator(); while (e.MoveNext()) { switch (e.Name) { case"DataSet.RemotingFormat": //DataSet.RemotingFormat does not exist in V1/V1.1 versionsremotingFormat = (SerializationFormat)e.Value; break; case"SchemaSerializationMode.DataSet": //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versionsschemaSerializationMode = (SchemaSerializationMode)e.Value; break; } } if (schemaSerializationMode == SchemaSerializationMode.ExcludeSchema) { InitializeDerivedDataSet(); } // adding back this check will fix typed dataset XML remoting, but we have to fix case that // a class inherits from DataSet and just relies on DataSet to deserialize (see SQL BU DT 374717)// to fix that case also, we need to add a flag and add it to below check so return (no-op) will be // conditional (flag needs to be set in TypedDataSetif (remotingFormat == SerializationFormat.Xml && !ConstructSchema/* && this.GetType() != typeof(DataSet)*/) { return; //For typed dataset xml remoting, this is a no-op } DeserializeDataSet(info, context, remotingFormat, schemaSerializationMode); } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] public virtual voidGetObjectData(SerializationInfoinfo, StreamingContextcontext) { SerializationFormatremotingFormat = RemotingFormat; SerializeDataSet(info, context, remotingFormat); } // Deserialize all the tables data of the dataset from binary/xml stream.protected virtual voidInitializeDerivedDataSet() { return; } // Serialize all the tables.private voidSerializeDataSet(SerializationInfoinfo, StreamingContextcontext, SerializationFormatremotingFormat) { Debug.Assert(info != null); info.AddValue("DataSet.RemotingVersion", newVersion(2, 0)); // SqlHotFix 299, SerializationFormat enumeration types don't exist in V1.1 SP1if (SerializationFormat.Xml != remotingFormat) { info.AddValue("DataSet.RemotingFormat", remotingFormat); } // SqlHotFix 299, SchemaSerializationMode enumeration types don't exist in V1.1 SP1if (SchemaSerializationMode.IncludeSchema != SchemaSerializationMode) { //SkipSchemaDuringSerializationinfo.AddValue("SchemaSerializationMode.DataSet", SchemaSerializationMode); } if (remotingFormat != SerializationFormat.Xml) { if (SchemaSerializationMode == SchemaSerializationMode.IncludeSchema) { //DataSet public state propertiesSerializeDataSetProperties(info, context); //Tables Countinfo.AddValue("DataSet.Tables.Count", Tables.Count); //Tables, Columns, Rowsfor (inti = 0; i < Tables.Count; i++) { BinaryFormatterbf = newBinaryFormatter(null, newStreamingContext(context.State, false)); MemoryStreammemStream = newMemoryStream(); bf.Serialize(memStream, Tables[i]); memStream.Position = 0; info.AddValue(String.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), memStream.GetBuffer()); } //Constraintsfor (inti = 0; i < Tables.Count; i++) { Tables[i].SerializeConstraints(info, context, i, true); } //RelationsSerializeRelations(info, context); //Expression Columnsfor (inti = 0; i < Tables.Count; i++) { Tables[i].SerializeExpressionColumns(info, context, i); } } else { //Serialize DataSet public properties.SerializeDataSetProperties(info, context); } //Rowsfor (inti = 0; i < Tables.Count; i++) { Tables[i].SerializeTableData(info, context, i); } } else { // old behaviourStringstrSchema = this.GetXmlSchemaForRemoting(null); StringstrData = null; info.AddValue(KEY_XMLSCHEMA, strSchema); StringBuilderstrBuilder; strBuilder = newStringBuilder(EstimatedXmlStringSize() * 2); StringWriterstrWriter = newStringWriter(strBuilder, CultureInfo.InvariantCulture); XmlTextWriterw = newXmlTextWriter(strWriter); WriteXml(w, XmlWriteMode.DiffGram); strData = strWriter.ToString(); info.AddValue(KEY_XMLDIFFGRAM, strData); } } // Deserialize all the tables - marked internal so that DataTable can call into thisinternal voidDeserializeDataSet(SerializationInfoinfo, StreamingContextcontext, SerializationFormatremotingFormat, SchemaSerializationModeschemaSerializationMode) { // deserialize schemaDeserializeDataSetSchema(info, context, remotingFormat, schemaSerializationMode); // deserialize dataDeserializeDataSetData(info, context, remotingFormat); } // Deserialize schema.private voidDeserializeDataSetSchema(SerializationInfoinfo, StreamingContextcontext, SerializationFormatremotingFormat, SchemaSerializationModeschemaSerializationMode) { if (remotingFormat != SerializationFormat.Xml) { if (schemaSerializationMode == SchemaSerializationMode.IncludeSchema) { //DataSet public state propertiesDeserializeDataSetProperties(info, context); //Tables CountinttableCount = info.GetInt32("DataSet.Tables.Count"); //Tables, Columns, Rowsfor (inti = 0; i < tableCount; i++) { Byte[] buffer = (Byte[])info.GetValue(String.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), typeof(Byte[])); MemoryStreammemStream = newMemoryStream(buffer); memStream.Position = 0; BinaryFormatterbf = newBinaryFormatter(null, newStreamingContext(context.State, false)); DataTabledt = (DataTable)bf.Deserialize(memStream); Tables.Add(dt); } //Constraintsfor (inti = 0; i < tableCount; i++) { Tables[i].DeserializeConstraints(info, context, /* table index */i, /* serialize all constraints */true); // } //RelationsDeserializeRelations(info, context); //Expression Columnsfor (inti = 0; i < tableCount; i++) { Tables[i].DeserializeExpressionColumns(info, context, i); } } else { //DeSerialize DataSet public properties.[Locale, CaseSensitive and EnforceConstraints]DeserializeDataSetProperties(info, context); } } else { stringstrSchema = (String)info.GetValue(KEY_XMLSCHEMA, typeof(System.String)); if (strSchema != null) { this.ReadXmlSchema(newXmlTextReader(newStringReader(strSchema)), true); } } } // Deserialize all data.private voidDeserializeDataSetData(SerializationInfoinfo, StreamingContextcontext, SerializationFormatremotingFormat) { if (remotingFormat != SerializationFormat.Xml) { for (inti = 0; i < Tables.Count; i++) { Tables[i].DeserializeTableData(info, context, i); } } else { stringstrData = (String)info.GetValue(KEY_XMLDIFFGRAM, typeof(System.String)); if (strData != null) { this.ReadXml(newXmlTextReader(newStringReader(strData)), XmlReadMode.DiffGram); } } } // Serialize just the dataset propertiesprivate voidSerializeDataSetProperties(SerializationInfoinfo, StreamingContextcontext) { //DataSet basic propertiesinfo.AddValue("DataSet.DataSetName", DataSetName); info.AddValue("DataSet.Namespace", Namespace); info.AddValue("DataSet.Prefix", Prefix); //DataSet runtime propertiesinfo.AddValue("DataSet.CaseSensitive", CaseSensitive); info.AddValue("DataSet.LocaleLCID", Locale.LCID); info.AddValue("DataSet.EnforceConstraints", EnforceConstraints); //ExtendedPropertiesinfo.AddValue("DataSet.ExtendedProperties", ExtendedProperties); } // DeSerialize dataset propertiesprivate voidDeserializeDataSetProperties(SerializationInfoinfo, StreamingContextcontext) { //DataSet basic propertiesdataSetName = info.GetString("DataSet.DataSetName"); namespaceURI = info.GetString("DataSet.Namespace"); _datasetPrefix = info.GetString("DataSet.Prefix"); //DataSet runtime properties_caseSensitive = info.GetBoolean("DataSet.CaseSensitive"); intlcid = (int)info.GetValue("DataSet.LocaleLCID", typeof(int)); _culture = newCultureInfo(lcid); _cultureUserSet = true; enforceConstraints = info.GetBoolean("DataSet.EnforceConstraints"); //ExtendedPropertiesextendedProperties = (PropertyCollection)info.GetValue("DataSet.ExtendedProperties", typeof(PropertyCollection)); } // Gets relation info from the dataset.// ***Schema for Serializing ArrayList of Relations***// Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties]private voidSerializeRelations(SerializationInfoinfo, StreamingContextcontext) { ArrayListrelationList = newArrayList(); foreach (DataRelationrelinRelations) { int[] parentInfo = newint[rel.ParentColumns.Length + 1]; parentInfo[0] = Tables.IndexOf(rel.ParentTable); for (intj = 1; j < parentInfo.Length; j++) { parentInfo[j] = rel.ParentColumns[j - 1].Ordinal; } int[] childInfo = newint[rel.ChildColumns.Length + 1]; childInfo[0] = Tables.IndexOf(rel.ChildTable); for (intj = 1; j < childInfo.Length; j++) { childInfo[j] = rel.ChildColumns[j - 1].Ordinal; } ArrayListlist = newArrayList(); list.Add(rel.RelationName); list.Add(parentInfo); list.Add(childInfo); list.Add(rel.Nested); list.Add(rel.extendedProperties); relationList.Add(list); } info.AddValue("DataSet.Relations", relationList); } /* Adds relations to the dataset. ***Schema for Serializing ArrayList of Relations*** Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties] */private voidDeserializeRelations(SerializationInfoinfo, StreamingContextcontext) { ArrayListrelationList = (ArrayList)info.GetValue("DataSet.Relations", typeof(ArrayList)); foreach (ArrayListlistinrelationList) { stringrelationName = (string)list[0]; int[] parentInfo = (int[])list[1]; int[] childInfo = (int[])list[2]; boolisNested = (bool)list[3]; PropertyCollectionextendedProperties = (PropertyCollection)list[4]; //ParentKey Columns.DataColumn[] parentkeyColumns = newDataColumn[parentInfo.Length - 1]; for (inti = 0; i < parentkeyColumns.Length; i++) { parentkeyColumns[i] = Tables[parentInfo[0]].Columns[parentInfo[i + 1]]; } //ChildKey Columns.DataColumn[] childkeyColumns = newDataColumn[childInfo.Length - 1]; for (inti = 0; i < childkeyColumns.Length; i++) { childkeyColumns[i] = Tables[childInfo[0]].Columns[childInfo[i + 1]]; } //Create the Relation, without any constraints[Assumption: The constraints are added earlier than the relations]DataRelationrel = newDataRelation(relationName, parentkeyColumns, childkeyColumns, false); rel.CheckMultipleNested = false; // disable the check for multiple nested parentrel.Nested = isNested; rel.extendedProperties = extendedProperties; Relations.Add(rel); rel.CheckMultipleNested = true; // enable the check for multiple nested parent } } internal voidFailedEnableConstraints() { this.EnforceConstraints = false; throwExceptionBuilder.EnforceConstraint(); } ///<devdoc>///<para>/// Gets or sets a value indicating whether string/// comparisons within <seecref='System.Data.DataTable'/>/// objects are/// case-sensitive.///</para>///</devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), DefaultValue(false), ResDescriptionAttribute(Res.DataSetCaseSensitiveDescr) ] public boolCaseSensitive { get { return_caseSensitive; } set { if (_caseSensitive != value) { boololdValue = _caseSensitive; _caseSensitive = value; if (!ValidateCaseConstraint()) { _caseSensitive = oldValue; throwExceptionBuilder.CannotChangeCaseLocale(); } foreach (DataTabletableinTables) { table.SetCaseSensitiveValue(value, false, true); } } } } bool System.ComponentModel.IListSource.ContainsListCollection { get { return true; } } ///<devdoc>///<para>Gets a custom view of the data contained by the <seecref='System.Data.DataSet'/> , one/// that allows filtering, searching, and navigating through the custom data view.</para>///</devdoc> [Browsable(false), ResDescriptionAttribute(Res.DataSetDefaultViewDescr)] publicDataViewManagerDefaultViewManager { get { if (defaultViewManager == null) { lock (_defaultViewManagerLock) { if (defaultViewManager == null) { defaultViewManager = newDataViewManager(this, true); } } } returndefaultViewManager; } } ///<devdoc>///<para>Gets or sets a value indicating whether constraint rules are followed when/// attempting any update operation.</para>///</devdoc> [DefaultValue(true), ResDescriptionAttribute(Res.DataSetEnforceConstraintsDescr)] public boolEnforceConstraints { get { returnenforceConstraints; } set { IntPtrhscp; Bid.ScopeEnter(outhscp, "<ds.DataSet.set_EnforceConstraints|API> %d#, %d{bool}\n", ObjectID, value); try { if (this.enforceConstraints != value) { if (value) EnableConstraints(); this.enforceConstraints = value; } } finally { Bid.ScopeLeave(refhscp); } } } internal voidRestoreEnforceConstraints(boolvalue) { this.enforceConstraints = value; } internal voidEnableConstraints() { IntPtrhscp; Bid.ScopeEnter(outhscp, "<ds.DataSet.EnableConstraints|INFO> %d#\n", ObjectID); try { boolerrors = false; for (ConstraintEnumeratorconstraints = newConstraintEnumerator(this); constraints.GetNext(); ) { Constraintconstraint = (Constraint)constraints.GetConstraint(); errors |= constraint.IsConstraintViolated(); } foreach (DataTabletableinTables) { foreach (DataColumncolumnintable.Columns) { if (!column.AllowDBNull) { errors |= column.IsNotAllowDBNullViolated(); } if (column.MaxLength >= 0) { errors |= column.IsMaxLengthViolated(); } } } if (errors) this.FailedEnableConstraints(); } finally { Bid.ScopeLeave(refhscp); } } ///<devdoc>///<para>Gets or/// sets the name of this <seecref='System.Data.DataSet'/> .</para>///</devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), DefaultValue(""), ResDescriptionAttribute(Res.DataSetDataSetNameDescr) ] public stringDataSetName { get { returndataSetName; } set { Bid.Trace("<ds.DataSet.set_DataSetName|API> %d#, '%ls'\n", ObjectID, value); if (value != dataSetName) { if (value == null || value.Length == 0) throwExceptionBuilder.SetDataSetNameToEmpty(); DataTableconflicting = Tables[value, Namespace]; if ((conflicting != null) && (!conflicting.fNestedInDataset)) throwExceptionBuilder.SetDataSetNameConflicting(value); RaisePropertyChanging("DataSetName"); this.dataSetName = value; } } } ///<devdoc>///</devdoc> [ DefaultValue(""), ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataSetNamespaceDescr) ] public stringNamespace { get { returnnamespaceURI; } set { Bid.Trace("<ds.DataSet.set_Namespace|API> %d#, '%ls'\n", ObjectID, value); if (value == null) value = String.Empty; if (value != namespaceURI) { RaisePropertyChanging("Namespace"); foreach (DataTabledtinTables) { if (dt.tableNamespace != null) continue; if ((dt.NestedParentRelations.Length == 0) || (dt.NestedParentRelations.Length == 1 && dt.NestedParentRelations[0].ChildTable == dt)) { // dt.SelfNestedWithOneRelation) { // this is wrong bug it was previous behaviorif (Tables.Contains(dt.TableName, value, false, true)) throwExceptionBuilder.DuplicateTableName2(dt.TableName, value); dt.CheckCascadingNamespaceConflict(value); dt.DoRaiseNamespaceChange(); } } namespaceURI = value; if (Common.ADP.IsEmpty(value)) _datasetPrefix = String.Empty; } } } ///<devdoc>///<para>[To be supplied.]</para>///</devdoc> [ DefaultValue(""), ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataSetPrefixDescr) ] public stringPrefix { get { return_datasetPrefix; } set { if (value == null) value = String.Empty; if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value)) throwExceptionBuilder.InvalidPrefix(value); if (value != _datasetPrefix) { RaisePropertyChanging("Prefix"); _datasetPrefix = value; } } } ///<devdoc>///<para>Gets the collection of custom user information.</para>///</devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), Browsable(false), ResDescriptionAttribute(Res.ExtendedPropertiesDescr) ] publicPropertyCollectionExtendedProperties { get { if (extendedProperties == null) { extendedProperties = newPropertyCollection(); } returnextendedProperties; } } ///<devdoc>///<para>/// Gets a value indicating whether there are errors in any/// of the rows in any of the tables of this <seecref='System.Data.DataSet'/> .///</para>///</devdoc> [Browsable(false), ResDescriptionAttribute(Res.DataSetHasErrorsDescr)] public boolHasErrors { get { for (inti = 0; i < Tables.Count; i++) { if (Tables[i].HasErrors) return true; } return false; } } [Browsable(false)] public boolIsInitialized { get { return !fInitInProgress; } } ///<devdoc>///<para>/// Gets or sets the locale information used to compare strings within the table.///</para>///</devdoc> [ ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.DataSetLocaleDescr) ] publicCultureInfoLocale { get { // used for comparing not formating/parsingDebug.Assert(null != _culture, "DataSet.Locale: null culture"); return_culture; } set { IntPtrhscp; Bid.ScopeEnter(outhscp, "<ds.DataSet.set_Locale|API> %d#\n", ObjectID); try { if (value != null) { if (!_culture.Equals(value)) { SetLocaleValue(value, true); } _cultureUserSet = true; } } finally { Bid.ScopeLeave(refhscp); } } } internal voidSetLocaleValue(CultureInfovalue, booluserSet) { boolflag = false; boolexceptionThrown = false; inttableCount = 0; CultureInfooldLocale = _culture; boololdUserSet = _cultureUserSet; try { _culture = value; _cultureUserSet = userSet; foreach (DataTabletableinTables) { if (!table.ShouldSerializeLocale()) { boolretchk = table.SetLocaleValue(value, false, false); //Debug.Assert(retchk == table.ShouldSerializeLocale(), "unexpected setting of table locale"); may fire with Deserialize
//------------------------------------------------------------------------------// <copyright file="SqlSessionStateStore.cs" company="Microsoft">// Copyright (c) Microsoft Corporation. All rights reserved.// </copyright>//------------------------------------------------------------------------------/* * SqlSessionStateStore.cs * * Copyright (c) 1998-2000, Microsoft Corporation * */namespace System.Web.SessionState { using System; using System.Configuration; using System.Collections; using System.Threading; using System.IO; using System.Web; using System.Web.Caching; using System.Web.Util; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Text; using System.Security.Principal; using System.Xml; using System.Collections.Specialized; using System.Configuration.Provider; using System.Globalization; using System.Web.Management; using System.Web.Hosting; using System.Web.Configuration; /* * Provides session state via SQL Server */internal classSqlSessionStateStore : SessionStateStoreProviderBase { internal enumSupportFlags : uint { None = 0x00000000, GetLockAge = 0x00000001, Uninitialized = 0xFFFFFFFF } #pragmawarningdisable 0649 staticReadWriteSpinLocks_lock; #pragmawarningrestore 0649 static ints_isClearPoolInProgress; static ints_commandTimeout; staticTimeSpans_retryInterval; staticSqlPartitionInfos_singlePartitionInfo; staticPartitionManagers_partitionManager; static bools_oneTimeInited; static bools_usePartition; staticEventHandlers_onAppDomainUnload; // We keep these info because we don't want to hold on to the config object.static strings_configPartitionResolverType; static strings_configSqlConnectionFileName; static ints_configSqlConnectionLineNumber; static bools_configAllowCustomSqlDatabase; static bools_configCompressionEnabled; // Per request infoHttpContext_rqContext; int_rqOrigStreamLen; IPartitionResolver_partitionResolver; SqlPartitionInfo_partitionInfo; const intITEM_SHORT_LENGTH = 7000; const intSQL_ERROR_PRIMARY_KEY_VIOLATION = 2627; const intSQL_LOGIN_FAILED = 18456; const intSQL_LOGIN_FAILED_2 = 18452; const intSQL_LOGIN_FAILED_3 = 18450; const intSQL_CANNOT_OPEN_DATABASE_FOR_LOGIN = 4060; const intSQL_TIMEOUT_EXPIRED = -2; const intAPP_SUFFIX_LENGTH = 8; const intFIRST_RETRY_SLEEP_TIME = 5000; const intRETRY_SLEEP_TIME = 1000; static intID_LENGTH = SessionIDManager.SessionIDMaxLength + APP_SUFFIX_LENGTH; internal const intSQL_COMMAND_TIMEOUT_DEFAULT = 30; // in secinternalSqlSessionStateStore() { } internal override voidInitialize(stringname, NameValueCollectionconfig, IPartitionResolverpartitionResolver) { _partitionResolver = partitionResolver; Initialize(name, config); } #if DBG SessionStateModule _module; internal void SetModule(SessionStateModule module) { _module = module; } #endifpublic override voidInitialize(stringname, NameValueCollectionconfig) { if (String.IsNullOrEmpty(name)) name = "SQL Server Session State Provider"; base.Initialize(name, config); if (!s_oneTimeInited) { s_lock.AcquireWriterLock(); try { if (!s_oneTimeInited) { OneTimeInit(); } } finally { s_lock.ReleaseWriterLock(); } } if (!s_usePartition) { // For single partition, the connection info won't change from request to requestDebug.Assert(_partitionResolver == null); _partitionInfo = s_singlePartitionInfo; } } voidOneTimeInit() { SessionStateSectionconfig = RuntimeConfig.GetAppConfig().SessionState; s_configPartitionResolverType = config.PartitionResolverType; s_configSqlConnectionFileName = config.ElementInformation.Properties["sqlConnectionString"].Source; s_configSqlConnectionLineNumber = config.ElementInformation.Properties["sqlConnectionString"].LineNumber; s_configAllowCustomSqlDatabase = config.AllowCustomSqlDatabase; s_configCompressionEnabled = config.CompressionEnabled; if (_partitionResolver == null) { StringsqlConnectionString = config.SqlConnectionString; SessionStateModule.ReadConnectionString(config, refsqlConnectionString, "sqlConnectionString"); s_singlePartitionInfo = (SqlPartitionInfo)CreatePartitionInfo(sqlConnectionString); } else { s_usePartition = true; s_partitionManager = newPartitionManager(newCreatePartitionInfo(CreatePartitionInfo)); } s_commandTimeout = (int)config.SqlCommandTimeout.TotalSeconds; s_retryInterval = config.SqlConnectionRetryInterval; s_isClearPoolInProgress = 0; // We only need to do this in one instances_onAppDomainUnload = newEventHandler(OnAppDomainUnload); Thread.GetDomain().DomainUnload += s_onAppDomainUnload; // Last thing to set.s_oneTimeInited = true; } voidOnAppDomainUnload(ObjectunusedObject, EventArgsunusedEventArgs) { Debug.Trace("SqlSessionStateStore", "OnAppDomainUnload called"); Thread.GetDomain().DomainUnload -= s_onAppDomainUnload; if (_partitionResolver == null) { if (s_singlePartitionInfo != null) { s_singlePartitionInfo.Dispose(); } } else { if (s_partitionManager != null) { s_partitionManager.Dispose(); } } } internalIPartitionInfoCreatePartitionInfo(stringsqlConnectionString) { /* * Parse the connection string for errors. We want to ensure * that the user's connection string doesn't contain an * Initial Catalog entry, so we must first create a dummy connection. */SqlConnectiondummyConnection; stringattachDBFilename = null; try { dummyConnection = newSqlConnection(sqlConnectionString); } catch (Exceptione) { if (s_usePartition) { HttpExceptionouterException = newHttpException( SR.GetString(SR.Error_parsing_sql_partition_resolver_string, s_configPartitionResolverType, e.Message), e); outerException.SetFormatter(newUseLastUnhandledErrorFormatter(outerException)); throwouterException; } else { thrownewConfigurationErrorsException( SR.GetString(SR.Error_parsing_session_sqlConnectionString, e.Message), e, s_configSqlConnectionFileName, s_configSqlConnectionLineNumber); } } // Search for both Database and AttachDbFileName. Don't append our// database name if either of them exists.stringdatabase = dummyConnection.Database; SqlConnectionStringBuilderscsb = newSqlConnectionStringBuilder(sqlConnectionString); if (String.IsNullOrEmpty(database)) { database = scsb.AttachDBFilename; attachDBFilename = database; } if (!String.IsNullOrEmpty(database)) { if (!s_configAllowCustomSqlDatabase) { if (s_usePartition) { thrownewHttpException( SR.GetString(SR.No_database_allowed_in_sql_partition_resolver_string, s_configPartitionResolverType, dummyConnection.DataSource, database)); } else { thrownewConfigurationErrorsException( SR.GetString(SR.No_database_allowed_in_sqlConnectionString), s_configSqlConnectionFileName, s_configSqlConnectionLineNumber); } } if (attachDBFilename != null) { HttpRuntime.CheckFilePermission(attachDBFilename, true); } } else { sqlConnectionString += ";Initial Catalog=ASPState"; } returnnewSqlPartitionInfo(newResourcePool(newTimeSpan(0, 0, 5), int.MaxValue), scsb.IntegratedSecurity, sqlConnectionString); } public override boolSetItemExpireCallback(SessionStateItemExpireCallbackexpireCallback) { return false; } public override voidDispose() { } public override voidInitializeRequest(HttpContextcontext) { Debug.Assert(context != null, "context != null"); _rqContext = context; _rqOrigStreamLen = 0; if (s_usePartition) { // For multiple partition case, the connection info can change from request to request_partitionInfo = null; } } public override voidEndRequest(HttpContextcontext) { Debug.Assert(context != null, "context != null"); _rqContext = null; } public boolKnowForSureNotUsingIntegratedSecurity { get { if (_partitionInfo == null) { Debug.Assert(s_usePartition, "_partitionInfo can be null only if we're using paritioning and we haven't called GetConnection yet."); // If we're using partitioning, we need the session id to figure out the connection// string. Without it, we can't know for sure.return false; } else { Debug.Assert(_partitionInfo != null); return !_partitionInfo.UseIntegratedSecurity; } } } //// Regarding resource pool, we will turn it on if in <identity>:// - User is not using integrated security// - impersonation = "false"// - impersonation = "true" and userName/password is NON-null// - impersonation = "true" and IIS is using Anonymous//// Otherwise, the impersonated account will be dynamic and we have to turn// resource pooling off.//// Note:// In case 2. above, the user can specify different usernames in different// web.config in different subdirs in the app. In this case, we will just// cache the connections in the resource pool based on the identity of the// connection. So in this specific scenario it is possible to have the// resource pool filled with mixed identities.//boolCanUsePooling() { boolret; if (KnowForSureNotUsingIntegratedSecurity) { Debug.Trace("SessionStatePooling", "CanUsePooling: not using integrated security"); ret = true; } else if (_rqContext == null) { // One way this can happen is we hit an error on page compilation,// and SessionStateModule.OnEndRequest is calledDebug.Trace("SessionStatePooling", "CanUsePooling: no context"); ret = false; } else if (!_rqContext.IsClientImpersonationConfigured) { Debug.Trace("SessionStatePooling", "CanUsePooling: mode is None or Application"); ret = true; } else if (HttpRuntime.IsOnUNCShareInternal) { Debug.Trace("SessionStatePooling", "CanUsePooling: mode is UNC"); ret = false; } else { stringlogon = _rqContext.WorkerRequest.GetServerVariable("LOGON_USER"); Debug.Trace("SessionStatePooling", "LOGON_USER = '" + logon + "'; identity = '" + _rqContext.User.Identity.Name + "'; IsUNC = " + HttpRuntime.IsOnUNCShareInternal); if (String.IsNullOrEmpty(logon)) { ret = true; } else { ret = false; } } Debug.Trace("SessionStatePooling", "CanUsePooling returns " + ret); returnret; } SqlStateConnectionGetConnection(stringid, ref boolusePooling) { SqlStateConnectionconn = null; if (_partitionInfo == null) { Debug.Assert(s_partitionManager != null); Debug.Assert(_partitionResolver != null); _partitionInfo = (SqlPartitionInfo)s_partitionManager.GetPartition(_partitionResolver, id); } Debug.Trace("SessionStatePooling", "Calling GetConnection under " + WindowsIdentity.GetCurrent().Name); #if DBG Debug.Assert(_module._rqChangeImpersonationRefCount != 0, "SessionStateModule.ChangeImpersonation should have been called before making any call to SQL"); #endifusePooling = CanUsePooling(); if (usePooling) { conn = (SqlStateConnection) _partitionInfo.RetrieveResource(); if (conn != null && (conn.Connection.State & ConnectionState.Open) == 0) { conn.Dispose(); conn = null; } } if (conn == null) { conn = newSqlStateConnection(_partitionInfo, s_retryInterval); } returnconn; } voidDisposeOrReuseConnection(refSqlStateConnectionconn, boolusePooling) { try { if (conn == null) { return; } if (usePooling) { conn.ClearAllParameters(); _partitionInfo.StoreResource(conn); conn = null; } } finally { if (conn != null) { conn.Dispose(); } } } internal static voidThrowSqlConnectionException(SqlConnectionconn, Exceptione) { if (s_usePartition) { thrownewHttpException( SR.GetString(SR.Cant_connect_sql_session_database_partition_resolver, s_configPartitionResolverType, conn.DataSource, conn.Database), e); } else { thrownewHttpException( SR.GetString(SR.Cant_connect_sql_session_database), e); } } SessionStateStoreDataDoGet(HttpContextcontext, Stringid, boolgetExclusive, out boollocked, outTimeSpanlockAge, out objectlockId, outSessionStateActionsactionFlags) { SqlDataReaderreader; byte [] buf; MemoryStreamstream = null; SessionStateStoreDataitem; booluseGetLockAge = false; SqlStateConnectionconn = null; SqlCommandcmd = null; boolusePooling = true; Debug.Assert(id.Length <= SessionIDManager.SESSION_ID_LENGTH_LIMIT, "id.Length <= SessionIDManager.SESSION_ID_LENGTH_LIMIT"); Debug.Assert(context != null, "context != null"); // Set default return valueslocked = false; lockId = null; lockAge = TimeSpan.Zero; actionFlags = 0; buf = null; reader = null; conn = GetConnection(id, refusePooling); Debug.Assert(_partitionInfo != null, "_partitionInfo != null"); Debug.Assert(_partitionInfo.SupportFlags != SupportFlags.Uninitialized, "_partitionInfo.SupportFlags != SupportFlags.Uninitialized"); //// In general, if we're talking to a SQL 2000 or above, we use LockAge; otherwise we use LockDate.// Below are the details://// Version 1// ---------// In v1, the lockDate is generated and stored in SQL using local time, and we calculate the "lockage"// (i.e. how long the item is locked) by having the web server read lockDate from SQL and substract it// from DateTime.Now. But this approach introduced two problems:// 1. SQL server and web servers need to be in the same time zone.// 2. Daylight savings problem.//// Version 1.1// -----------// In v1.1, if using SQL 2000 we fixed the problem by calculating the "lockage" directly in SQL// so that the SQL server and the web server don't have to be in the same time zone. We also// use UTC date to store time in SQL so that the Daylight savings problem is solved.//// In summary, if using SQL 2000 we made the following changes to the SQL tables:// i. The column Expires is using now UTC time// ii. Add new SP TempGetStateItem2 and TempGetStateItemExclusive2 to return a lockage// instead of a lockDate.// iii. To support v1 web server, we still need to have TempGetStateItem and// TempGetStateItemExclusive. However, we modify it a bit so that they use// UTC time to update Expires column.//// If using SQL 7, we decided not to fix the problem, and the SQL scripts for SQL 7 remain pretty much// the same. That means v1.1 web server will continue to call TempGetStateItem and// TempGetStateItemExclusive and use v1 way to calculate the "lockage".//// Version 2.0// -----------// In v2.0 we added some new SP TempGetStateItem3 and TempGetStateItemExclusive3// because we added a new return value 'actionFlags'. However, the principle remains the same// that we support lockAge only if talking to SQL 2000.//// (When one day MS stops supporting SQL 7 we can remove all the SQL7-specific scripts and// stop all these craziness.)//if ((_partitionInfo.SupportFlags & SupportFlags.GetLockAge) != 0) { useGetLockAge = true; } try { if (getExclusive) { cmd = conn.TempGetExclusive; } else { cmd = conn.TempGet; } cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; // @idcmd.Parameters[1].Value = Convert.DBNull; // @itemShortcmd.Parameters[2].Value = Convert.DBNull; // @lockedcmd.Parameters[3].Value = Convert.DBNull; // @lockDate or @lockAgecmd.Parameters[4].Value = Convert.DBNull; // @lockCookiecmd.Parameters[5].Value = Convert.DBNull; // @actionFlagsusing(reader = SqlExecuteReaderWithRetry(cmd, CommandBehavior.Default)) { /* If the cmd returned data, we must read it all before getting out params */if (reader != null) { try { if (reader.Read()) { Debug.Trace("SqlSessionStateStore", "Sql Get returned long item"); buf = (byte[]) reader[0]; } } catch(Exceptione) { ThrowSqlConnectionException(cmd.Connection, e); } } } /* Check if value was returned */if (Convert.IsDBNull(cmd.Parameters[2].Value)) { Debug.Trace("SqlSessionStateStore", "Sql Get returned null"); return null; } /* Check if item is locked */Debug.Assert(!Convert.IsDBNull(cmd.Parameters[3].Value), "!Convert.IsDBNull(cmd.Parameters[3].Value)"); Debug.Assert(!Convert.IsDBNull(cmd.Parameters[4].Value), "!Convert.IsDBNull(cmd.Parameters[4].Value)"); locked = (bool) cmd.Parameters[2].Value; lockId = (int) cmd.Parameters[4].Value; if (locked) { Debug.Trace("SqlSessionStateStore", "Sql Get returned item that was locked"); Debug.Assert(((int)cmd.Parameters[5].Value & (int)SessionStateActions.InitializeItem) == 0, "(cmd.Parameters[5].Value & SessionStateActions.InitializeItem) == 0; uninit item shouldn't be locked"); if (useGetLockAge) { lockAge = newTimeSpan(0, 0, (int) cmd.Parameters[3].Value); } else { DateTimelockDate; lockDate = (DateTime) cmd.Parameters[3].Value; lockAge = DateTime.Now - lockDate; } Debug.Trace("SqlSessionStateStore", "LockAge = " + lockAge); if (lockAge > newTimeSpan(0, 0, Sec.ONE_YEAR)) { Debug.Trace("SqlSessionStateStore", "Lock age is more than 1 year!!!"); lockAge = TimeSpan.Zero; } return null; } actionFlags = (SessionStateActions) cmd.Parameters[5].Value; if (buf == null) { /* Get short item */Debug.Assert(!Convert.IsDBNull(cmd.Parameters[1].Value), "!Convert.IsDBNull(cmd.Parameters[1].Value)"); Debug.Trace("SqlSessionStateStore", "Sql Get returned short item"); buf = (byte[]) cmd.Parameters[1].Value; Debug.Assert(buf != null, "buf != null"); } // Done with the connection.DisposeOrReuseConnection(refconn, usePooling); using(stream = newMemoryStream(buf)) { item = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled); _rqOrigStreamLen = (int) stream.Position; } returnitem; } finally { DisposeOrReuseConnection(refconn, usePooling); } } public overrideSessionStateStoreDataGetItem(HttpContextcontext, Stringid, out boollocked, outTimeSpanlockAge, out objectlockId, outSessionStateActionsactionFlags) { Debug.Trace("SqlSessionStateStore", "Calling Sql Get, id=" + id); SessionIDManager.CheckIdLength(id, true/* throwOnFail */); returnDoGet(context, id, false, outlocked, outlockAge, outlockId, outactionFlags); } public overrideSessionStateStoreDataGetItemExclusive(HttpContextcontext, Stringid, out boollocked, outTimeSpanlockAge, out objectlockId, outSessionStateActionsactionFlags) { Debug.Trace("SqlSessionStateStore", "Calling Sql GetExclusive, id=" + id); SessionIDManager.CheckIdLength(id, true/* throwOnFail */); returnDoGet(context, id, true, outlocked, outlockAge, outlockId, outactionFlags); } public override voidReleaseItemExclusive(HttpContextcontext, Stringid, objectlockId) { Debug.Trace("SqlSessionStateStore", "Calling Sql ReleaseExclusive, id=" + id); Debug.Assert(lockId != null, "lockId != null"); Debug.Assert(context != null, "context != null"); boolusePooling = true; SqlStateConnectionconn = null; intlockCookie = (int)lockId; try { SessionIDManager.CheckIdLength(id, true/* throwOnFail */); conn = GetConnection(id, refusePooling); SqlCommandcmd = conn.TempReleaseExclusive; cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; cmd.Parameters[1].Value = lockCookie; SqlExecuteNonQueryWithRetry(cmd, false, null); } finally { DisposeOrReuseConnection(refconn, usePooling); } } public override voidSetAndReleaseItemExclusive(HttpContextcontext, Stringid, SessionStateStoreDataitem, objectlockId, boolnewItem) { byte [] buf; intlength; SqlCommandcmd; boolusePooling = true; SqlStateConnectionconn = null; intlockCookie; Debug.Assert(context != null, "context != null"); try { Debug.Trace("SqlSessionStateStore", "Calling Sql Set, id=" + id); Debug.Assert(item.Items != null, "item.Items != null"); Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null"); SessionIDManager.CheckIdLength(id, true/* throwOnFail */); try { SessionStateUtility.SerializeStoreData(item, ITEM_SHORT_LENGTH, outbuf, outlength, s_configCompressionEnabled); } catch { if (!newItem) { ((SessionStateStoreProviderBase)this).ReleaseItemExclusive(context, id, lockId); } throw; } // Save it to the storeif (lockId == null) { lockCookie = 0; } else { lockCookie = (int)lockId; } conn = GetConnection(id, refusePooling); if (!newItem) { Debug.Assert(_rqOrigStreamLen > 0, "_rqOrigStreamLen > 0"); if (length <= ITEM_SHORT_LENGTH) { if (_rqOrigStreamLen <= ITEM_SHORT_LENGTH) { cmd = conn.TempUpdateShort; } else { cmd = conn.TempUpdateShortNullLong; } } else { if (_rqOrigStreamLen <= ITEM_SHORT_LENGTH) { cmd = conn.TempUpdateLongNullShort; } else { cmd = conn.TempUpdateLong; } } } else { if (length <= ITEM_SHORT_LENGTH) { cmd = conn.TempInsertShort; } else { cmd = conn.TempInsertLong; } } cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; cmd.Parameters[1].Size = length; cmd.Parameters[1].Value = buf; cmd.Parameters[2].Value = item.Timeout; if (!newItem) { cmd.Parameters[3].Value = lockCookie; } SqlExecuteNonQueryWithRetry(cmd, newItem, id); } finally { DisposeOrReuseConnection(refconn, usePooling); } } public override voidRemoveItem(HttpContextcontext, Stringid, objectlockId, SessionStateStoreDataitem) { Debug.Trace("SqlSessionStateStore", "Calling Sql Remove, id=" + id); Debug.Assert(lockId != null, "lockId != null"); Debug.Assert(context != null, "context != null"); boolusePooling = true; SqlStateConnectionconn = null; intlockCookie = (int)lockId; try { SessionIDManager.CheckIdLength(id, true/* throwOnFail */); conn = GetConnection(id, refusePooling); SqlCommandcmd = conn.TempRemove; cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; cmd.Parameters[1].Value = lockCookie; SqlExecuteNonQueryWithRetry(cmd, false, null); } finally { DisposeOrReuseConnection(refconn, usePooling); } } public override voidResetItemTimeout(HttpContextcontext, Stringid) { Debug.Trace("SqlSessionStateStore", "Calling Sql ResetTimeout, id=" + id); Debug.Assert(context != null, "context != null"); boolusePooling = true; SqlStateConnectionconn = null; try { SessionIDManager.CheckIdLength(id, true/* throwOnFail */); conn = GetConnection(id, refusePooling); SqlCommandcmd = conn.TempResetTimeout; cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; SqlExecuteNonQueryWithRetry(cmd, false, null); } finally { DisposeOrReuseConnection(refconn, usePooling); } } public overrideSessionStateStoreDataCreateNewStoreData(HttpContextcontext, inttimeout) { Debug.Assert(context != null, "context != null"); returnSessionStateUtility.CreateLegitStoreData(context, null, null, timeout); } public override voidCreateUninitializedItem(HttpContextcontext, Stringid, inttimeout) { Debug.Trace("SqlSessionStateStore", "Calling Sql InsertUninitializedItem, id=" + id); Debug.Assert(context != null, "context != null"); boolusePooling = true; SqlStateConnectionconn = null; byte [] buf; intlength; try { SessionIDManager.CheckIdLength(id, true/* throwOnFail */); // Store an empty dataSessionStateUtility.SerializeStoreData(CreateNewStoreData(context, timeout), ITEM_SHORT_LENGTH, outbuf, outlength, s_configCompressionEnabled); conn = GetConnection(id, refusePooling); SqlCommandcmd = conn.TempInsertUninitializedItem; cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; cmd.Parameters[1].Size = length; cmd.Parameters[1].Value = buf; cmd.Parameters[2].Value = timeout; SqlExecuteNonQueryWithRetry(cmd, true, id); } finally { DisposeOrReuseConnection(refconn, usePooling); } } static boolIsInsertPKException(SqlExceptionex, boolignoreInsertPKException, stringid) { // If the severity is greater than 20, we have a serious error.// The server usually closes the connection in these cases.if (ex != null && ex.Number == SQL_ERROR_PRIMARY_KEY_VIOLATION && ignoreInsertPKException) { Debug.Trace("SessionStateClientSet", "Insert failed because of primary key violation; just leave gracefully; id=" + id); // It's possible that two threads (from the same session) are creating the session// state, both failed to get it first, and now both tried to insert it.// One thread may lose with a Primary Key Violation error. If so, that thread will// just lose and exit gracefully.return true; } return false; } static boolIsFatalSqlException(SqlExceptionex) { // We will retry sql operations for serious errors.// We consider fatal exceptions any error with severity >= 20.// In this case, the SQL server closes the connection.// if(ex != null && (ex.Class >= 20 || ex.Number == SQL_CANNOT_OPEN_DATABASE_FOR_LOGIN || ex.Number == SQL_TIMEOUT_EXPIRED)) { return true; } return false; } static voidClearFlagForClearPoolInProgress() { // clear s_isClearPoolInProgress if it was setInterlocked.CompareExchange(refs_isClearPoolInProgress, 0, 1); } static boolCanRetry(SqlExceptionex, SqlConnectionconn, ref boolisFirstAttempt, refDateTimeendRetryTime) { if (s_retryInterval.Seconds <= 0) { // no retry policy setreturn false; } if (!IsFatalSqlException(ex)) { if (!isFirstAttempt) { ClearFlagForClearPoolInProgress(); } return false; } if (isFirstAttempt) { // check if someone has called ClearPool for this connection string// s_isClearPoolInProgress can be:// 0 - no one called ClearPool;// 1 - ClearPool is in progress or has already been called// If no one called ClearPool (s_isClearPoolInProgress = 0), then// make s_isClearPoolInProgress 1 and call clear poolif (0 == Interlocked.CompareExchange(refs_isClearPoolInProgress, 1, 0)) { Debug.Trace("SqlSessionStateStore", "CanRetry: Call ClearPool to destroy the corrupted connections in the pool"); SqlConnection.ClearPool(conn); } // First time we sleep longer than for subsequent retries.Thread.Sleep(FIRST_RETRY_SLEEP_TIME); endRetryTime = DateTime.UtcNow.Add(s_retryInterval); isFirstAttempt = false; return true; } if (DateTime.UtcNow > endRetryTime) { // the specified retry interval is up, we can't retry anymoreif (!isFirstAttempt) { ClearFlagForClearPoolInProgress(); } return false; } // sleep the specified time and allow retryThread.Sleep(RETRY_SLEEP_TIME); return true; } static intSqlExecuteNonQueryWithRetry(SqlCommandcmd, boolignoreInsertPKException, stringid) { boolisFirstAttempt = true; DateTimeendRetryTime = DateTime.UtcNow; while(true) { try { if (cmd.Connection.State != ConnectionState.Open) { // reopen the connection// (gets closed if a previous operation throwed a SQL exception with severity >= 20)cmd.Connection.Open(); } intresult = cmd.ExecuteNonQuery(); // the operation succeeded// If we retried, it's possible ClearPool has been called.// In this case, we clear the flag that shows ClearPool is in progress.if (!isFirstAttempt) { ClearFlagForClearPoolInProgress(); } returnresult; } catch (SqlExceptione) { // if specified, ignore primary key violationsif (IsInsertPKException(e, ignoreInsertPKException, id)) { // ignoreInsertPKException = insert && newItemreturn -1; } if (!CanRetry(e, cmd.Connection, refisFirstAttempt, refendRetryTime)) { // just throw, because not all conditions to retry are satisfiedThrowSqlConnectionException(cmd.Connection, e); } } catch (Exceptione) { // just throw, we have a different ExceptionThrowSqlConnectionException(cmd.Connection, e); } } } staticSqlDataReaderSqlExecuteReaderWithRetry(SqlCommandcmd, CommandBehaviorcmdBehavior) { boolisFirstAttempt = true; DateTimeendRetryTime = DateTime.UtcNow; while(true) { try { if (cmd.Connection.State != ConnectionState.Open) { // reopen the connection// (gets closed if a previous operation throwed a SQL exception with severity >= 20)cmd.Connection.Open(); } SqlDataReaderreader = cmd.ExecuteReader(cmdBehavior); // the operation succeededif (!isFirstAttempt) { ClearFlagForClearPoolInProgress(); } returnreader; } catch (SqlExceptione) { if (!CanRetry(e, cmd.Connection, refisFirstAttempt, refendRetryTime)) { // just throw, default to previous behaviorThrowSqlConnectionException(cmd.Connection, e); } } catch (Exceptione) { // just throw, we have a different ExceptionThrowSqlConnectionException(cmd.Connection, e); } } } internal classSqlPartitionInfo : PartitionInfo { bool_useIntegratedSecurity; string_sqlConnectionString; string_tracingPartitionString; SupportFlags_support = SupportFlags.Uninitialized; string_appSuffix

0 Replies to “Ms 57 Solved Assignment Cs”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *