public void MultipleLevelScoping() { ScopeManager <object> scopeManager = null; using (scopeManager = ScopeManager <object> .GetScopeManager("object")) { Assert.AreEqual(1, scopeManager.RefCount); using (ScopeManager <object> .GetScopeManager("object")) { Assert.AreEqual(2, scopeManager.RefCount); using (ScopeManager <object> .GetScopeManager("object")) { Assert.AreEqual(3, scopeManager.RefCount); } Assert.AreEqual(2, scopeManager.RefCount); } Assert.AreEqual(1, scopeManager.RefCount); } Assert.AreEqual(0, scopeManager.RefCount); }
private void OnDeserialized(StreamingContext context) { IsDeserializedDataAvailable = true; if (_serializationInfo == null) { // Probably a custom serializer which will populate us in a different way return; } var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, () => new SerializationScope(SerializationFactory.GetBinarySerializer(), SerializationConfiguration))) { var serializer = scopeManager.ScopeObject.Serializer; var configuration = scopeManager.ScopeObject.Configuration; var dependencyResolver = this.GetDependencyResolver(); var serializationContextInfoFactory = dependencyResolver.Resolve <ISerializationContextInfoFactory>(serializer.GetType()); var serializationContext = serializationContextInfoFactory.GetSerializationContextInfo(serializer, this, _serializationInfo, configuration); serializer.Deserialize(this, serializationContext, configuration); } DeserializationSucceeded = true; }
public FeedVerificationResult VerifyFeed(string source, bool authenticateIfRequired = true) { var result = FeedVerificationResult.Valid; Log.Debug("Verifying feed '{0}'", source); using (ScopeManager <AuthenticationScope> .GetScopeManager(source.GetSafeScopeName(), () => new AuthenticationScope(authenticateIfRequired))) { try { var repository = _packageRepositoryFactory.CreateRepository(source); repository.GetPackages().Take(1).Count(); } catch (WebException ex) { result = HandleWebException(ex, source); } catch (UriFormatException ex) { Log.Debug(ex, "Failed to verify feed '{0}', a UriFormatException occurred", source); result = FeedVerificationResult.Invalid; } catch (Exception ex) { Log.Debug(ex, "Failed to verify feed '{0}'", source); result = FeedVerificationResult.Invalid; } } Log.Debug("Verified feed '{0}', result is '{1}'", source, result); return(result); }
protected override async Task <bool> SaveAsync() { var editablePackageSource = EditablePackageSources; if (editablePackageSource == null) { return(false); } if (editablePackageSource.Any(x => x.IsValid == null)) { return(false); } _ignoreNextPackageUpdate = true; PackageSources = editablePackageSource.Select(x => { using (ScopeManager <AuthenticationScope> .GetScopeManager(x.Source.GetSafeScopeName(), () => new AuthenticationScope(false))) { var packageSource = _packageSourceFactory.CreatePackageSource(x.Source, x.Name, x.IsEnabled, false); return(packageSource); } }).ToArray(); return(await base.SaveAsync()); }
/// <summary> /// Gets the current serialization scope. /// </summary> /// <param name="configuration">The configuration.</param> /// <returns></returns> protected virtual ScopeManager <SerializationScope> GetCurrentSerializationScopeManager(ISerializationConfiguration configuration) { var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, () => new SerializationScope(this, configuration ?? DefaultSerializationConfiguration)); return(scopeManager); }
private void OnDeserialized(StreamingContext context) { #if NET || NETCORE if (_serializationInfo is null) { // Probably a custom serializer which will populate us in a different way return; } var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, BinarySerializationScopeFactory)) { var serializer = scopeManager.ScopeObject.Serializer; var configuration = scopeManager.ScopeObject.Configuration; var dependencyResolver = this.GetDependencyResolver(); var serializationContextInfoFactory = dependencyResolver.Resolve <ISerializationContextInfoFactory>(serializer.GetType()); var serializationContext = serializationContextInfoFactory.GetSerializationContextInfo(serializer, this, _serializationInfo, configuration); serializer.Deserialize(this, serializationContext, configuration); } #else throw new NotSupportedInPlatformException("It's adviced to no longer use binary serialization on this platform"); #endif }
/// <summary> /// Initializes a new instance of the <see cref="ModelBase"/> class. /// <para /> /// Only constructor for the ModelBase. /// </summary> /// <param name="info">SerializationInfo object, null if this is the first time construction.</param> /// <param name="context">StreamingContext object, simple pass a default new StreamingContext() if this is the first time construction.</param> /// <remarks> /// Call this method, even when constructing the object for the first time (thus not deserializing). /// </remarks> protected ModelBase(SerializationInfo info, StreamingContext context) { Initialize(); // Make sure this is not a first time call or custom call with null if (info != null) { _serializationInfo = info; // Too bad we cannot put this in the BinarySerializer, but BinarySerialization works bottom => top. We // do need the GraphId though, thus we are setting it here var scopeName = SerializationContextHelper.GetSerializationScopeName(); using (var scopeManager = ScopeManager <SerializationContextScope <BinarySerializationContextInfo> > .GetScopeManager(scopeName)) { var referenceManager = scopeManager.ScopeObject.ReferenceManager; int?graphId = null; try { // Binary graphId = (int)info.GetValue("GraphId", typeof(int)); } catch (Exception) { // Swallow } if (graphId.HasValue) { referenceManager.RegisterManually(graphId.Value, this); } } } }
/// <summary> /// Initializes a new instance of the <see cref="SerializationContext{TContext}" /> class. /// </summary> /// <param name="model">The model, can be <c>null</c> for value types.</param> /// <param name="modelType">Type of the model.</param> /// <param name="context">The context.</param> /// <param name="contextMode">The context mode.</param> /// <param name="configuration">The configuration.</param> /// <exception cref="ArgumentNullException">The <paramref name="modelType" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="context" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="configuration" /> is <c>null</c>.</exception> public SerializationContext(object model, Type modelType, TContext context, SerializationContextMode contextMode, ISerializationConfiguration configuration = null) { Argument.IsNotNull("modelType", modelType); Argument.IsNotNull("context", context); Argument.IsNotNull("configuration", configuration); Model = model; ModelType = modelType; ModelTypeName = modelType.GetSafeFullName(false); Context = context; ContextMode = contextMode; TypeStack = new Stack <Type>(); Configuration = configuration; var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); _typeStackScopeManager = ScopeManager <Stack <Type> > .GetScopeManager(scopeName, () => new Stack <Type>()); TypeStack = _typeStackScopeManager.ScopeObject; _referenceManagerScopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName); ReferenceManager = _referenceManagerScopeManager.ScopeObject; _serializableToken = CreateSerializableToken(); }
/// <summary> /// Writes the json. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> /// <param name="serializer">The serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var serialize = true; if (_jsonSerializer.PreserveReferences) { var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName)) { var referenceManager = scopeManager.ScopeObject; var referenceInfo = referenceManager.GetInfo(value); if (referenceInfo != null && !referenceInfo.IsFirstUsage) { writer.WriteStartObject(); writer.WritePropertyName(Json.JsonSerializer.GraphRefId); writer.WriteValue(referenceInfo.Id); writer.WriteEndObject(); serialize = false; } } } if (serialize) { _jsonSerializer.Serialize((ModelBase)value, writer); } }
public async Task <AuthenticationCredentials> GetCredentialsAsync(Uri uri, bool previousCredentialsFailed) { Log.Debug("Requesting credentials for '{0}'", uri); bool?result = null; var credentials = new AuthenticationCredentials(uri); using (_pleaseWaitInterruptService.Value.InterruptTemporarily()) { await DispatchHelper.DispatchIfNecessaryAsync(() => { var uriString = uri.ToString().ToLower(); using (var scopeManager = ScopeManager <AuthenticationScope> .GetScopeManager(uriString.GetSafeScopeName(), () => new AuthenticationScope())) { var authenticationScope = scopeManager.ScopeObject; var credentialsPrompter = new CredentialsPrompter(_configurationService) { Target = uriString, UserName = string.Empty, Password = string.Empty, AllowStoredCredentials = !previousCredentialsFailed, ShowSaveCheckBox = true, WindowTitle = "Credentials required", MainInstruction = "Credentials are required to access this feed", Content = string.Format("In order to continue, please enter the credentials for {0} below.", uri), IsAuthenticationRequired = authenticationScope.CanPromptForAuthentication }; authenticationScope.HasPromptedForAuthentication = true; result = credentialsPrompter.ShowDialog(); if (result ?? false) { credentials.UserName = credentialsPrompter.UserName; credentials.Password = credentialsPrompter.Password; } else { credentials.StoreCredentials = false; } } }); } if (result ?? false) { Log.Debug("Successfully requested credentials for '{0}' using user '{1}'", uri, credentials.UserName); return(credentials); } Log.Debug("Failed to request credentials for '{0}'", uri); return(null); }
public void ReturnsTrueForExistignScope() { Assert.IsFalse(ScopeManager <string> .ScopeExists()); using (var scopeManager = ScopeManager <string> .GetScopeManager()) { Assert.IsTrue(ScopeManager <string> .ScopeExists()); } Assert.IsFalse(ScopeManager <string> .ScopeExists()); }
/// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> void IXmlSerializable.WriteXml(XmlWriter writer) { // Note: although this XmlWriter doesn't have settings, it has an internal writer that // is used (with the correct settings). For more details, see the source at: // https://referencesource.microsoft.com/#System.Runtime.Serialization/System/Runtime/Serialization/XmlSerializableWriter.cs var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, XmlSerializationScopeFactory)) { var serializer = scopeManager.ScopeObject.Serializer; serializer.Serialize(this, new XmlSerializationContextInfo(writer, this), scopeManager.ScopeObject.Configuration); } }
/// <summary> /// Gets the namespace for the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="preferredPrefix">The preferred prefix.</param> /// <returns>The xml namespace.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException">The <paramref name="preferredPrefix"/> is <c>null</c> or whitespace.</exception> public XmlNamespace GetNamespace(Type type, string preferredPrefix) { Argument.IsNotNull("type", type); var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var serializationManagerScopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName)) { EnsureSubscribedToScope(serializationManagerScopeManager, scopeName); var scopeInfo = _scopeInfo[scopeName]; return(scopeInfo.GetNamespace(type, preferredPrefix)); } }
public void CustomScopeCreationTest() { var obj1 = "15"; var obj2 = "16"; using (var scope1Manager = ScopeManager <string> .GetScopeManager(createScopeFunction: () => obj1)) { using (var scope2Manager = ScopeManager <string> .GetScopeManager(createScopeFunction: () => obj2)) { Assert.AreEqual(obj1, scope2Manager.ScopeObject); Assert.AreEqual(2, scope2Manager.RefCount); } } }
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <ISerializer> .GetScopeManager(scopeName, SerializationFactory.GetBinarySerializer)) { var serializer = scopeManager.ScopeObject; var dependencyResolver = this.GetDependencyResolver(); var serializationContextInfoFactory = dependencyResolver.Resolve <ISerializationContextInfoFactory>(serializer.GetType()); var serializationContext = serializationContextInfoFactory.GetSerializationContextInfo(serializer, this, info); serializer.Serialize(this, serializationContext); } }
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager<SerializationScope>.GetScopeManager(scopeName, () => new SerializationScope(SerializationFactory.GetBinarySerializer(), null))) { var serializer = scopeManager.ScopeObject.Serializer; var configuration = scopeManager.ScopeObject.Configuration; var dependencyResolver = this.GetDependencyResolver(); var serializationContextInfoFactory = dependencyResolver.Resolve<ISerializationContextInfoFactory>(serializer.GetType()); var serializationContext = serializationContextInfoFactory.GetSerializationContextInfo(serializer, this, info, configuration); serializer.Serialize(this, serializationContext, configuration); } }
/// <summary> /// Serializes the specified model. /// </summary> /// <param name="model">The model.</param> /// <param name="context">The context.</param> public virtual void Serialize(object model, TSerializationContext context) { Argument.IsNotNull("model", model); Argument.IsNotNull("context", context); var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (ScopeManager <ISerializer> .GetScopeManager(scopeName, () => this)) { using (var finalContext = GetContext(model, model.GetType(), context, SerializationContextMode.Serialization)) { Serialize(model, finalContext); } } }
/// <summary> /// Initializes a new instance of the <see cref="SerializationContext{TContext}" /> class. /// </summary> /// <param name="model">The model.</param> /// <param name="context">The context.</param> /// <param name="contextMode">The context mode.</param> /// <exception cref="ArgumentNullException">The <paramref name="model" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="context" /> is <c>null</c>.</exception> public SerializationContext(ModelBase model, TContext context, SerializationContextMode contextMode) { Argument.IsNotNull("model", model); Argument.IsNotNull("context", context); Model = model; ModelType = model.GetType(); Context = context; ContextMode = contextMode; var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); _referenceManagerScopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName); ReferenceManager = _referenceManagerScopeManager.ScopeObject; }
/// <summary> /// Serializes the members. /// </summary> /// <param name="context">The context.</param> /// <param name="membersToSerialize">The members to serialize.</param> protected virtual void SerializeMembers(ISerializationContext <TSerializationContext> context, List <MemberValue> membersToSerialize) { ApiCop.UpdateRule <InitializationApiCopRule>("SerializerBase.WarmupAtStartup", x => x.SetInitializationMode(InitializationMode.Lazy, GetType().GetSafeFullName())); var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (ScopeManager <ISerializer> .GetScopeManager(scopeName, () => this)) { var serializerModifiers = SerializationManager.GetSerializerModifiers(context.ModelType); foreach (var member in membersToSerialize) { bool skipByModifiers = false; foreach (var serializerModifier in serializerModifiers) { if (serializerModifier.ShouldIgnoreMember(context, context.Model, member)) { skipByModifiers = true; break; } } if (skipByModifiers) { continue; } var memberSerializationEventArgs = new MemberSerializationEventArgs(context, member); SerializingMember.SafeInvoke(this, memberSerializationEventArgs); BeforeSerializeMember(context, member); foreach (var serializerModifier in serializerModifiers) { serializerModifier.SerializeMember(context, member); } SerializeMember(context, member); AfterSerializeMember(context, member); SerializedMember.SafeInvoke(this, memberSerializationEventArgs); } } }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> void IXmlSerializable.ReadXml(XmlReader reader) { if (reader.IsEmptyElement && !reader.HasAttributes) { return; } var contextInfo = new XmlSerializationContextInfo(reader, this); var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, () => new SerializationScope(SerializationFactory.GetXmlSerializer(), SerializationConfiguration))) { var serializer = scopeManager.ScopeObject.Serializer; serializer.Deserialize(this, contextInfo, scopeManager.ScopeObject.Configuration); } }
private async Task CountAndSearchAsync() { var selectedRepository = Navigator.SelectedRepository; if (selectedRepository is null) { return; } try { _dispatcherService.BeginInvoke(() => SearchResult.PackageList.Clear()); using (ScopeManager <AuthenticationScope> .GetScopeManager(selectedRepository.Source.GetSafeScopeName(), () => new AuthenticationScope())) { using (_pleaseWaitService.WaitingScope()) { var searchSettings = SearchSettings; SearchResult.TotalPackagesCount = await TaskHelper.Run(() => _packageQueryService.CountPackages(selectedRepository, searchSettings.SearchFilter, IsPrereleaseAllowed ?? true), true); var packageDetails = await TaskHelper.Run(() => _packageQueryService.GetPackages(selectedRepository, IsPrereleaseAllowed ?? true, searchSettings.SearchFilter, searchSettings.PackagesToSkip), true); var packages = packageDetails; _dispatcherService.BeginInvoke(() => { using (SearchResult.PackageList.SuspendChangeNotifications()) { CollectionExtensions.AddRange(((ICollection <IPackageDetails>)SearchResult.PackageList), packages); } }); } } } catch (Exception ex) { Log.Error(ex, "Failed to search packages"); } finally { // Note: this is hack Navigator.SelectedRepository = selectedRepository; } }
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { #if NET || NETCORE var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, BinarySerializationScopeFactory)) { var serializer = scopeManager.ScopeObject.Serializer; var configuration = scopeManager.ScopeObject.Configuration; var dependencyResolver = this.GetDependencyResolver(); var serializationContextInfoFactory = dependencyResolver.Resolve <ISerializationContextInfoFactory>(serializer.GetType()); var serializationContext = serializationContextInfoFactory.GetSerializationContextInfo(serializer, this, info, configuration); serializer.Serialize(this, serializationContext, configuration); } #else throw new NotSupportedInPlatformException("It's adviced to no longer use binary serialization on this platform"); #endif }
public IEnumerable <IPackageDetails> SearchForUpdates(bool?allowPrerelease = null, bool authenticateIfRequired = true) { var scopeManagers = new List <ScopeManager <AuthenticationScope> >(); try { Log.Debug("Searching for updates, allowPrerelease = {0}, authenticateIfRequired = {1}", allowPrerelease, authenticateIfRequired); var sourceRepositories = _repositoryService.GetSourceRepositories(); foreach (var repository in sourceRepositories) { var scopeManager = ScopeManager <AuthenticationScope> .GetScopeManager(repository.Source.GetSafeScopeName(), () => new AuthenticationScope(authenticateIfRequired)); scopeManagers.Add(scopeManager); } var availableUpdates = new List <IPackageDetails>(); var packageRepository = _repositoryCacheService.GetNuGetRepository(_repositoryService.GetSourceAggregateRepository()); var packages = _repositoryCacheService.GetNuGetRepository(_repositoryService.LocalRepository).GetPackages(); foreach (var package in packages) { var prerelease = allowPrerelease ?? package.IsPrerelease(); var packageUpdates = packageRepository.GetUpdates(new[] { package }, prerelease, false).Select(x => _packageCacheService.GetPackageDetails(packageRepository, x, allowPrerelease ?? true)); availableUpdates.AddRange(packageUpdates); } Log.Debug("Finished searching for updates, found '{0}' updates", availableUpdates.Count); return(availableUpdates); } finally { foreach (var scopeManager in scopeManagers) { scopeManager.Dispose(); } scopeManagers.Clear(); } }
/// <summary> /// Initializes a new instance of the <see cref="SerializationContext{TContext}" /> class. /// </summary> /// <param name="model">The model, can be <c>null</c> for value types.</param> /// <param name="modelType">Type of the model.</param> /// <param name="context">The context.</param> /// <param name="contextMode">The context mode.</param> /// <param name="configuration">The configuration.</param> /// <exception cref="ArgumentNullException">The <paramref name="modelType" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="modelType" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="modelType" /> is <c>null</c>.</exception> public SerializationContext(object model, Type modelType, TSerializationContextInfo context, SerializationContextMode contextMode, ISerializationConfiguration configuration = null) { Argument.IsNotNull("modelType", modelType); Argument.IsNotNull("context", context); Argument.IsNotNull("configuration", configuration); Model = model; ModelType = modelType; ModelTypeName = modelType.GetSafeFullName(false); Context = context; ContextMode = contextMode; TypeStack = new Stack <Type>(); Configuration = configuration; var scopeName = SerializationContextHelper.GetSerializationScopeName(); _scopeManager = ScopeManager <SerializationContextScope <TSerializationContextInfo> > .GetScopeManager(scopeName, () => new SerializationContextScope <TSerializationContextInfo>()); var contextScope = _scopeManager.ScopeObject; TypeStack = contextScope.TypeStack; ReferenceManager = contextScope.ReferenceManager; Contexts = contextScope.Contexts; var contexts = contextScope.Contexts; if (contexts.Count > 0) { Parent = contexts.Peek(); } var serializationContextInfoParentSetter = context as ISerializationContextContainer; if (serializationContextInfoParentSetter != null) { serializationContextInfoParentSetter.SetSerializationContext(this); } Initialize(); }
/// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> void IXmlSerializable.WriteXml(XmlWriter writer) { var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <SerializationScope> .GetScopeManager(scopeName, () => new SerializationScope(SerializationFactory.GetXmlSerializer(), SerializationConfiguration))) { var type = GetType(); var element = new XElement(type.Name); var serializer = scopeManager.ScopeObject.Serializer; serializer.Serialize(this, new XmlSerializationContextInfo(element, this), scopeManager.ScopeObject.Configuration); // The serializer gives us the full element, but we only need the actual content. According to // http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement, this method is the fastest: var reader = element.CreateReader(); reader.MoveToContent(); // CTL-710: fix attributes on top level elements if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); var attributePrefix = reader.Prefix; var attributeLocalName = reader.LocalName; var attributeNs = reader.NamespaceURI; var attributeValue = reader.Value; writer.WriteAttributeString(attributePrefix, attributeLocalName, attributeNs, attributeValue); } reader.MoveToElement(); } var elementContent = reader.ReadInnerXml(); writer.WriteRaw(elementContent); } }
/// <summary> /// Initializes a new instance of the <see cref="ModelBase"/> class. /// <para /> /// Only constructor for the ModelBase. /// </summary> /// <param name="info">SerializationInfo object, null if this is the first time construction.</param> /// <param name="context">StreamingContext object, simple pass a default new StreamingContext() if this is the first time construction.</param> /// <remarks> /// Call this method, even when constructing the object for the first time (thus not deserializing). /// </remarks> protected ModelBase(SerializationInfo info, StreamingContext context) { OnInitializing(); Initialize(); // Make sure this is not a first time call or custom call with null if (info == null) { FinishInitializationAfterConstructionOrDeserialization(); } else { _serializationInfo = info; // Too bad we cannot put this in the BinarySerializer, but BinarySerialization works bottom => top. We // do need the GraphId though, thus we are setting it here var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName)) { var referenceManager = scopeManager.ScopeObject; try { var graphId = (int)info.GetValue("GraphId", typeof(int)); referenceManager.RegisterManually(graphId, this); } catch (Exception) { // Swallow } } } OnInitialized(); }
/// <summary> /// Deserializes the specified model from the json reader. /// </summary> /// <param name="modelType">Type of the model.</param> /// <param name="jsonReader">The json reader.</param> /// <param name="configuration">The configuration.</param> /// <returns> /// The model. /// </returns> public object Deserialize(Type modelType, JsonReader jsonReader, ISerializationConfiguration configuration) { Dictionary <string, JProperty> jsonProperties = null; JArray jsonArray = null; if (modelType.ImplementsInterfaceEx <ICustomJsonSerializable>()) { var customModel = CreateModelInstance(modelType) as ICustomJsonSerializable; if (customModel == null) { throw Log.ErrorAndCreateException <SerializationException>($"'{modelType.GetSafeFullName(false)}' implements ICustomJsonSerializable but could not be instantiated"); } customModel.Deserialize(jsonReader); return(customModel); } if (ShouldSerializeAsCollection(modelType)) { jsonArray = JArray.Load(jsonReader); } else if (ShouldExternalSerializerHandleMember(modelType)) { return(Convert.ChangeType(jsonReader.Value, modelType, CultureInfo.CurrentCulture)); } else { if (jsonReader.TokenType == JsonToken.Null) { return(null); } var jsonObject = JObject.Load(jsonReader); jsonProperties = jsonObject.Properties().ToDictionary(x => x.Name, x => x); if (PreserveReferences) { if (jsonProperties.ContainsKey(GraphRefId)) { var graphId = (int)jsonProperties[GraphRefId].Value; var scopeName = SerializationContextHelper.GetSerializationReferenceManagerScopeName(); using (var scopeManager = ScopeManager <ReferenceManager> .GetScopeManager(scopeName)) { var referenceManager = scopeManager.ScopeObject; var referenceInfo = referenceManager.GetInfoById(graphId); if (referenceInfo != null) { return(referenceInfo.Instance); } } } } if (jsonProperties.ContainsKey(TypeName)) { var modelTypeOverrideValue = (string)jsonProperties[TypeName].Value; var modelTypeOverride = TypeCache.GetTypeWithoutAssembly(modelTypeOverrideValue); if (modelTypeOverride == null) { Log.Warning("Object was serialized as '{0}', but the type is not available. Using original type '{1}'", modelTypeOverrideValue, modelType.GetSafeFullName(false)); } else { modelType = modelTypeOverride; } } } var model = CreateModelInstance(modelType); using (GetCurrentSerializationScopeManager(configuration)) { configuration = GetCurrentSerializationConfiguration(configuration); using (var context = GetContext(model, modelType, jsonReader, null, SerializationContextMode.Deserialization, jsonProperties, jsonArray, configuration)) { model = base.Deserialize(model, context.Context, configuration); } } return(model); }