public SupportInitializeGuard(ISupportInitialize supportInitialize) { if (supportInitialize == null) throw new ArgumentNullException("supportInitialize"); _supportInitialize = supportInitialize; supportInitialize.BeginInit(); }
public static object FromBytes(object instance, byte[] bytes, int index, int count) { object message = instance; ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count); ISupportInitialize iSupportInitialize = message as ISupportInitialize; if (iSupportInitialize == null) { return(message); } iSupportInitialize.EndInit(); return(message); }
public static object FromStream(Type type, MemoryStream stream) { object message = Activator.CreateInstance(type); ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length); ISupportInitialize iSupportInitialize = message as ISupportInitialize; if (iSupportInitialize == null) { return(message); } iSupportInitialize.EndInit(); return(message); }
public static T FromBytes<T>(byte[] bytes, int index, int length) { T t; using (MemoryStream ms = new MemoryStream(bytes, index, length)) { t = Serializer.Deserialize<T>(ms); } ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize == null) { return t; } iSupportInitialize.EndInit(); return t; }
public static T FromBytes <T>(byte[] bytes, int index, int length) { T t; using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, index, length)) { t = Serializer.Deserialize <T>(ms); } ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize == null) { return(t); } iSupportInitialize.EndInit(); return(t); }
public static object FromBytes(Type type, byte[] bytes, int index, int length) { object t; using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, index, length)) { t = Serializer.NonGeneric.Deserialize(type, ms); } ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize == null) { return(t); } iSupportInitialize.EndInit(); return(t); }
public static object FromBytes(Type type, byte[] bytes) { object t; using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { t = Serializer.NonGeneric.Deserialize(type, ms); } ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize == null) { return(t); } iSupportInitialize.EndInit(); return(t); }
public void Calling_BeginInit_EndInit_DoesNotCall_Refresh_When_NoDefer_WhenProviderIsNotChanged() { ISupportInitialize isi = this.provider; Exception ex = null; try { isi.BeginInit(); isi.EndInit(); } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.AreEqual(0, this.provider.RefreshCallCount); }
public static object FromJson(Type type, string str) { object t = JsonUtility.FromJson(str, type); ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize != null) { iSupportInitialize.EndInit(); } IDeserializationCallback deserializationCallback = t as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(t); } return(t); }
public void Calling_EndInit_Before_BeginInit_Throw_InvalidOperationException() { ISupportInitialize isi = this.provider; Exception ex = null; try { isi.EndInit(); } catch (Exception e) { ex = e; } Assert.IsNotNull(ex); Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); Assert.IsFalse(completedEventRaised); }
public static T FromJson <T>(string str) { T t = JsonUtility.FromJson <T>(str); ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize != null) { iSupportInitialize.EndInit(); } IDeserializationCallback deserializationCallback = t as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(t); } return(t); }
JumpItem PrepareItem(ApplicationJumpItemInfo item, JumpItem itemToReplace) { JumpItem itemWrap = ApplicationJumpItemWrapper.Wrap(item); ApplicationJumpTaskWrap task = itemWrap as ApplicationJumpTaskWrap; if (task != null) { PrepareTask(task); JumpItem existingItem = nativeJumpList.Find(task.ApplicationJumpTask.CommandId); if (existingItem != null && existingItem != itemToReplace) { throw new ApplicationJumpTaskDuplicateCommandIdException(); } } ISupportInitialize itemInit = item; itemInit.EndInit(); return(itemWrap); }
public void Setting_New_FieldDescriptions_Calls_Refresh() { ISupportInitialize isi = this.provider; Exception ex = null; try { (this.provider as IDataProvider).FieldDescriptionsProvider = new LocalDataSourceFieldDescriptionsProvider(); Assert.AreEqual(1, this.provider.RefreshCallCount); } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.AreEqual(1, this.provider.RefreshCallCount); }
public void Calling_DeferRefresh_Calls_Refresh_When_BeginInit_AndProviderLocalStateIsChanged() { ISupportInitialize isi = this.provider; Exception ex = null; try { using (provider.DeferRefresh()) { this.provider.AddPendingChangeToProvider(); } } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.AreEqual(1, this.provider.RefreshCallCount); }
public object DeserializeFrom(Type rType, byte[] rBytes, int nIndex, int nCount) { var rObj = HotfixReflectAssists.Construct(rType) as HotfixSerializerBinary; using (MemoryStream ms = mRecyclableMSMgr.GetStream("protobuf", rBytes, nIndex, nCount)) { using (var br = new BinaryReader(ms)) { rObj.Deserialize(br); } } ISupportInitialize iSupportInitialize = rObj as ISupportInitialize; if (iSupportInitialize == null) { return(rObj); } iSupportInitialize.EndInit(); return(rObj); }
public void DataGridViewColumnCollection_Add_ColumnAutomaticSortModeColumnSelectionModeInInitialization_ThrowsInvalidOperationException(DataGridViewSelectionMode selectionMode) { using var control = new DataGridView { SelectionMode = selectionMode }; ISupportInitialize iSupportInitialize = (ISupportInitialize)control; DataGridViewColumnCollection collection = control.Columns; using var column = new DataGridViewColumn(new SubDataGridViewCell()) { SortMode = DataGridViewColumnSortMode.Automatic }; iSupportInitialize.BeginInit(); collection.Add(column); // End init. Assert.Throws <InvalidOperationException>(() => iSupportInitialize.EndInit()); Assert.Equal(DataGridViewSelectionMode.RowHeaderSelect, control.SelectionMode); }
public static void SyncCollection( NotifyCollectionChangedEventArgs e, IList target, IList source, Func <object, object> convertItemAction, Action <int, object> insertItemAction = null, ISupportInitialize supportInitialize = null, Action <object> clearItemAction = null) { switch (e.Action) { case NotifyCollectionChangedAction.Add: DoAction(e.NewItems, (item) => InsertItem(item, target, source, convertItemAction, insertItemAction)); break; case NotifyCollectionChangedAction.Remove: DoAction(e.OldItems, (item) => { RemoveItem(e.OldStartingIndex, target, clearItemAction); }); break; case NotifyCollectionChangedAction.Reset: PopulateCore(target, source, convertItemAction, insertItemAction, supportInitialize); break; #if !SILVERLIGHT case NotifyCollectionChangedAction.Move: object insertItem = target[e.OldStartingIndex]; object insertItemAt = target[e.NewStartingIndex]; int deltaItem = e.NewStartingIndex > e.OldStartingIndex ? 1 : 0; target.Remove(insertItem); target.Insert(target.IndexOf(insertItemAt) + deltaItem, insertItem); break; #endif case NotifyCollectionChangedAction.Replace: RemoveItem(e.NewStartingIndex, target, clearItemAction); InsertItem(e.NewItems[0], target, source, convertItemAction, insertItemAction); break; } }
public void Setting_ItemsSource_To_Null_Calls_Refresh() { ISupportInitialize isi = this.provider; Exception ex = null; try { provider.ItemsSource = new List <Order>(); provider.BlockUntilRefreshCompletes(); Assert.IsTrue(this.StatuschangedEventWasRaised()); this.ClearStatusChangedEvents(); provider.ItemsSource = null; } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.IsTrue(this.StatuschangedEventWasRaised()); }
public static void SyncCollection( NotifyCollectionChangedEventArgs e, IList target, IList source, Func <object, object> convertItemAction, Action <int, object> insertItemAction = null, ISupportInitialize supportInitialize = null, Action <object> clearItemAction = null) { GuardHelper.ArgumentNotNull(target, nameof(target)); GuardHelper.ArgumentNotNull(source, nameof(source)); switch (e.Action) { case NotifyCollectionChangedAction.Add: DoAction(e.NewItems, (item) => InsertItem(item, target, source, convertItemAction, insertItemAction)); break; case NotifyCollectionChangedAction.Remove: DoAction(e.OldItems, (item) => { RemoveItem(e.OldStartingIndex, target, clearItemAction); }); break; case NotifyCollectionChangedAction.Reset: PopulateCore(target, source, convertItemAction, insertItemAction, supportInitialize); break; case NotifyCollectionChangedAction.Move: object insertItem = target[e.OldStartingIndex]; target.RemoveAt(e.OldStartingIndex); target.Insert(e.NewStartingIndex, insertItem); break; case NotifyCollectionChangedAction.Replace: RemoveItem(e.NewStartingIndex, target, clearItemAction); InsertItem(e.NewItems[0], target, source, convertItemAction, insertItemAction); break; } }
public virtual bool AddOrReplace(ApplicationJumpTaskInfo jumpTask) { if (InteractionHelper.IsInDesignMode(this)) { designModeItems.Add(jumpTask); return(true); } ApplicationJumpTaskWrap jumpTaskWrap = new ApplicationJumpTaskWrap(jumpTask); PrepareTask(jumpTaskWrap); ISupportInitialize itemInit = jumpTask; itemInit.EndInit(); JumpItem existingItem = nativeJumpList.Find(jumpTask.CommandId); if (existingItem != null) { nativeJumpList[nativeJumpList.IndexOf(existingItem)] = jumpTaskWrap; return(false); } nativeJumpList.Add(jumpTaskWrap); return(true); }
public void Calling_DeferRefresh_After_BeginInit_Does_Not_Calls_Refresh() { ISupportInitialize isi = this.provider; Exception ex = null; try { isi.BeginInit(); using (provider.DeferRefresh()) { //provider.ItemsSource = new List<Order>(); } provider.BlockUntilRefreshCompletes(); } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.IsFalse(completedEventRaised); }
public void Calling_BeginInit_EndInit_Inside_DeferRefresh_DoesNotCall_Refresh_WhenProviderStateIsChanged() { ISupportInitialize isi = this.provider; Exception ex = null; try { using (provider.DeferRefresh()) { isi.BeginInit(); this.provider.AddPendingChangeToProvider(); isi.EndInit(); Assert.AreEqual(0, this.provider.RefreshCallCount); } } catch (Exception e) { ex = e; } Assert.IsNull(ex); Assert.AreEqual(1, this.provider.RefreshCallCount); }
public static void PopulateCore( IList target, IList source, Func <object, object> convertItemAction, Action <int, object> insertItemAction = null, ISupportInitialize supportInitialize = null, Action <object> clearItemAction = null) { if (target == null) { return; } BeginPopulate(target, supportInitialize); try { var oldItems = target.OfType <object>().ToList(); target.Clear(); if (clearItemAction != null) { oldItems.ForEach(clearItemAction); } if (source == null) { return; } if (insertItemAction == null) { DoAction(source, (item) => AddItem(item, target, convertItemAction)); } else { DoAction(source, (item) => InsertItem(item, target, source, convertItemAction, insertItemAction)); } } finally { EndPopulate(target, supportInitialize); } }
private double ChangeGlyphOrientation(GlyphRunDrawing glyphDrawing, double baselineShiftX, double baselineShiftY, bool isLatin) { if (glyphDrawing == null) { return(0); } GlyphRun glyphRun = glyphDrawing.GlyphRun; GlyphRun verticalRun = new GlyphRun(); ISupportInitialize glyphInit = verticalRun; glyphInit.BeginInit(); verticalRun.IsSideways = true; List <double> advancedHeights = null; double totalHeight = 0; IList <ushort> glyphIndices = glyphRun.GlyphIndices; int advancedCount = glyphIndices.Count; //{ // double textHeight = glyphRun.ComputeInkBoundingBox().Height + glyphRun.ComputeAlignmentBox().Height; // textHeight = textHeight / 2.0d; // totalHeight = advancedCount * textHeight; // advancedHeights = new List<double>(advancedCount); // for (int k = 0; k < advancedCount; k++) // { // advancedHeights.Add(textHeight); // } //} advancedHeights = new List <double>(advancedCount); IDictionary <ushort, double> allGlyphHeights = glyphRun.GlyphTypeface.AdvanceHeights; double fontSize = glyphRun.FontRenderingEmSize; for (int k = 0; k < advancedCount; k++) { double tempValue = allGlyphHeights[glyphIndices[k]] * fontSize; advancedHeights.Add(tempValue); totalHeight += tempValue; } Point baselineOrigin = glyphRun.BaselineOrigin; if (isLatin) { baselineOrigin.X += baselineShiftX; baselineOrigin.Y += baselineShiftY; } //verticalRun.AdvanceWidths = glyphRun.AdvanceWidths; verticalRun.AdvanceWidths = advancedHeights; verticalRun.BaselineOrigin = baselineOrigin; verticalRun.BidiLevel = glyphRun.BidiLevel; verticalRun.CaretStops = glyphRun.CaretStops; verticalRun.Characters = glyphRun.Characters; verticalRun.ClusterMap = glyphRun.ClusterMap; verticalRun.DeviceFontName = glyphRun.DeviceFontName; verticalRun.FontRenderingEmSize = glyphRun.FontRenderingEmSize; verticalRun.GlyphIndices = glyphRun.GlyphIndices; verticalRun.GlyphOffsets = glyphRun.GlyphOffsets; verticalRun.GlyphTypeface = glyphRun.GlyphTypeface; verticalRun.Language = glyphRun.Language; glyphInit.EndInit(); glyphDrawing.GlyphRun = verticalRun; return(totalHeight); }
public ControlInitializationToken(ISupportInitialize control) { _control = control; }
/// <summary> /// Allows a c# using statement to be used for the <see cref="ISupportInitialize"/> contract. /// </summary> public static IDisposable BeginUiUpdate(ISupportInitialize control) { control.BeginInit(); return new ControlInitializationToken(control); }
void RefreshGrid() { ThreadHelper.ThrowIfNotOnUIThread(); ISupportInitialize init = bindingGrid; init.BeginInit(); try { foreach (ChangeSourceControlRow row in bindingGrid.Rows) { row.Refresh(); } } finally { init.EndInit(); } bool enableConnect = false; bool enableDisconnect = false; IAnkhSccService scc = Context.GetService <IAnkhSccService>(); bool isSolution = false; foreach (SccProject project in SelectedProjects) { if (project.IsSolution) { isSolution = true; } if (scc.IsProjectManaged(project)) { enableDisconnect = true; } else if (!enableConnect) { SvnItem item = null; if (!project.IsSolution) { ISccProjectInfo projectInfo = ProjectMapper.GetProjectInfo(project); if (projectInfo == null || string.IsNullOrEmpty(projectInfo.ProjectDirectory)) { continue; } item = StatusCache[projectInfo.SccBaseDirectory]; } else { item = SolutionSettings.ProjectRootSvnItem; } if (item != null && item.Uri != null) { enableConnect = true; } } if (enableConnect && enableDisconnect && isSolution) { break; } } EnableTab(solutionSettingsTab, isSolution); EnableTab(sharedSettingsTab, !isSolution); EnableTab(userSettingsTab, false); UpdateSettingTabs(); connectButton.Enabled = enableConnect; disconnectButton.Enabled = enableDisconnect; UpdateSettingTabs(); }
public int Compare(RawItem xRawItem, RawItem yRawItem) { if (xRawItem == null) { if (yRawItem == null) { return(0); } else { return(-1); } } else { if (yRawItem == null) { return(1); } } ListSortDirection lastSortDirection = ListSortDirection.Ascending; SortDescriptionCollection sortDescriptions = m_collectionView.SortDescriptions; int sortDescriptionCount = sortDescriptions.Count; if (sortDescriptionCount > 0) { int result; DataGridItemPropertyCollection itemProperties = m_collectionView.ItemProperties; for (int i = 0; i < sortDescriptionCount; i++) { SortDescription sortDescription = sortDescriptions[i]; lastSortDirection = sortDescription.Direction; DataGridItemPropertyBase dataProperty = itemProperties[sortDescription.PropertyName]; if (dataProperty == null) { continue; } ISupportInitialize supportInitialize = dataProperty as ISupportInitialize; object xData = null; object yData = null; if (supportInitialize != null) { supportInitialize.BeginInit(); } try { xData = dataProperty.GetValue(xRawItem.DataItem); yData = dataProperty.GetValue(yRawItem.DataItem); } finally { if (supportInitialize != null) { supportInitialize.EndInit(); } } IComparer sortComparer = dataProperty.SortComparer; if (sortComparer != null) { result = sortComparer.Compare(xData, yData); } else { result = ObjectDataStore.CompareData(xData, yData); } if (result != 0) { if (lastSortDirection == ListSortDirection.Descending) { result = -result; } return(result); } } } if (lastSortDirection == ListSortDirection.Descending) { return(yRawItem.Index - xRawItem.Index); } return(xRawItem.Index - yRawItem.Index); }
XamlObject ParseObject(XmlElement element) { Type elementType = settings.TypeFinder.GetType(element.NamespaceURI, element.LocalName); if (elementType == null) { elementType = settings.TypeFinder.GetType(element.NamespaceURI, element.LocalName + "Extension"); if (elementType == null) { throw new XamlLoadException("Cannot find type " + element.Name); } } XmlSpace oldXmlSpace = currentXmlSpace; XamlObject parentXamlObject = currentXamlObject; if (element.HasAttribute("xml:space")) { currentXmlSpace = (XmlSpace)Enum.Parse(typeof(XmlSpace), element.GetAttribute("xml:space"), true); } XamlPropertyInfo defaultProperty = GetDefaultProperty(elementType); XamlTextValue initializeFromTextValueInsteadOfConstructor = null; if (defaultProperty == null) { int numberOfTextNodes = 0; bool onlyTextNodes = true; foreach (XmlNode childNode in element.ChildNodes) { if (childNode.NodeType == XmlNodeType.Text) { numberOfTextNodes++; } else if (childNode.NodeType == XmlNodeType.Element) { onlyTextNodes = false; } } if (onlyTextNodes && numberOfTextNodes == 1) { foreach (XmlNode childNode in element.ChildNodes) { if (childNode.NodeType == XmlNodeType.Text) { initializeFromTextValueInsteadOfConstructor = (XamlTextValue)ParseValue(childNode); } } } } object instance; if (initializeFromTextValueInsteadOfConstructor != null) { instance = TypeDescriptor.GetConverter(elementType).ConvertFromString( document.GetTypeDescriptorContext(null), CultureInfo.InvariantCulture, initializeFromTextValueInsteadOfConstructor.Text); } else { instance = settings.CreateInstanceCallback(elementType, emptyObjectArray); } XamlObject obj = new XamlObject(document, element, elementType, instance); currentXamlObject = obj; obj.ParentObject = parentXamlObject; if (parentXamlObject == null && obj.Instance is DependencyObject) { NameScope.SetNameScope((DependencyObject)obj.Instance, new NameScope()); } ISupportInitialize iSupportInitializeInstance = instance as ISupportInitialize; if (iSupportInitializeInstance != null) { iSupportInitializeInstance.BeginInit(); } foreach (XmlAttribute attribute in element.Attributes) { if (attribute.Value.StartsWith("clr-namespace", StringComparison.OrdinalIgnoreCase)) { // the format is "clr-namespace:<Namespace here>;assembly=<Assembly name here>" var clrNamespace = attribute.Value.Split(new[] { ':', ';', '=' }); if (clrNamespace.Length == 4) { // get the assembly name var assembly = settings.TypeFinder.LoadAssembly(clrNamespace[3]); if (assembly != null) { settings.TypeFinder.RegisterAssembly(assembly); } } else { // if no assembly name is there, then load the assembly of the opened file. var assembly = settings.TypeFinder.LoadAssembly(null); if (assembly != null) { settings.TypeFinder.RegisterAssembly(assembly); } } } if (attribute.NamespaceURI == XamlConstants.XmlnsNamespace) { continue; } if (attribute.Name == "xml:space") { continue; } if (GetAttributeNamespace(attribute) == XamlConstants.XamlNamespace) { if (attribute.LocalName == "Name") { try { NameScopeHelper.NameChanged(obj, null, attribute.Value); } catch (Exception x) { ReportException(x, attribute); } } continue; } ParseObjectAttribute(obj, attribute); } if (!(obj.Instance is Style)) { ParseObjectContent(obj, element, defaultProperty, initializeFromTextValueInsteadOfConstructor); } if (iSupportInitializeInstance != null) { iSupportInitializeInstance.EndInit(); } currentXmlSpace = oldXmlSpace; currentXamlObject = parentXamlObject; return(obj); }
/// <summary> /// Allows a c# using statement to be used for the <see cref="ISupportInitialize"/> contract. /// </summary> public static IDisposable BeginUiUpdate(ISupportInitialize control) { control.BeginInit(); return(new ControlInitializationToken(control)); }
/// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyNominalType(nominalType); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == Bson.BsonType.Null) { bsonReader.ReadNull(); return(null); } else { if (actualType != _classMap.ClassType) { var message = string.Format("BsonClassMapSerializer.Deserialize for type {0} was called with actualType {1}.", BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType)); throw new BsonSerializationException(message); } if (actualType.IsValueType) { var message = string.Format("Value class {0} cannot be deserialized.", actualType.FullName); throw new BsonSerializationException(message); } if (_classMap.IsAnonymous) { throw new InvalidOperationException("An anonymous class cannot be deserialized."); } if (bsonType != BsonType.Document) { var message = string.Format( "Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.", actualType.FullName, bsonType); throw new FileFormatException(message); } Dictionary <string, object> values = null; object obj = null; ISupportInitialize supportsInitialization = null; if (_classMap.HasCreatorMaps) { // for creator-based deserialization we first gather the values in a dictionary and then call a matching creator values = new Dictionary <string, object>(); } else { // for mutable classes we deserialize the values directly into the result object obj = _classMap.CreateInstance(); supportsInitialization = obj as ISupportInitialize; if (supportsInitialization != null) { supportsInitialization.BeginInit(); } } var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count); bsonReader.ReadStartDocument(); var elementTrie = _classMap.ElementTrie; bool memberMapFound; int memberMapIndex; while (bsonReader.ReadBsonType(elementTrie, out memberMapFound, out memberMapIndex) != BsonType.EndOfDocument) { var elementName = bsonReader.ReadName(); if (memberMapFound) { var memberMap = allMemberMaps[memberMapIndex]; if (memberMapIndex != extraElementsMemberMapIndex) { if (obj != null) { if (memberMap.IsReadOnly) { bsonReader.SkipValue(); } else { var value = DeserializeMemberValue(bsonReader, memberMap); memberMap.Setter(obj, value); } } else { var value = DeserializeMemberValue(bsonReader, memberMap); values[elementName] = value; } } else { DeserializeExtraElement(bsonReader, obj, elementName, memberMap); } memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31); } else { if (elementName == discriminatorConvention.ElementName) { bsonReader.SkipValue(); // skip over discriminator continue; } if (extraElementsMemberMapIndex >= 0) { DeserializeExtraElement(bsonReader, obj, elementName, _classMap.ExtraElementsMemberMap); memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31); } else if (_classMap.IgnoreExtraElements) { bsonReader.SkipValue(); } else { var message = string.Format( "Element '{0}' does not match any field or property of class {1}.", elementName, _classMap.ClassType.FullName); throw new FileFormatException(message); } } } bsonReader.ReadEndDocument(); // check any members left over that we didn't have elements for (in blocks of 32 elements at a time) for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex) { memberMapIndex = bitArrayIndex << 5; var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements // work through this memberMapBlock of 32 elements while (true) { // examine missing elements (memberMapBlock is shifted right as we work through the block) for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1) { var memberMap = allMemberMaps[memberMapIndex]; if (memberMap.IsReadOnly) { continue; } if (memberMap.IsRequired) { var fieldOrProperty = (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property"; var message = string.Format( "Required element '{0}' for {1} '{2}' of class {3} is missing.", memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName); throw new FileFormatException(message); } if (obj != null) { memberMap.ApplyDefaultValue(obj); } else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly) { values[memberMap.ElementName] = memberMap.DefaultValue; } } if (memberMapBlock == 0) { break; } // skip ahead to the next missing element var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock); memberMapIndex += leastSignificantBit; memberMapBlock >>= leastSignificantBit; } } if (obj != null) { if (supportsInitialization != null) { supportsInitialization.EndInit(); } return(obj); } else { return(CreateInstanceUsingCreator(values)); } } }
/// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <returns>A deserialized value.</returns> public TClass DeserializeClass(BsonDeserializationContext context) { var bsonReader = context.Reader; var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType != BsonType.Document) { var message = string.Format( "Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.", typeof(TClass).FullName, bsonType); throw new FormatException(message); } Dictionary <string, object> values = null; var document = default(TClass); #if NET452 || NETSTANDARD2_0 ISupportInitialize supportsInitialization = null; #endif if (_classMap.HasCreatorMaps) { // for creator-based deserialization we first gather the values in a dictionary and then call a matching creator values = new Dictionary <string, object>(); } else { // for mutable classes we deserialize the values directly into the result object document = (TClass)_classMap.CreateInstance(); #if NET452 || NETSTANDARD2_0 supportsInitialization = document as ISupportInitialize; if (supportsInitialization != null) { supportsInitialization.BeginInit(); } #endif #if NETSTANDARD1_5 if (_beginInitMethodInfo != null) { _beginInitMethodInfo.Invoke(document, new object[0]); } #endif } var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count); bsonReader.ReadStartDocument(); var elementTrie = _classMap.ElementTrie; while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var trieDecoder = new TrieNameDecoder <int>(elementTrie); var elementName = bsonReader.ReadName(trieDecoder); if (trieDecoder.Found) { var memberMapIndex = trieDecoder.Value; var memberMap = allMemberMaps[memberMapIndex]; if (memberMapIndex != extraElementsMemberMapIndex) { if (document != null) { if (memberMap.IsReadOnly) { bsonReader.SkipValue(); } else { var value = DeserializeMemberValue(context, memberMap); memberMap.Setter(document, value); } } else { var value = DeserializeMemberValue(context, memberMap); values[elementName] = value; } } else { if (document != null) { DeserializeExtraElementMember(context, document, elementName, memberMap); } else { DeserializeExtraElementValue(context, values, elementName, memberMap); } } memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31); } else { if (elementName == discriminatorConvention.ElementName) { bsonReader.SkipValue(); // skip over discriminator continue; } if (extraElementsMemberMapIndex >= 0) { var extraElementsMemberMap = _classMap.ExtraElementsMemberMap; if (document != null) { DeserializeExtraElementMember(context, document, elementName, extraElementsMemberMap); } else { DeserializeExtraElementValue(context, values, elementName, extraElementsMemberMap); } memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31); } else if (_classMap.IgnoreExtraElements) { bsonReader.SkipValue(); } else { var message = string.Format( "Element '{0}' does not match any field or property of class {1}.", elementName, _classMap.ClassType.FullName); throw new FormatException(message); } } } bsonReader.ReadEndDocument(); // check any members left over that we didn't have elements for (in blocks of 32 elements at a time) for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex) { var memberMapIndex = bitArrayIndex << 5; var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements // work through this memberMapBlock of 32 elements while (true) { // examine missing elements (memberMapBlock is shifted right as we work through the block) for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1) { var memberMap = allMemberMaps[memberMapIndex]; if (memberMap.IsReadOnly) { continue; } if (memberMap.IsRequired) { var fieldOrProperty = (memberMap.MemberInfo is FieldInfo) ? "field" : "property"; var message = string.Format( "Required element '{0}' for {1} '{2}' of class {3} is missing.", memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName); throw new FormatException(message); } if (document != null) { memberMap.ApplyDefaultValue(document); } else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly) { values[memberMap.ElementName] = memberMap.DefaultValue; } } if (memberMapBlock == 0) { break; } // skip ahead to the next missing element var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock); memberMapIndex += leastSignificantBit; memberMapBlock >>= leastSignificantBit; } } if (document != null) { #if NET452 || NETSTANDARD2_0 if (supportsInitialization != null) { supportsInitialization.EndInit(); } #endif #if NETSTANDARD1_5 if (_endInitMethodInfo != null) { _endInitMethodInfo.Invoke(document, new object[0]); } #endif return(document); } else { return(CreateInstanceUsingCreator(values)); } }
public Initializer(ISupportInitialize toInit) { Helper.GuardNotNull(toInit); _toInit = toInit; _toInit.BeginInit(); }