Exception trying to Update Service reference! - c#

I have a Silverlight Application that use a WebService for MultPorpose,
When i usa that markers:
[XmlInclude(typeof(StringCustomField))]
In on of my classes i get that error:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
contract: SCI4WebService ----> **System.IO.FileNotFoundException: Could not load file or assembly 'System.Xml**, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. O sistema não pode encontrar o arquivo especificado.
at System.ModuleHandle.ResolveType(Int32 typeToken, RuntimeTypeHandle* typeInstArgs, Int32 typeInstCount, RuntimeTypeHandle* methodInstArgs, Int32 methodInstCount)
at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.Module.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, Module decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, RuntimeMethodHandle& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(Module decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
at System.Runtime.Serialization.DataContract.TryGetDCAttribute(Type type, DataContractAttribute& dataContractAttribute)
at System.Runtime.Serialization.DataContract.GetStableName(Type type, Boolean& hasDataContract)
at System.Runtime.Serialization.DataContract.GetCollectionStableName(Type type, Type itemType, CollectionDataContractAttribute& collectionContractAttribute)
at System.Runtime.Serialization.CollectionDataContract.CollectionDataContractCriticalHelper..ctor(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
at System.Runtime.Serialization.CollectionDataContract.IsCollectionOrTryCreate(Type type, Boolean tryCreate, DataContract& dataContract, Type& itemType, Boolean constructorRequired)
at System.Runtime.Serialization.CollectionDataContract.TryCreate(Type type, DataContract& dataContract)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
at System.Runtime.Serialization.DataContractSet.GetDataContract(Type clrType)
at System.Runtime.Serialization.DataContractSet.GetMemberTypeDataContract(DataMember dataMember)
at System.Runtime.Serialization.DataContractSet.AddClassDataContract(ClassDataContract classDataContract)
at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
at System.Runtime.Serialization.DataContractSet.AddCollectionDataContract(CollectionDataContract collectionDataContract)
at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
at System.Runtime.Serialization.DataContractSet.AddClassDataContract(ClassDataContract classDataContract)
at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
at System.Runtime.Serialization.DataContractSet.AddCollectionDataContract(CollectionDataContract collectionDataContract)
at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
at System.Runtime.Serialization.DataContractSet.AddClassDataContract(ClassDataContract classDataContract)
at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
at System.Runtime.Serialization.DataContractSet.Add(Type type)
at System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
at System.ServiceModel.Description.MessageContractExporter.ExportType(Type type, String partName, String operationName, XmlSchemaType& xsdType)
at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.ExportBody(Int32 messageIndex, Object state)
at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
at System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext contractContext)
at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
--- End of inner ExceptionDetail stack trace ---
at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
at SyncInvokeGet(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</PRE></DIV></BODY></HTML>
--.
Metadata contains a reference that cannot be resolved: 'http://localhost:1071/SCI4WebService.svc'.
Content Type application/soap+xml; charset=utf-8 was not supported by service http://localhost:1071/SCI4WebService.svc. The client and service bindings may be mismatched.
The remote server returned an error: (415) Unsupported Media Type.
If the service is defined in the current solution, try building the solution and adding the service reference again.
I have no ideas, try to reference XML namespace in all projects and nothing!!!
Help!!
Looking for a answer i see that:
i have two System.Xml on my machine:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll - 2.0.0.0
C:\Arquivos de programas\Microsoft SDKs\Silverlight\v2.0\ReferenceAssemblies\System.Xml.dll - 2.0.0.5
Is this my problem????

Was your framework version recently updated? It could be that the System.XML dlls were replaced by a newer version of them (since the error indicates that it is looking for version 2.0.5.0) and you'd need to update your web.config or System.Xml references to make sure it's using the newer version.

Related

Error on local machine but not on production server

Can someone help me with this error ? this throws on 4 of 5 developer boxes and does not (fortunatelly) on production enviroment, yet no idea why.
System.Web.Services.Protocols.SoapException: Server was unable to
process request. ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. --->
System.OverflowException: Value was either too large or too small for
a Decimal. at System.Number.ParseDecimal(String value, NumberStyles
options, NumberFormatInfo numfmt) at System.Convert.ToDecimal(String
value, IFormatProvider provider) at
System.String.System.IConvertible.ToDecimal(IFormatProvider provider)
at System.Convert.ToDecimal(Object value) at
MySql.Data.MySqlClient.MySqlDataReader.GetDecimal(Int32 i) at
MySql.Data.Entity.EFMySqlDataReader.GetDecimal(Int32 ordinal) ---
End of inner exception stack trace --- at
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetTypedValueDefault(DbDataReader
reader, Int32 ordinal) at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader
reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func2
constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper ) at
System.Data.Entity.Core.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper
shaper) at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.RowNestedResultEnumerator.MaterializeRow()
at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.RowNestedResultEnumerator.MoveNext()
at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.ObjectQueryNestedEnumerator.TryReadToNextElement()
at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.ObjectQueryNestedEnumerator.ReadElement()
at
System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.ObjectQueryNestedEnumerator.MoveNext()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection) at
System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
Glocalapps.BusinessLogic.Logic.ProductLogic.GetProductManagementCatalogData(Int32
idCatalog, Int32 skip, Int32 take, String name, Nullable1 isActive,
Nullable1 isVisible, Nullable1 revised)

FileLoadException for log4net when using CRM SDK

I've been at this for days now and I just do not understand why this error is occurring. It's a FileLoadException for log4net v1.2.10.0, but it occurs during a XRM SDK linq query. I use log4net v1.2.12.0 in the application, and I expected a bindingRedirect to fix this but it doesn't. (The v1.2.10.0 log4net is required by a library that I use)
It looks like the XRM sdk somehow tries to serialize/deserialize assemblies. I'm not sure why it does this, I reckon the post may be relevant.
Inner Exception is null
Exception Message:
Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference.
(Exception from HRESULT: 0x80131040)":"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821
Server stack trace:
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
at System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit)
at Microsoft.Xrm.Sdk.KnownTypesProvider.GetProxyTypesAttribute(Assembly assembly)
at Microsoft.Xrm.Sdk.KnownTypesProvider.RegisterAssembly(Assembly assembly)
at Microsoft.Xrm.Sdk.KnownTypesProvider.get_KnownAssemblies()
at Microsoft.Xrm.Sdk.KnownTypesProvider.get_KnownOrganizationRequestResponseTypes()
at Microsoft.Xrm.Sdk.KnownTypesResolver.ResolveName(String typeName, String typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromDataContractResolver(XmlQualifiedName typeName, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromKnownTypes(String typeName, String typeNs, DataContract memberTypeContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Dictionary`2 knownDataContracts, Type declaredType)
at System.Runtime.Serialization.KnownTypeDataContractResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at Microsoft.Xrm.Sdk.KnownTypesResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.ResolveType(Type objectType, Type declaredType, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] parameters)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups, String& pagingCookie, Boolean& moreRecords)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.Query`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ClassLibrary.Class1.Method1() in C:\Users\Greg.tarr\Documents\Visual Studio 2010\Projects\RestService\ClassLibrary\Class1.cs:line 36
This is possibly caused by an incorrect / outdated reference to log4net in the project (when using an updated version), references are compiled into the assembly and a load is then attempted. Taken from here
Also make sure your PublicKeyToken is correct.
If you've updated through NuGet the token can be incorrect / not update ... as per this SO post

Unsolvable (as of yet) serialization error

We are currently experiencing the following error (from the logs) when using our Windows Azure App:
System.Runtime.Serialization.SerializationException Assembly 'EntityFrameworkDynamicProxies-Marriott.emergePortal.Common,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not found.
This error comes and goes we haven't been able to understand exactly what causes it.
We've tried everything! Any help that anyone could provide would be awesome.
The entire error message from the log is:
System.Web.HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown. ---> System.Runtime.Serialization.SerializatioFnException: Assembly 'EntityFrameworkDynamicProxies-Marriott.emergePortal.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not found.
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, Int32 declaredTypeID, Type declaredType, String name, String ns)
at ReadArrayOfPropertyEnrollmentFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, Int32 declaredTypeID, Type declaredType, String name, String ns)
at ReadArrayOfPropertyEnrollmentFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, Int32 declaredTypeID, Type declaredType, String name, String ns)
at ReadArrayOfanyTypeFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, Int32 declaredTypeID, Type declaredType, String name, String ns)
at ReadSerializableSessionStateStoreDataFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, Int32 declaredTypeID, Type declaredType, String name, String ns)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, String name, String ns)
at System.Runtime.Serialization.NetDataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
at Microsoft.ApplicationServer.Caching.NetDataContractCacheObjectSerializer.Deserialize(Stream stream)
at Microsoft.ApplicationServer.Caching.DataCacheObjectSerializationProvider.DeserializeUserObject(Byte[][] serializedData, ValueFlagsVersion flagsType)
at Microsoft.ApplicationServer.Caching.SocketClientProtocol.GetAndLock(String key, TimeSpan timeout, DataCacheLockHandle& lockHandle, String region, Boolean lockKey, IMonitoringListener listener)
at Microsoft.ApplicationServer.Caching.DataCache.<>c__DisplayClass8a.<GetAndLock>b__89()
at Microsoft.ApplicationServer.Caching.DataCache.GetAndLock(String key, TimeSpan timeout, DataCacheLockHandle& lockHandle)
at Microsoft.Web.DistributedCache.DataCacheForwarderBase.<>c__DisplayClass31`1.<PerformCacheOperation>b__30()
at Microsoft.Web.DistributedCache.DataCacheRetryWrapper.PerformCacheOperation(Action action)
at Microsoft.Web.DistributedCache.DataCacheForwarderBase.GetAndLock(String key, TimeSpan timeout, DataCacheLockHandle& lockHandle)
at Microsoft.Web.DistributedCache.BlobBasedSessionStoreProvider.GetItem(HttpContextBase context, String id, Boolean acquireWriteLock, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions)
at Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions)
at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
at System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state)
at System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)
Without seeing any of the code, it's difficult to troubleshoot. However, we had something similar that was caused because the DataContractSerializer expected a specific type (as defined in the service interface), but was instead getting an EntityFramework proxy type.
We decided to use the Data Transfer Object pattern to resolve this. We created base classes that were simple data transfer objects. EF-aware classes inherit from these and add persistence-related logic.
These DTO objects implement ICloneable (or something similar) which allows us to easily create data transfer copies of the Entity Framework proxy classes before sending objects to the serializer at the service level.
It may also be possible to resolve this by creating a custom serializer that has knowledge of Entity Framework proxy classes but that approach seemed more like a hack. The DTO pattern seemed simpler and was very effective.

Exception occurs when i try to create instance of type through assembly.CreateInstance method

Exception occurs when i try to create instance of type through assembly.CreateInstance method. This is my code in which exception occurs
Assembly assembly = Assembly.LoadFrom(#"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = assembly.CreateInstance(type.FullName);
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: serviceContext
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext)
at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext, Boolean ignorePrivacy)
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Reflection.Assembly.CreateInstance(String typeName)
at HomeWork.Program.Main(String[] args) in c:\users\amasud\documents\visual studio 2010\Projects\HomeWork\HomeWork\Program.cs:line 23
I dont know the reason why you want to create Microsoft.Office.Server.UserProfiles.UserProfileManager object in reflective way. In your case, you have to pass SPServerContext to the constructor. Here is how you can do it.
Assembly assembly = Assembly.LoadFrom(#"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll");
SPServiceContext serviceContext = SPServiceContext.Current;
Type type = assembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfileManager");
object ins = Activator.CreateInstance(type, serviceContext);
From the look of it, whatever type you are creating is expecting a serviceContext parameter in the constructor. You haven't set it, so it crashes.

MMC development in c#

Hi i am developing MMC snap in C#,
in this i want to read XML file so where to put my xml file.
the code is not giving any build error but when i am adding the snapin in MMC its giveing error what to do.
[SnapInSettings("{2078B103-76FF-46E1-95BB-8B2CE3A72E60}",
DisplayName = "Configuration",
Description = "abc Pvt Ltd.")
]
public class Mymmc : SnapIn
{
XDocument xDoc;
public Sararmmc()
{
ScopeNode childscopenode;
xDoc = XDocument.Load("MMCSnapinXML.xml");
IEnumerable<XElement> xelements = xDoc.Root.Descendants();
this.RootNode = new ScopeNode();
this.RootNode.DisplayName = xDoc.Root.Attribute("name").Value;
foreach (XElement elm in xelements)
{
childscopenode = new ScopeNode();
childscopenode.DisplayName = elm.Attribute("name").Value;
this.RootNode.Children.Add(childscopenode);
}
}
}
i am getting
Exception has been thrown by the target of an invocation.
Server stack trace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.SnapInClient.CreateSnapIn(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.ClassLibraryServices.Microsoft.ManagementConsole.Internal.IClassLibraryServices.CreateSnapIn(String assemblyName, String typeName)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at Microsoft.ManagementConsole.Executive.SnapInInitializationOperation.OnStart()
at Microsoft.ManagementConsole.Executive.Operation.Start()
at Microsoft.ManagementConsole.Executive.RunningOperationsTable.EnqueueOperation(Operation operation)
at Microsoft.ManagementConsole.Executive.StandAloneComponentData..ctor(SnapInRegistrationInfo info, Int32 bookkeepingId)
at Microsoft.ManagementConsole.Advanced.FrameworkSnapInFactory.Microsoft.ManagementConsole.Advanced.ISnapInFactory.CreateSnapIn(Int32 bookkeepingId, String snapInKey, Object& snapIn)
There are many exceptions which could be thrown in your constructor (the stack trace indicates that this is the source of the error). It could be a malformed XML exception is thrown on XDocument.Load, it could also be null reference exception if any of the named nodes/attributes you're accessing don't exist. It could be a file not found exception, or even a SecurityException - it could even be something more obscure such as MMC requiring that your assembly is signed.. without knowing what type of exception you're getting it's very difficult for anyone to help you!
As I said in my comment, when you receive errors at runtime that you can't easily explain - this is when having verbose logging in your application becomes really valuable! NLog and log4net are the two most popular logging frameworks for .NET applications

Categories