/// <summary> /// Creates a connection point to of the given interface type /// which will call on a managed code sink that implements that interface. /// </summary> public ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { Exception ex = null; if (source is IConnectionPointContainer) { _connectionPointContainer = (IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; _connectionPointContainer.FindConnectionPoint(ref tmp, out _connectionPoint); } catch { _connectionPoint = null; } if (_connectionPoint == null) { ex = new NotSupportedException(); } else if (sink == null || !eventInterface.IsInstanceOfType(sink)) { ex = new InvalidCastException(); } else { try { _connectionPoint.Advise(sink, out _cookie); } catch { _cookie = 0; _connectionPoint = null; ex = new Exception(); } } } else { ex = new InvalidCastException(); } if (throwException && (_connectionPoint == null || _cookie == 0)) { Dispose(); if (ex == null) { throw new ArgumentException("Exception null, but cookie was zero or the connection point was null"); } else { throw ex; } } #if DEBUG //_callStack = Environment.StackTrace; //this._eventInterface = eventInterface; #endif }
internal static ErrorRecord CreateNotSupportedErrorRecord(string resourceStr, string errorId, object[] args) { string str = StringUtil.Format(resourceStr, args); NotSupportedException notSupportedException = new NotSupportedException(str); ErrorRecord errorRecord = new ErrorRecord(notSupportedException, errorId, ErrorCategory.NotImplemented, null); return errorRecord; }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(NotSupportedException).GetClassName(), "Bridge.NotSupportedException", "Name"); object d = new NotSupportedException(); Assert.True(d is NotSupportedException, "is NotSupportedException"); Assert.True(d is Exception, "is Exception"); }
public bool IsUnsupportedConsoleApplication(string script, out Exception e) { e = null; if (null == UnsupportedConsoleApplications || ! UnsupportedConsoleApplications.Any() ) { return false; } if (UnsupportedConsoleApplications.Contains( script.Trim(), StringComparer.InvariantCultureIgnoreCase )) { e = new NotSupportedException( String.Format( @"The application ""{0}"" cannot be started because it is in the list of unsupported applications for this host. To view or modify the list of unsupported applications for this host, see the ${1} variable, or type ""get-help {2}"". Alternatively, you may try running the application as a unique process using the Start-Process cmdlet.", script, UnsupportedConsoleApplicationsVariableName, UnsupportedConsoleApplicationsHelpTopicName) ); return true; } return false; }
public void TestConcurrentQueueDeclare() { string x = GenerateExchangeName(); Random rnd = new Random(); List <Thread> ts = new List <Thread>(); System.NotSupportedException nse = null; for (int i = 0; i < 256; i++) { Thread t = new Thread(() => { try { // sleep for a random amount of time to increase the chances // of thread interleaving. MK. Thread.Sleep(rnd.Next(5, 500)); Model.ExchangeDeclare(x, "fanout", false, false, null); } catch (System.NotSupportedException e) { nse = e; } }); ts.Add(t); t.Start(); } foreach (Thread t in ts) { t.Join(); } Assert.IsNotNull(nse); Model.ExchangeDelete(x); }
public void ConstructorWithMessageAndInnerExceptionWorks() { var inner = new Exception("a"); var ex = new NotSupportedException("The message", inner); Assert.IsTrue((object)ex is NotSupportedException, "is NotSupportedException"); Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
private static void LogMessage(string text) { var randomType = Random.Next(0, 5); switch (randomType) { case 0: var embeddedException = new NotSupportedException(); var keyNotFoundException = new KeyNotFoundException("Some wrapped message", embeddedException); Log.Error(text, keyNotFoundException); break; case 1: Log.Fatal(text); break; case 2: Log.Info(text); break; case 3: Log.Warn(text); break; default: Log.Debug(text); break; } }
public void ConstructorWithMessageWorks() { var ex = new NotSupportedException("The message"); Assert.True((object)ex is NotSupportedException, "is NotSupportedException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
public void DefaultConstructorWorks() { var ex = new NotSupportedException(); Assert.True((object)ex is NotSupportedException, "is NotSupportedException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "Specified method is not supported."); }
static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *__ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new System.NotSupportedException(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public override IMessage Invoke(IMessage message) { IMessage result = null; IMethodCallMessage methodCall = message as IMethodCallMessage; MethodInfo method = methodCall.MethodBase as MethodInfo; // Invoke if (result == null) { if (proxyTarget != null) { Console.WriteLine("proxy going to invoke: {0}", method.Name); object callResult; object actualresult; bool make_proxy = true; if (method.ReturnType.IsInterface) { actualresult = method.Invoke(proxyTarget, methodCall.InArgs); if (method.ReturnType.IsGenericType) { // Console.WriteLine("** return value is generic type: {0}", method.ReturnType.GetGenericTypeDefinition()); if (method.ReturnType.GetGenericTypeDefinition() == (typeof(IEnumerator<>))) { Console.WriteLine("** method returning IEnumerator<>, making BatchProxy"); Type[] args = method.ReturnType.GetGenericArguments(); Type srvbatchtype = typeof(EnumeratorServerBatch<>).MakeGenericType(args); object srv = Activator.CreateInstance(srvbatchtype, actualresult); Type clbatchtype = typeof(EnumeratorClientBatch<>).MakeGenericType(args); object client = Activator.CreateInstance(clbatchtype, srv); make_proxy = false; actualresult = client; } } if (make_proxy) { var newproxy = new MyProxy(method.ReturnType, actualresult); callResult = newproxy.GetTransparentProxy(); } else { callResult = actualresult; } } else { callResult = method.Invoke(proxyTarget, methodCall.InArgs); } Console.WriteLine("proxy done Invoking: {0}", method.Name); LogicalCallContext context = methodCall.LogicalCallContext; result = new ReturnMessage(callResult, null, 0, context, message as IMethodCallMessage); } else { NotSupportedException exception = new NotSupportedException("proxyTarget is not defined"); result = new ReturnMessage(exception, message as IMethodCallMessage); } } return result; }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(NotSupportedException).FullName, "ss.NotSupportedException", "Name"); Assert.IsTrue(typeof(NotSupportedException).IsClass, "IsClass"); Assert.AreEqual(typeof(NotSupportedException).BaseType, typeof(Exception), "BaseType"); object d = new NotSupportedException(); Assert.IsTrue(d is NotSupportedException, "is NotSupportedException"); Assert.IsTrue(d is Exception, "is Exception"); var interfaces = typeof(NotSupportedException).GetInterfaces(); Assert.AreEqual(interfaces.Length, 0, "Interfaces length"); }
static void FatalExceptionObject(object exceptionObject) { var huh = exceptionObject as Exception; if (huh == null) { huh = new NotSupportedException( "Unhandled exception doesn't derive from System.Exception: " + exceptionObject.ToString() ); } FatalExceptionHandler.Handle(huh); }
protected void Act() { try { _sftpFileStream.SetLength(_length); Assert.Fail(); } catch (NotSupportedException ex) { _actualException = ex; } }
public void exception_type() { var exception1 = new NotImplementedException(); var exception2 = new NotSupportedException(); theExpression.IsType<NotImplementedException>(); theMatch.Description.ShouldEqual("Exception type is " + typeof (NotImplementedException).FullName); theMatch.Matches(null, exception1).ShouldBeTrue(); theMatch.Matches(null, exception2).ShouldBeFalse(); }
private string ConvertirString( string valorActual, List<IValorRespuestaWS> equivalencias ) { IValorRespuestaWS valor = equivalencias. Find( x => x.Equivalencia.Equals( valorActual, StringComparison.OrdinalIgnoreCase ) ); if ( valor == null ) { NotSupportedException ex = new NotSupportedException( "No se encuentra el valor '" + valorActual + "'" ); throw ex; } return valor.ObtenerId(); }
public virtual Exception Convert(ExceptionModel model) { Exception exception = null; TypeSwitch.On(model) .Case<ArgumentNullExceptionModel>(m => exception = new ArgumentNullException(m.ParamName, m.Message)) .Case<ArgumentExceptionModel>(m => exception = new ArgumentException(m.ParamName, m.Message)) .Case<InvalidOperationExceptionModel>(m => exception = new InvalidOperationException(m.Message)) .Case<NotSupportedExceptionModel>(m => exception = new NotSupportedException(m.Message)) .Case<HttpStatusExceptionModel>(m => exception = Convert(m.InnerException)) .Default(m => exception = new Exception(m.Message)); return exception; }
static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @message = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = new System.NotSupportedException(@message); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); }
private static RuleCodeDomStatement GetStatement(CodeStatement statement) { Type type = statement.GetType(); if (type == typeof(CodeExpressionStatement)) { return ExpressionStatement.Create(statement); } if (type == typeof(CodeAssignStatement)) { return AssignmentStatement.Create(statement); } NotSupportedException exception = new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Messages.CodeStatementNotHandled, new object[] { statement.GetType().FullName })); exception.Data["ErrorObject"] = statement; throw exception; }
public async Task Should_Throw_Exception_To_Requester_If_Responder_Throws_Sync() { /* Setup */ var responseException = new NotSupportedException("I'll throw this"); var requester = BusClientFactory.CreateDefault(TimeSpan.FromHours(1)); var responder = BusClientFactory.CreateDefault(TimeSpan.FromHours(1)); responder.RespondAsync<BasicRequest, BasicResponse>((request, context) => { throw responseException; }); /* Test */ /* Assert */ var e = await Assert.ThrowsAsync<MessageHandlerException>(() => requester.RequestAsync<BasicRequest, BasicResponse>()); Assert.Equal(expected: responseException.Message, actual: e.InnerException.Message); }
public override IMediaFile NewMediaFile(IFile file, MediaFileNodeType mediaFileNodeType) { var lastException = new NotSupportedException(); foreach (MediaFileFactory factory in this.ComponentFactories) { try { return factory.NewMediaFile(file, mediaFileNodeType); } catch (NotSupportedException e) { lastException = e; } } throw lastException; }
public void CheckValid(MethodInfo method, Attribute[] attributes, bool methodIsAsync) { if (!CheckedMethodCaches.ContainsKey(method)) { var @params = method.GetParameters(); var delegateParam = @params.FirstOrDefault(p => typeof (Delegate).IsAssignableFrom(p.ParameterType)); if (delegateParam != null) { CheckedMethodCaches[method] = new NotSupportedException(string.Format("Dude, method {0} has param {1} is a delegate of type {2}. RPC call does not support delegate", method.Name, delegateParam.Name, delegateParam.ParameterType.FullName)); } else if (method.DeclaringType != null && method.DeclaringType.GetProperties().Any(prop => prop.GetSetMethod() == method || prop.GetGetMethod() == method)) { CheckedMethodCaches[method] = new NotSupportedException(string.Format("Dude, property accessor {0} is not supported for RPC call", method.Name)); } else if (!methodIsAsync) { CheckedMethodCaches[method] = null; } else if (method.ReturnType != typeof (void)) { CheckedMethodCaches[method] = new Exception(string.Format("Dude, method {0} requires to return a value but it's expected to run asynchronously", method.Name)); } else foreach (var param in @params) { if (param.IsOut) { CheckedMethodCaches[method] = new Exception(string.Format("Dude, param '{0}' of method {1} is 'out' param, but the method is expected to run asynchronously", param.Name, method.Name)); break; } } } if (CheckedMethodCaches.ContainsKey(method) && CheckedMethodCaches[method] != null) { throw CheckedMethodCaches[method]; } }
public int CompareTo(object current, object other) { int result = 0; bool isNumber = DetermineIfObjectIsAnyTypeOfNumber(current); if (other is string) { int whichIsLonger = DetermineWhichStringLonger((string)current, (string)other); int maxI = DetermineMaxStringIndexToCheck((string)current, (string)other); result = DetermineWhichStringFirst((string)current, (string)other, maxI, whichIsLonger); } else if (isNumber == true) { decimal numberA = ConvertToDecimal(current); decimal numberB = ConvertToDecimal(other); result = DetermineWhichNumberFirst(numberA, numberB); } else { System.NotSupportedException cannotSort = new System.NotSupportedException(); throw cannotSort; } return(result); }
internal static void ThrowSystemException( string message, Type exceptionType, string source, string argument = "" ) { Exception exception; if( exceptionType == typeof( ArgumentException ) ) { exception = new ArgumentException( message, argument ); } else if( exceptionType == typeof( ArgumentNullException ) ) { exception = new ArgumentNullException( message ); } else if( exceptionType == typeof( ArgumentOutOfRangeException ) ) { exception = new ArgumentOutOfRangeException( argument, message ); } else if( exceptionType == typeof( IndexOutOfRangeException ) ) { exception = new IndexOutOfRangeException( message ); } else if( exceptionType == typeof( InvalidOperationException ) ) { exception = new InvalidOperationException( message ); } else if( exceptionType == typeof( NotSupportedException ) ) { exception = new NotSupportedException( message ); } else { exception = new Exception( message ); } exception.Source = source; throw exception; }
private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference) { TypeDesc typeDesc = null; TypeKind kind; Type arrayElementType = null; Type baseType = null; TypeFlags flags = 0; Exception exception = null; if (!type.GetTypeInfo().IsVisible) { flags |= TypeFlags.Unsupported; exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName)); } else if (directReference && (type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed)) { flags |= TypeFlags.Unsupported; exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName)); } if (!type.GetTypeInfo().IsValueType) flags |= TypeFlags.Reference; if (type == typeof(object)) { kind = TypeKind.Root; flags |= TypeFlags.HasDefaultConstructor; } else if (type == typeof(ValueType)) { kind = TypeKind.Enum; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } else if (type == typeof(void)) { kind = TypeKind.Void; } else if (typeof(IXmlSerializable).IsAssignableFrom(type)) { kind = TypeKind.Serializable; flags |= TypeFlags.Special | TypeFlags.CanBeElementValue; flags |= GetConstructorFlags(type, ref exception); } else if (type.IsArray) { kind = TypeKind.Array; if (type.GetArrayRank() > 1) { flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName)); } } arrayElementType = type.GetElementType(); flags |= TypeFlags.HasDefaultConstructor; } else if (typeof(ICollection).IsAssignableFrom(type)) { kind = TypeKind.Collection; arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name); flags |= GetConstructorFlags(type, ref exception); } else if (type == typeof(XmlQualifiedName)) { kind = TypeKind.Primitive; } else if (type.GetTypeInfo().IsPrimitive) { kind = TypeKind.Primitive; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } else if (type.GetTypeInfo().IsEnum) { kind = TypeKind.Enum; } else if (type.GetTypeInfo().IsValueType) { kind = TypeKind.Struct; if (IsOptionalValue(type)) { baseType = type.GetGenericArguments()[0]; flags |= TypeFlags.OptionalValue; } else { baseType = type.GetTypeInfo().BaseType; } if (type.GetTypeInfo().IsAbstract) flags |= TypeFlags.Abstract; } else if (type.GetTypeInfo().IsClass) { if (type == typeof(XmlAttribute)) { kind = TypeKind.Attribute; flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue; } else if (typeof(XmlNode).IsAssignableFrom(type)) { kind = TypeKind.Node; baseType = type.GetTypeInfo().BaseType; flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue; if (typeof(XmlText).IsAssignableFrom(type)) flags &= ~TypeFlags.CanBeElementValue; else if (typeof(XmlElement).IsAssignableFrom(type)) flags &= ~TypeFlags.CanBeTextValue; else if (type.IsAssignableFrom(typeof(XmlAttribute))) flags |= TypeFlags.CanBeAttributeValue; } else { kind = TypeKind.Class; baseType = type.GetTypeInfo().BaseType; if (type.GetTypeInfo().IsAbstract) flags |= TypeFlags.Abstract; } } else if (type.GetTypeInfo().IsInterface) { kind = TypeKind.Void; flags |= TypeFlags.Unsupported; if (exception == null) { if (memberInfo == null) { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName)); } else { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName)); } } } else { kind = TypeKind.Void; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } // check to see if the type has public default constructor for classes if (kind == TypeKind.Class && !type.GetTypeInfo().IsAbstract) { flags |= GetConstructorFlags(type, ref exception); } // check if a struct-like type is enumerable if (kind == TypeKind.Struct || kind == TypeKind.Class) { if (typeof(IEnumerable).IsAssignableFrom(type)) { arrayElementType = GetEnumeratorElementType(type, ref flags); kind = TypeKind.Enumerable; // GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property, // we need to check the MoveNext() and ctor methods for the security attribues flags |= GetConstructorFlags(type, ref exception); } } typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null); typeDesc.Exception = exception; if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable)) typeDesc.CheckNeedConstructor(); if (typeDesc.IsUnsupported) { // return right away, do not check anything else return typeDesc; } _typeDescs.Add(type, typeDesc); if (arrayElementType != null) { TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false); // explicitly disallow read-only elements, even if they are collections if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive) { td.CheckNeedConstructor(); } typeDesc.ArrayElementTypeDesc = td; } if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType)) { typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false); } return typeDesc; }
public void StripNestedAggregateExceptions() { _client.AddWrapperExceptions(typeof(AggregateException)); OutOfMemoryException exception2 = new OutOfMemoryException("Ran out of Int64s"); NotSupportedException exception3 = new NotSupportedException("Forgot to implement this method"); AggregateException innerWrapper = new AggregateException(_exception, exception2); AggregateException wrapper = new AggregateException(innerWrapper, exception3); List<Exception> exceptions = _client.ExposeStripWrapperExceptions(wrapper).ToList(); Assert.AreEqual(3, exceptions.Count); Assert.Contains(_exception, exceptions); Assert.Contains(exception2, exceptions); Assert.Contains(exception3, exceptions); }
public virtual Response MethodNotAllowed(System.NotSupportedException e) { return(Response(Response.status(405), new ExceptionRepresentation(e))); }
private void ResponseCallback(IAsyncResult ar) { HttpWebResponse webResponse = null; lock (_syncObject) { try { if (_disposed) { return; } // The caller thread can dispose this class and the worker thread need to check the disposed // condition; need to lock // If disposed, there is nothing to handle webResponse = (HttpWebResponse)WpfWebRequestHelper.EndGetResponse(_webRequest, ar); // If it is not partial content, no need to look further if (webResponse.StatusCode == HttpStatusCode.PartialContent) { // // Check for few conditions // // Get the header and make sure that it was indeed the byte range response int beginOffset = _byteRangesInProgress[0, Offset_Index]; int endOffset = beginOffset+ _byteRangesInProgress[0,Length_Index] - 1; // HttpWebRequest in the current CLR does not allow multiple byte range requests. // At this point, none of the callers of this class will make more than one range at a time // So, we should not receive any response with more than one range returned // When multiple byte ranges requests are support in HttpWebRequest eventually, // there is a question on how to handle multipart response (Content-Type=multipart/byteranges) // At this point we only need to handle one byte range response (Content-Range header) only // Request was successful // Note: endOffset could be trimmed offset in the case where the response didn't // satisfy the entire request if (CheckContentRange(webResponse.Headers, beginOffset, ref endOffset)) { // Write out the bytes to the temp file if (WriteByteRange(webResponse, beginOffset, endOffset - beginOffset + 1)) { // The range is downloaded successfully; add it to the list _byteRangesAvailable.Add(beginOffset); _byteRangesAvailable.Add(endOffset - beginOffset + 1); } else _erroredOut = true; } else { _erroredOut = true; _erroredOutException = new NotSupportedException(SR.Get(SRID.ByteRangeRequestIsNotSupported)); } } else { _erroredOut = true; } } catch (Exception e) // catch (and re-throw) exceptions so we can inform the other thread { _erroredOut = true; _erroredOutException = e; throw e; } catch // catch (and re-throw) all kinds of exceptions so we can inform the other thread { // inform other thread of error condition _erroredOut= true; _erroredOutException = null; throw; } finally { if (webResponse != null) { webResponse.Close(); } // bytes requested are downloaded or errored out // inform the caller that these ranges are available RaiseEvent(!_erroredOut); } // If we haven't errored out already, process the next batch if (!_erroredOut) { ProcessWaitQueue(); } } }
private void _NotImpl(string message) { NotSupportedException ex = new NotSupportedException(message, new ExternalException(String.Empty, VSConstants.E_NOTIMPL)); throw ex; }
private void _NotImpl(string message) { NotSupportedException ex = new NotSupportedException(); throw ex; }
private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) { object obj2 = null; string mimeType = dataNodeInfo.MimeType; string typeName = ((dataNodeInfo.TypeName == null) || (dataNodeInfo.TypeName.Length == 0)) ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) : dataNodeInfo.TypeName; if ((mimeType != null) && (mimeType.Length > 0)) { if ((string.Equals(mimeType, ResXResourceWriter.BinSerializedObjectMimeType) || string.Equals(mimeType, ResXResourceWriter.Beta2CompatSerializedObjectMimeType)) || string.Equals(mimeType, ResXResourceWriter.CompatBinSerializedObjectMimeType)) { byte[] buffer = FromBase64WrappedString(dataNodeInfo.ValueData); if (this.binaryFormatter == null) { this.binaryFormatter = new BinaryFormatter(); this.binaryFormatter.Binder = new ResXSerializationBinder(typeResolver); } IFormatter binaryFormatter = this.binaryFormatter; if ((buffer != null) && (buffer.Length > 0)) { obj2 = binaryFormatter.Deserialize(new MemoryStream(buffer)); if (obj2 is ResXNullRef) { obj2 = null; } } return obj2; } if (string.Equals(mimeType, ResXResourceWriter.SoapSerializedObjectMimeType) || string.Equals(mimeType, ResXResourceWriter.CompatSoapSerializedObjectMimeType)) { byte[] buffer2 = FromBase64WrappedString(dataNodeInfo.ValueData); if ((buffer2 != null) && (buffer2.Length > 0)) { obj2 = this.CreateSoapFormatter().Deserialize(new MemoryStream(buffer2)); if (obj2 is ResXNullRef) { obj2 = null; } } return obj2; } if ((!string.Equals(mimeType, ResXResourceWriter.ByteArraySerializedObjectMimeType) || (typeName == null)) || (typeName.Length <= 0)) { return obj2; } System.Type type = this.ResolveType(typeName, typeResolver); if (type != null) { TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(byte[]))) { byte[] buffer3 = FromBase64WrappedString(dataNodeInfo.ValueData); if (buffer3 != null) { obj2 = converter.ConvertFrom(buffer3); } } return obj2; } string str6 = System.Windows.Forms.SR.GetString("TypeLoadException", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X }); XmlException exception = new XmlException(str6, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException exception2 = new TypeLoadException(str6, exception); throw exception2; } if ((typeName == null) || (typeName.Length <= 0)) { return obj2; } System.Type type2 = this.ResolveType(typeName, typeResolver); if (type2 != null) { if (type2 == typeof(ResXNullRef)) { return null; } if ((typeName.IndexOf("System.Byte[]") != -1) && (typeName.IndexOf("mscorlib") != -1)) { return FromBase64WrappedString(dataNodeInfo.ValueData); } TypeConverter converter2 = TypeDescriptor.GetConverter(type2); if (!converter2.CanConvertFrom(typeof(string))) { return obj2; } string valueData = dataNodeInfo.ValueData; try { return converter2.ConvertFromInvariantString(valueData); } catch (NotSupportedException exception3) { string str8 = System.Windows.Forms.SR.GetString("NotSupported", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X, exception3.Message }); XmlException innerException = new XmlException(str8, exception3, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); NotSupportedException exception5 = new NotSupportedException(str8, innerException); throw exception5; } } string message = System.Windows.Forms.SR.GetString("TypeLoadException", new object[] { typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X }); XmlException inner = new XmlException(message, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException exception7 = new TypeLoadException(message, inner); throw exception7; }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return null; } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked((int)0x800A01C1): case unchecked((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) shouldDisplayHR = true; break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) shouldDisplayHR = true; break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) shouldDisplayHR = true; break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) shouldDisplayHR = true; break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked((int)0x800A793C): case unchecked((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) shouldDisplayHR = true; break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) shouldDisplayHR = true; break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) shouldDisplayHR = true; break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked((int)0x800A01B6): case unchecked((int)0x800A01BD): case unchecked((int)0x800A01CA): case unchecked((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) shouldDisplayHR = true; break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) shouldDisplayHR = true; break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) shouldDisplayHR = true; break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) shouldDisplayHR = true; } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) shouldDisplayHR = true; } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) shouldConstructMessage = true; } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) message = hrMessage; else message = message + " (" + hrMessage + ")"; } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return exception; }
private static void SynchronizeProperties(DataContext context, PageType pageType, Type type, IList<PropertyEntity> propertyEntities) { var propertyAttributeType = typeof(PropertyAttribute); var requiredAttributeType = typeof(RequiredAttribute); var properties = propertyEntities; var sortOrder = 0; foreach (var propertyInfo in type.GetProperties()) { var attributes = propertyInfo.GetCustomAttributes(true); var propertyAttribute = (PropertyAttribute)attributes.SingleOrDefault(propertyAttributeType.IsInstanceOfType); if (propertyAttribute != null) { var propertyName = propertyInfo.Name; var declaringType = propertyInfo.PropertyType; var propertyTypeId = PropertyType.GetPropertyTypeId(declaringType); if (!propertyAttribute.IsTypeValid(declaringType)) { var notSupportedException = new NotSupportedException(string.Format("The property attribute of '{0}' on pagetype '{1}' ({2}) does not support the propertytype!", propertyName, pageType.Name, type.FullName)); Logger.Write(notSupportedException, Logger.Severity.Critical); throw notSupportedException; } var required = attributes.Count(requiredAttributeType.IsInstanceOfType) > 0; sortOrder++; var property = properties.SingleOrDefault(p => p.Name == propertyName); if (property == null) { property = new PropertyEntity {Name = propertyName}; properties.Add(property); } property.PropertyTypeId = propertyTypeId; property.PageTypeId = pageType.PageTypeId; property.SortOrder = sortOrder; property.Header = propertyAttribute.Header; property.Required = required; // If generic and standard attribute, store generic type as parameter. Required for list types like CollectionProperty. if (declaringType.IsGenericType && propertyAttribute.GetType() == typeof(PropertyAttribute)) { var subType = declaringType.GetGenericArguments()[0]; property.Parameters = subType.FullName + ", " + subType.Assembly.GetName().Name; } else { property.Parameters = propertyAttribute.Parameters; } if (property.PropertyId == 0) { context.Add(property); } var propertyDefinition = Mapper.Map<PropertyEntity, PropertyDefinition>(property); propertyDefinition.TabGroup = propertyAttribute.TabGroup; pageType.Properties.Add(propertyDefinition); } } context.SaveChanges(); }
public static void SynchronizeSiteProperties() { var typesWithAttribute = AttributeReader.GetTypesWithAttribute(typeof(SiteSettingsAttribute)).ToList(); if (typesWithAttribute.Count > 1) { throw new Exception("More than one class implementing Site was found!"); } if (!typesWithAttribute.Any()) { CmsSite.PropertyDefinitions = new List<PropertyDefinition>(); return; } var type = typesWithAttribute.First(); var siteSettingsAttribute = AttributeReader.GetAttribute<SiteSettingsAttribute>(type); CmsSite.AllowedTypes = siteSettingsAttribute.AllowedTypes; CmsSite.DefaultChildSortDirection = siteSettingsAttribute.DefaultChildSortDirection; CmsSite.DefaultChildSortOrder = siteSettingsAttribute.DefaultChildSortOrder; var definition = new List<PropertyDefinition>(); var propertyAttributeType = typeof(PropertyAttribute); var requiredAttributeType = typeof(RequiredAttribute); var sortOrder = 0; using (var context = new DataContext()) { var properties = context.SitePropertyDefinitions.ToList(); foreach (var propertyInfo in type.GetProperties()) { var attributes = propertyInfo.GetCustomAttributes(true); var propertyAttribute = (PropertyAttribute)attributes.SingleOrDefault(propertyAttributeType.IsInstanceOfType); if (propertyAttribute != null) { var propertyName = propertyInfo.Name; var declaringType = propertyInfo.PropertyType; var propertyTypeId = PropertyType.GetPropertyTypeId(declaringType); if (!propertyAttribute.IsTypeValid(declaringType)) { var notSupportedException = new NotSupportedException(string.Format("The property attribute of '{0}' on site settings ({1}) does not support the propertytype!", propertyName, type.FullName)); Logger.Write(notSupportedException, Logger.Severity.Critical); throw notSupportedException; } var required = attributes.Count(requiredAttributeType.IsInstanceOfType) > 0; sortOrder++; var property = properties.SingleOrDefault(p => p.Name == propertyName); if (property == null) { property = new SitePropertyDefinitionEntity {Name = propertyName}; properties.Add(property); } property.PropertyTypeId = propertyTypeId; property.SortOrder = sortOrder; property.Header = propertyAttribute.Header; property.Required = required; // If generic and standard attribute, store generic type as parameter. Required for list types like CollectionProperty. if (declaringType.IsGenericType && propertyAttribute.GetType() == typeof(PropertyAttribute)) { var subType = declaringType.GetGenericArguments()[0]; property.Parameters = subType.FullName + ", " + subType.Assembly.GetName().Name; } else { property.Parameters = propertyAttribute.Parameters; } if (property.PropertyId == 0) { context.Add(property); } var propertyDefinition = Mapper.Map<SitePropertyDefinitionEntity, PropertyDefinition>(property); propertyDefinition.TabGroup = propertyAttribute.TabGroup; definition.Add(propertyDefinition); } } context.SaveChanges(); } CmsSite.PropertyDefinitions = definition; }
public string getFilePath(string filepath) { // check file path is valid before proceeding string timestamp = DateTime.Now.ToString("yyyy-MM-dd H-mm-ss"); filepath = filepath + @"\Chat_" + timestamp + ".doc"; try { FileInfo fi = new FileInfo(filepath); return filepath; } catch (NotSupportedException e) { e = new NotSupportedException(e.Message + "\nThe filename entered contains unsupported characters.\nPlease remove characters such as ':' and try again."); throw e; } }