internal void StartEvents()
        {
            if (this._connectionPoint != null)
            {
                return;
            }
            object activeXInstance = this.Host.ActiveXInstance;

            if (activeXInstance != null)
            {
                try
                {
                    this._connectionPoint = new ConnectionPointCookie(activeXInstance, this, typeof(UnsafeNativeMethods.IPropertyNotifySink));
                }
                catch (Exception ex)
                {
                    if (CriticalExceptions.IsCriticalException(ex))
                    {
                        throw;
                    }
                }
            }
        }
Esempio n. 2
0
        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------

        #region Private Methods


        private Uri GetEntryAssemblyLocation()
        {
            Uri entryLocation = null;

            try
            {
                entryLocation = new Uri(Application.ResourceAssembly.CodeBase);
            }
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalException(ex))
                {
                    throw;
                }
                // `Swallow any other exceptions to avoid disclosing the critical path.
                //
                // Possible Exceptions: ArgumentException, ArgumentNullException, PathTooLongException
                // DirectoryNotFoundException, IOException, UnauthorizedAccessException,
                // ArgumentOutOfRangeException, FileNotFoundException, NotSupportedException
            }

            return(entryLocation);
        }
Esempio n. 3
0
 protected override XamlType GetXamlType(string xamlNamespace, string name, params XamlType[] typeArguments)
 {
     try
     {
         return(LookupXamlType(xamlNamespace, name, typeArguments));
     }
     catch (Exception e)
     {
         if (CriticalExceptions.IsCriticalException(e))
         {
             throw;
         }
         if (_typeMapper.LoadReferenceAssemblies())
         {
             // If new reference assemblies were loaded, retry the type load
             return(LookupXamlType(xamlNamespace, name, typeArguments));
         }
         else
         {
             throw;
         }
     }
 }
Esempio n. 4
0
        // Token: 0x060007C0 RID: 1984 RVA: 0x0001884C File Offset: 0x00016A4C
        private object GetTypedParamValue(string param, Type type, bool throwOnError)
        {
            object obj = null;

            if (type == typeof(string))
            {
                return(param);
            }
            TypeConverter converter = TypeDescriptor.GetConverter(type);

            if (converter != null && converter.CanConvertFrom(typeof(string)))
            {
                try
                {
                    obj = converter.ConvertFromString(null, CultureInfo.InvariantCulture, param);
                }
                catch (Exception ex)
                {
                    if (CriticalExceptions.IsCriticalApplicationException(ex) || throwOnError)
                    {
                        throw;
                    }
                }
                catch
                {
                    if (throwOnError)
                    {
                        throw;
                    }
                }
            }
            if (obj == null && type.IsAssignableFrom(typeof(string)))
            {
                obj = param;
            }
            return(obj);
        }
 internal void Disconnect()
 {
     if (this.connectionPoint != null && this.cookie != 0)
     {
         try
         {
             this.connectionPoint.Unadvise(this.cookie);
         }
         catch (Exception ex)
         {
             if (CriticalExceptions.IsCriticalException(ex))
             {
                 throw;
             }
         }
         finally
         {
             this.cookie = 0;
         }
         try
         {
             Marshal.FinalReleaseComObject(this.connectionPoint);
         }
         catch (Exception ex2)
         {
             if (CriticalExceptions.IsCriticalException(ex2))
             {
                 throw;
             }
         }
         finally
         {
             this.connectionPoint = null;
         }
     }
 }
Esempio n. 6
0
        public override object GetValue(Object obj, XamlMember property, bool failIfWriteOnly)
        {
            object value;

            try
            {
                if (property.IsDirective)
                {
                    value = this.CreateInstance(property.Type, null);
                }
                else if (!failIfWriteOnly)
                {
                    try
                    {
                        value = GetValue(property, obj);
                    }
                    catch (NotSupportedException)
                    {
                        value = null;
                    }
                }
                else
                {
                    value = GetValue(property, obj);
                }
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e))
                {
                    throw;
                }
                throw CreateException(SR.Get(SRID.GetValue, property), UnwrapTargetInvocationException(e));
            }
            return(value);
        }
        private Uri GetEntryAssemblyLocation()
        {
            Uri           result        = null;
            PermissionSet permissionSet = new PermissionSet(null);

            permissionSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            permissionSet.Assert();
            try
            {
                result = new Uri(Application.ResourceAssembly.CodeBase);
            }
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalException(ex))
                {
                    throw;
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            return(result);
        }
Esempio n. 8
0
 public override KeyValuePair <AttachableMemberIdentifier, object>[] GetAttachedProperties(object instance)
 {
     KeyValuePair <AttachableMemberIdentifier, object>[] pairArray2;
     try
     {
         KeyValuePair <AttachableMemberIdentifier, object>[] array = null;
         int attachedPropertyCount = AttachablePropertyServices.GetAttachedPropertyCount(instance);
         if (attachedPropertyCount > 0)
         {
             array = new KeyValuePair <AttachableMemberIdentifier, object> [attachedPropertyCount];
             AttachablePropertyServices.CopyPropertiesTo(instance, array, 0);
         }
         pairArray2 = array;
     }
     catch (Exception exception)
     {
         if (CriticalExceptions.IsCriticalException(exception))
         {
             throw;
         }
         throw this.CreateException(System.Xaml.SR.Get("APSException", new object[] { instance }));
     }
     return(pairArray2);
 }
Esempio n. 9
0
        // Token: 0x06001CE3 RID: 7395 RVA: 0x00086FA8 File Offset: 0x000851A8
        private void CreateDocFromExternalSource(WebRequest request)
        {
            bool        flag        = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer);
            XmlDocument xmlDocument = new XmlDocument();
            Exception   ex          = null;

            try
            {
                if (flag)
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadSource(new object[]
                    {
                        TraceData.Identify(this),
                        base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                        TraceData.Identify(request.RequestUri.ToString())
                    }));
                }
                WebResponse response = WpfWebRequestHelper.GetResponse(request);
                if (response == null)
                {
                    throw new InvalidOperationException(SR.Get("GetResponseFailed"));
                }
                Stream responseStream = response.GetResponseStream();
                if (flag)
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadDoc(new object[]
                    {
                        TraceData.Identify(this)
                    }));
                }
                xmlDocument.Load(responseStream);
                responseStream.Close();
            }
            catch (Exception ex2)
            {
                if (CriticalExceptions.IsCriticalException(ex2))
                {
                    throw;
                }
                ex = ex2;
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, this.Source, ex);
                }
            }
            catch
            {
                throw;
            }
            if (ex != null)
            {
                if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach))
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished(new object[]
                    {
                        TraceData.Identify(this),
                        base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                        TraceData.Identify(null),
                        TraceData.IdentifyException(ex)
                    }));
                }
                this.OnQueryFinished(null, ex, this.CompletedCallback, null);
                return;
            }
            this.BuildNodeCollection(xmlDocument);
        }
        InvokeSaveAsXamlBatchWorkItem(
            Object arg
            )
        {
            //
            // PreSharp uses message numbers that the C# compiler doesn't know about.
            // Disable the C# complaints, per the PreSharp documentation.
            #pragma warning disable 1634, 1691
            //
            // PreSharp complains about catching NullReference (and other) exceptions.
            // This is an async model and we need to catch all exception ourselves and then
            // send them to the completion delegate
            #pragma warning disable 56500
            try
            {
                // This logic must be mirrored in IsAsyncWorkPending see remarks.

                if (!_serializationOperationCanceled)
                {
                    if (!_isBatchWorkItemInProgress && _batchOperationQueue.Count > 0)
                    {
                        BatchOperationWorkItem batchOperationWorkItem = (BatchOperationWorkItem)_batchOperationQueue.Dequeue();

                        if (batchOperationWorkItem.OperationType == BatchOperationType.batchWrite)
                        {
                            _currentPageXmlWriter = Simulator.SimulateBeginFixedPage();

                            ReachSerializer reachSerializer = GetSerializer(batchOperationWorkItem.SerializedObject);

                            if (reachSerializer != null)
                            {
                                //
                                // Prepare the context that is going to be pushed on the stack
                                //
                                SerializationManagerOperationContextStack
                                    contextStack = new SerializationManagerOperationContextStack(reachSerializer,
                                                                                                 batchOperationWorkItem.SerializedObject);
                                //
                                // At this stage, start calling another method which would peak at the stack
                                //
                                _operationStack.Push(contextStack);

                                PostSerializationTask(new DispatcherOperationCallback(InvokeSaveAsXamlBatchWorkItem));
                            }
                            else
                            {
                                throw new XpsSerializationException(SR.Get(SRID.ReachSerialization_NoSerializer));
                            }
                            _isBatchWorkItemInProgress = true;
                        }
                        else if (batchOperationWorkItem.OperationType == BatchOperationType.batchCommit)
                        {
                            Simulator.EndConfirmToXPSStructure(IsBatchMode);
                            XPSSerializationCompletionMethod();
                        }
                    }
                    else
                    {
                        if (_operationStack.Count > 0)
                        {
                            Object objectOnStack = _operationStack.Pop();

                            if (objectOnStack.GetType() ==
                                typeof(System.Windows.Xps.Serialization.SerializationManagerOperationContextStack))
                            {
                                SerializationManagerOperationContextStack context =
                                    (SerializationManagerOperationContextStack)objectOnStack;

                                context.ReachSerializer.SerializeObject(context.SerializedObject);
                            }
                            else if (typeof(System.Windows.Xps.Serialization.ReachSerializerContext).IsAssignableFrom(objectOnStack.GetType()))
                            {
                                ReachSerializerContext context = (ReachSerializerContext)objectOnStack;
                                context.Serializer.AsyncOperation(context);
                            }
                            PostSerializationTask(new DispatcherOperationCallback(InvokeSaveAsXamlBatchWorkItem));
                        }
                        else
                        {
                            Simulator.SimulateEndFixedPage(_currentPageXmlWriter);
                            _isBatchWorkItemInProgress = false;
                            _currentPageXmlWriter      = null;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e))
                {
                    throw;
                }

                //
                // Indicate that an error happened
                //
                bool canceled = false;

                XpsSerializationCompletedEventArgs args = new XpsSerializationCompletedEventArgs(canceled,
                                                                                                 null,
                                                                                                 e);

                _serializationOperationCanceled = true;

                PostSerializationTask(new DispatcherOperationCallback(OnXPSSerializationCompleted), args);

                return(null);
            }
            #pragma warning restore 56500
            #pragma warning restore 1634, 1691


            return(null);
        }
        InvokeSaveAsXamlWorkItem(
            Object arg
            )
        {
            //
            // PreSharp uses message numbers that the C# compiler doesn't know about.
            // Disable the C# complaints, per the PreSharp documentation.
            #pragma warning disable 1634, 1691
            //
            // PreSharp complains about catching NullReference (and other) exceptions.
            // This is an async model and we need to catch all exception ourselves and then
            // send them to the completion delegate
            #pragma warning disable 56500
            try
            {
                if (!_serializationOperationCanceled)
                {
                    if (_operationStack.Count > 0)
                    {
                        Object objectOnStack = _operationStack.Pop();

                        if (objectOnStack.GetType() ==
                            typeof(System.Windows.Xps.Serialization.SerializationManagerOperationContextStack))
                        {
                            SerializationManagerOperationContextStack context =
                                (SerializationManagerOperationContextStack)objectOnStack;

                            context.ReachSerializer.SerializeObject(context.SerializedObject);
                        }
                        else if (typeof(System.Windows.Xps.Serialization.ReachSerializerContext).IsAssignableFrom(objectOnStack.GetType()))
                        {
                            ReachSerializerContext context = (ReachSerializerContext)objectOnStack;
                            context.Serializer.AsyncOperation(context);
                        }
                        PostSerializationTask(new DispatcherOperationCallback(InvokeSaveAsXamlWorkItem));
                    }
                    else
                    {
                        Simulator.EndConfirmToXPSStructure(IsBatchMode);
                        XPSSerializationCompletionMethod();
                    }
                }
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e))
                {
                    throw;
                }

                //
                // Indicate that an error happened
                //
                bool canceled = false;

                XpsSerializationCompletedEventArgs args = new XpsSerializationCompletedEventArgs(canceled,
                                                                                                 null,
                                                                                                 e);

                _serializationOperationCanceled = true;

                PostSerializationTask(new DispatcherOperationCallback(OnXPSSerializationCompleted), args);

                return(null);
            }
            #pragma warning restore 56500
            #pragma warning restore 1634, 1691

            return(null);
        }
Esempio n. 12
0
        object InvokeMethodOnInstance(out Exception e)
        {
            object data  = null;
            string error = null;    // string that describes known error

            e = null;

            Debug.Assert(_objectType != null);

            object[] parameters = new object[_methodParameters.Count];
            _methodParameters.CopyTo(parameters, 0);

            // PreSharp uses message numbers that the C# compiler doesn't know about.
            // Disable the C# complaints, per the PreSharp documentation.
            #pragma warning disable 1634, 1691

            // PreSharp complains about catching NullReference (and other) exceptions.
            // It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
            #pragma warning disable 56500

            try
            {
                data = _objectType.InvokeMember(MethodName,
                                                s_invokeMethodFlags, null, _objectInstance, parameters,
                                                System.Globalization.CultureInfo.InvariantCulture);
            }
            catch (ArgumentException ae)
            {
                error = "Parameter array contains a string that is a null reference.";
                e     = ae;
            }
            catch (MethodAccessException mae)
            {
                error = "The specified member is a class initializer.";
                e     = mae;
            }
            catch (MissingMethodException mme)
            {
                error = "No method was found with matching parameter signature.";
                e     = mme;
            }
            catch (TargetException te)
            {
                error = "The specified member cannot be invoked on target.";
                e     = te;
            }
            catch (AmbiguousMatchException ame)
            {
                error = "More than one method matches the binding criteria.";
                e     = ame;
            }
            // Catch all exceptions.  When there is no app code on the stack,
            // the exception isn't actionable by the app.
            // Yet we don't want to crash the app.
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalApplicationException(ex))
                {
                    throw;
                }
                error = null;   // indicate unknown error
                e     = ex;
            }
            catch             //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers
            {
                error = null; // indicate unknown error
                e     = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSExceptionInvoke, MethodName, _objectType.Name));
            }

            #pragma warning restore 56500
            #pragma warning restore 1634, 1691

            if (e != null || error != null)
            {
                // report known errors through TraceData (instead of throwing exceptions)
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.ObjDPInvokeFailed, MethodName, _objectType.Name, error, e);
                }

                // in async mode we pass all exceptions to main thread;
                // in [....] mode we don't handle unknown exceptions.
                if (!IsAsynchronous && error == null)
                {
                    throw e;
                }
            }

            return(data);
        }
Esempio n. 13
0
        object CreateObjectInstance(out Exception e)
        {
            object instance = null;
            string error    = null; // string that describes known error

            e = null;

            // PreSharp uses message numbers that the C# compiler doesn't know about.
            // Disable the C# complaints, per the PreSharp documentation.
            #pragma warning disable 1634, 1691

            // PreSharp complains about catching NullReference (and other) exceptions.
            // It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
            #pragma warning disable 56500

            Debug.Assert(_objectType != null);

            try
            {
                object[] parameters = new object[_constructorParameters.Count];
                _constructorParameters.CopyTo(parameters, 0);
                instance = Activator.CreateInstance(_objectType, 0, null, parameters,
                                                    System.Globalization.CultureInfo.InvariantCulture);
                OnPropertyChanged(s_instance);
            }
            catch (ArgumentException ae)
            {
                // this may fire when trying to create Context Affinity objects
                error = "Cannot create Context Affinity object.";
                e     = ae;
            }
            catch (System.Runtime.InteropServices.COMException ce)
            {
                // this may fire due to marshalling issues
                error = "Marshaling issue detected.";
                e     = ce;
            }
            catch (System.MissingMethodException mme)
            {
                // this may be due to setting parameters to a non parameter
                // only class contructor
                error = "Wrong parameters for constructor.";
                e     = mme;
            }
            // Catch all exceptions.  When there is no app code on the stack,
            // the exception isn't actionable by the app.
            // Yet we don't want to crash the app.
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalApplicationException(ex))
                {
                    throw;
                }
                error = null;   // indicate unknown error
                e     = ex;
            }
            catch             // non CLS compliant exception
            {
                error = null; // indicate unknown error
                e     = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSException, _objectType.Name));
            }

            #pragma warning restore 56500
            #pragma warning restore 1634, 1691

            if (e != null || error != null)
            {
                // report known errors through TraceData (instead of throwing exceptions)
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.ObjDPCreateFailed, _objectType.Name, error, e);
                }

                // in async mode we pass all exceptions to main thread;
                // in [....] mode we don't handle unknown exceptions.
                if (!IsAsynchronous && error == null)
                {
                    throw e;
                }
            }

            return(instance);
        }
Esempio n. 14
0
        // Token: 0x06001C5B RID: 7259 RVA: 0x000857F4 File Offset: 0x000839F4
        private object InvokeMethodOnInstance(out Exception e)
        {
            object result = null;
            string text   = null;

            e = null;
            object[] array = new object[this._methodParameters.Count];
            this._methodParameters.CopyTo(array, 0);
            try
            {
                result = this._objectType.InvokeMember(this.MethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, null, this._objectInstance, array, CultureInfo.InvariantCulture);
            }
            catch (ArgumentException ex)
            {
                text = "Parameter array contains a string that is a null reference.";
                e    = ex;
            }
            catch (MethodAccessException ex2)
            {
                text = "The specified member is a class initializer.";
                e    = ex2;
            }
            catch (MissingMethodException ex3)
            {
                text = "No method was found with matching parameter signature.";
                e    = ex3;
            }
            catch (TargetException ex4)
            {
                text = "The specified member cannot be invoked on target.";
                e    = ex4;
            }
            catch (AmbiguousMatchException ex5)
            {
                text = "More than one method matches the binding criteria.";
                e    = ex5;
            }
            catch (Exception ex6)
            {
                if (CriticalExceptions.IsCriticalApplicationException(ex6))
                {
                    throw;
                }
                text = null;
                e    = ex6;
            }
            catch
            {
                text = null;
                e    = new InvalidOperationException(SR.Get("ObjectDataProviderNonCLSExceptionInvoke", new object[]
                {
                    this.MethodName,
                    this._objectType.Name
                }));
            }
            if (e != null || text != null)
            {
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.ObjDPInvokeFailed, new object[]
                    {
                        this.MethodName,
                        this._objectType.Name,
                        text,
                        e
                    });
                }
                if (!this.IsAsynchronous && text == null)
                {
                    throw e;
                }
            }
            return(result);
        }
Esempio n. 15
0
        // this method can run on a worker thread!
        private void CreateDocFromExternalSource(WebRequest request)
        {
            bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.XmlProvider);

            XmlDocument doc = new XmlDocument();
            Exception   ex  = null;

            // request the content from the URI
            try
            {
                if (isExtendedTraceEnabled)
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.XmlLoadSource(
                                        TraceData.Identify(this),
                                        Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                                        TraceData.Identify(request.RequestUri.ToString())));
                }

                WebResponse response = WpfWebRequestHelper.GetResponse(request);
                if (response == null)
                {
                    throw new InvalidOperationException(SR.Get(SRID.GetResponseFailed));
                }

                // Get Stream and content type from WebResponse.
                Stream stream = response.GetResponseStream();

                if (isExtendedTraceEnabled)
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.XmlLoadDoc(
                                        TraceData.Identify(this)));
                }

                // load the XML from the stream
                doc.Load(stream);
                stream.Close();
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e))
                {
                    throw;
                }
                ex = e;
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, Source, ex);
                }
            }
            //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers
            catch
            {
                throw;
            }

            if (ex != null)
            {
                if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery))
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.QueryFinished(
                                        TraceData.Identify(this),
                                        Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
                                        TraceData.Identify(null),
                                        TraceData.IdentifyException(ex)));
                }

                // we're done if we got an error up to this point
                // both .Data and .Document properties will be reset to null
                OnQueryFinished(null, ex, CompletedCallback, null);
                return;  // have an error, no processing of DOM
            }

            BuildNodeCollection(doc);
            // above method also calls OnQueryFinished to push new property values
        }
        internal ConnectionPointCookie(object source, object sink, Type eventInterface)
        {
            Exception ex = null;

            if (source is UnsafeNativeMethods.IConnectionPointContainer)
            {
                UnsafeNativeMethods.IConnectionPointContainer connectionPointContainer = (UnsafeNativeMethods.IConnectionPointContainer)source;
                try
                {
                    Guid guid = eventInterface.GUID;
                    if (connectionPointContainer.FindConnectionPoint(ref guid, out this.connectionPoint) != 0)
                    {
                        this.connectionPoint = null;
                    }
                }
                catch (Exception ex2)
                {
                    if (CriticalExceptions.IsCriticalException(ex2))
                    {
                        throw;
                    }
                    this.connectionPoint = null;
                }
                if (this.connectionPoint == null)
                {
                    ex = new ArgumentException(SR.Get("AxNoEventInterface", new object[]
                    {
                        eventInterface.Name
                    }));
                }
                else if (sink == null || (!eventInterface.IsInstanceOfType(sink) && !Marshal.IsComObject(sink)))
                {
                    ex = new InvalidCastException(SR.Get("AxNoSinkImplementation", new object[]
                    {
                        eventInterface.Name
                    }));
                }
                else
                {
                    int num = this.connectionPoint.Advise(sink, ref this.cookie);
                    if (num != 0)
                    {
                        this.cookie = 0;
                        Marshal.FinalReleaseComObject(this.connectionPoint);
                        this.connectionPoint = null;
                        ex = new InvalidOperationException(SR.Get("AxNoSinkAdvise", new object[]
                        {
                            eventInterface.Name,
                            num
                        }));
                    }
                }
            }
            else
            {
                ex = new InvalidCastException(SR.Get("AxNoConnectionPointContainer"));
            }
            if (this.connectionPoint != null && this.cookie != 0)
            {
                return;
            }
            if (this.connectionPoint != null)
            {
                Marshal.FinalReleaseComObject(this.connectionPoint);
            }
            if (ex == null)
            {
                throw new ArgumentException(SR.Get("AxNoConnectionPoint", new object[]
                {
                    eventInterface.Name
                }));
            }
            throw ex;
        }
Esempio n. 17
0
        /// Creates a connection point to of the given interface type.
        /// which will call on a managed code sink that implements that interface.
        internal ConnectionPointCookie(object source, object sink, Type eventInterface)
        {
            Exception ex = null;

            if (source is UnsafeNativeMethods.IConnectionPointContainer)
            {
                UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source;

                try
                {
                    Guid tmp = eventInterface.GUID;
                    if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK)
                    {
                        connectionPoint = null;
                    }
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }

                    connectionPoint = null;
                }

                if (connectionPoint == null)
                {
                    ex = new ArgumentException(SR.Get(SRID.AxNoEventInterface, eventInterface.Name));
                }
                // IsComObject(sink): this is the case of a managed sink object wrapped in IDispatchSTAForwarder -
                // see WebBrowser.CreateSink().
                else if (sink == null || !eventInterface.IsInstanceOfType(sink) && !Marshal.IsComObject(sink))
                {
                    ex = new InvalidCastException(SR.Get(SRID.AxNoSinkImplementation, eventInterface.Name));
                }
                else
                {
                    int hr = connectionPoint.Advise(sink, ref cookie);
                    if (hr != NativeMethods.S_OK)
                    {
                        cookie = 0;
                        Marshal.FinalReleaseComObject(connectionPoint);
                        connectionPoint = null;
                        ex = new InvalidOperationException(SR.Get(SRID.AxNoSinkAdvise, eventInterface.Name, hr));
                    }
                }
            }
            else
            {
                ex = new InvalidCastException(SR.Get(SRID.AxNoConnectionPointContainer));
            }


            if (connectionPoint == null || cookie == 0)
            {
                if (connectionPoint != null)
                {
                    Marshal.FinalReleaseComObject(connectionPoint);
                }

                if (ex == null)
                {
                    throw new ArgumentException(SR.Get(SRID.AxNoConnectionPoint, eventInterface.Name));
                }
                else
                {
                    throw ex;
                }
            }
        }
Esempio n. 18
0
        ///
        /// Begin a download
        ///
        internal static void BeginDownload(
            BitmapDecoder decoder,
            Uri uri,
            RequestCachePolicy uriCachePolicy,
            Stream stream
            )
        {
            lock (_syncLock)
            {
                if (!_thread.IsAlive)
                {
                    _thread.IsBackground = true;
                    _thread.Start();
                }
            }

            QueueEntry entry;

            // If there is already a download for this uri, just add the decoder to the list
            if (uri != null)
            {
                lock (_syncLock)
                {
                    if (_uriTable[uri] != null)
                    {
                        entry = (QueueEntry)_uriTable[uri];
                        entry.decoders.Add(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(decoder));
            }

            entry.inputUri    = uri;
            entry.inputStream = stream;

            string cacheFolder = MS.Win32.WinInet.InternetCacheFolder.LocalPath;
            bool   passed      = false;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
            try
            {
                // Get the file path
                StringBuilder tmpFileName = new StringBuilder(NativeMethods.MAX_PATH);
                MS.Win32.UnsafeNativeMethods.GetTempFileName(cacheFolder, "WPF", 0, tmpFileName);

                try
                {
                    string         pathToUse  = tmpFileName.ToString();
                    SafeFileHandle fileHandle = MS.Win32.UnsafeNativeMethods.CreateFile(
                        pathToUse,
                        NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, /* dwDesiredAccess */
                        0,                                                        /* dwShare */
                        null,                                                     /* lpSecurityAttributes */
                        NativeMethods.CREATE_ALWAYS,                              /* dwCreationDisposition */
                        NativeMethods.FILE_ATTRIBUTE_TEMPORARY |
                        NativeMethods.FILE_FLAG_DELETE_ON_CLOSE,                  /* dwFlagsAndAttributes */
                        IntPtr.Zero                                               /* hTemplateFile */
                        );

                    if (fileHandle.IsInvalid)
                    {
                        throw new Win32Exception();
                    }

                    entry.outputStream = new FileStream(fileHandle, FileAccess.ReadWrite);
                    entry.streamPath   = pathToUse;
                    passed             = true;
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }

            if (!passed)
            {
                throw new IOException(SR.Get(SRID.Image_CannotCreateTempFile));
            }

            entry.readBuffer    = new byte[READ_SIZE];
            entry.contentLength = -1;
            entry.contentType   = string.Empty;
            entry.lastPercent   = 0;

            // Add the entry to the table if we know the uri
            if (uri != null)
            {
                lock (_syncLock)
                {
                    _uriTable[uri] = entry;
                }
            }

            if (stream == null)
            {
                entry.webRequest = WpfWebRequestHelper.CreateRequest(uri);
                if (uriCachePolicy != null)
                {
                    entry.webRequest.CachePolicy = uriCachePolicy;
                }

                entry.webRequest.BeginGetResponse(_responseCallback, entry);
            }
            else
            {
                _workQueue.Enqueue(entry);
                // Signal
                _waitEvent.Set();
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Validate is called when Data binding is updating
        /// </summary>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            // This rule is called during the CommittedValue step, so the value is the
            // owner of the rule collection - either a BindingGroup or an individual
            // binding expression.
            BindingGroup      bindingGroup;
            BindingExpression bindingExpr;

            if ((bindingGroup = value as BindingGroup) != null)
            {
                // in a BindingGroup, check the item-level IDataErrorInfo for each
                // source item in the group
                IList items = bindingGroup.Items;
                for (int i = items.Count - 1; i >= 0; --i)
                {
                    IDataErrorInfo idei = items[i] as IDataErrorInfo;
                    if (idei != null)
                    {
                        string error = idei.Error;
                        if (!String.IsNullOrEmpty(error))
                        {
                            return(new ValidationResult(false, error));
                        }
                    }
                }
            }
            else if ((bindingExpr = value as BindingExpression) != null)
            {
                // in a binding, check the error info for the binding's source
                // property
                IDataErrorInfo idei = bindingExpr.SourceItem as IDataErrorInfo;
                string         name = (idei != null) ? bindingExpr.SourcePropertyName : null;

                if (!String.IsNullOrEmpty(name))
                {
                    // get the data error information, if any, by calling idie[name].
                    // We do this in a paranoid way, even though indexers with
                    // string-valued arguments are not supposed to throw exceptions.

                    // PreSharp uses message numbers that the C# compiler doesn't know about.
                    // Disable the C# complaints, per the PreSharp documentation.
                    #pragma warning disable 1634, 1691

                    // PreSharp complains about catching NullReference (and other) exceptions.
                    // It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
                    #pragma warning disable 56500

                    string error;
                    try
                    {
                        error = idei[name];
                    }
                    catch (Exception ex)
                    {
                        if (CriticalExceptions.IsCriticalApplicationException(ex))
                        {
                            throw;
                        }

                        error = null;

                        if (TraceData.IsEnabled)
                        {
                            TraceData.TraceAndNotify(TraceEventType.Error,
                                                     TraceData.DataErrorInfoFailed(
                                                         name,
                                                         idei.GetType().FullName,
                                                         ex.GetType().FullName,
                                                         ex.Message),
                                                     bindingExpr);
                        }
                    }
                    #pragma warning restore 56500
                    #pragma warning restore 1634, 1691

                    if (!String.IsNullOrEmpty(error))
                    {
                        return(new ValidationResult(false, error));
                    }
                }
            }
            else
            {
                throw new InvalidOperationException(SR.Get(SRID.ValidationRule_UnexpectedValue, this, value));
            }

            return(ValidationResult.ValidResult);
        }
Esempio n. 20
0
        InvokeSaveAsXamlBatchWorkItem(
            Object arg
            )
        {
            try
            {
                // This logic must be mirrored in IsAsyncWorkPending see remarks.

                if (!_serializationOperationCanceled)
                {
                    if (!_isBatchWorkItemInProgress && _batchOperationQueue.Count > 0)
                    {
                        BatchOperationWorkItem batchOperationWorkItem = (BatchOperationWorkItem)_batchOperationQueue.Dequeue();

                        if (batchOperationWorkItem.OperationType == BatchOperationType.batchWrite)
                        {
                            _currentPageXmlWriter = Simulator.SimulateBeginFixedPage();

                            ReachSerializer reachSerializer = GetSerializer(batchOperationWorkItem.SerializedObject);

                            if (reachSerializer != null)
                            {
                                //
                                // Prepare the context that is going to be pushed on the stack
                                //
                                SerializationManagerOperationContextStack
                                    contextStack = new SerializationManagerOperationContextStack(reachSerializer,
                                                                                                 batchOperationWorkItem.SerializedObject);
                                //
                                // At this stage, start calling another method which would peak at the stack
                                //
                                _operationStack.Push(contextStack);

                                PostSerializationTask(new DispatcherOperationCallback(InvokeSaveAsXamlBatchWorkItem));
                            }
                            else
                            {
                                throw new XpsSerializationException(SR.Get(SRID.ReachSerialization_NoSerializer));
                            }
                            _isBatchWorkItemInProgress = true;
                        }
                        else if (batchOperationWorkItem.OperationType == BatchOperationType.batchCommit)
                        {
                            Simulator.EndConfirmToXPSStructure(IsBatchMode);
                            XPSSerializationCompletionMethod();
                        }
                    }
                    else
                    {
                        if (_operationStack.Count > 0)
                        {
                            Object objectOnStack = _operationStack.Pop();

                            if (objectOnStack.GetType() ==
                                typeof(System.Windows.Xps.Serialization.SerializationManagerOperationContextStack))
                            {
                                SerializationManagerOperationContextStack context =
                                    (SerializationManagerOperationContextStack)objectOnStack;

                                context.ReachSerializer.SerializeObject(context.SerializedObject);
                            }
                            else if (typeof(System.Windows.Xps.Serialization.ReachSerializerContext).IsAssignableFrom(objectOnStack.GetType()))
                            {
                                ReachSerializerContext context = (ReachSerializerContext)objectOnStack;
                                context.Serializer.AsyncOperation(context);
                            }
                            PostSerializationTask(new DispatcherOperationCallback(InvokeSaveAsXamlBatchWorkItem));
                        }
                        else
                        {
                            Simulator.SimulateEndFixedPage(_currentPageXmlWriter);
                            _isBatchWorkItemInProgress = false;
                            _currentPageXmlWriter      = null;
                        }
                    }
                }
            }
            catch (Exception e) when(!CriticalExceptions.IsCriticalException(e))
            {
                XpsSerializationCompletedEventArgs args = new XpsSerializationCompletedEventArgs(false, // Indicate that an error happened
                                                                                                 null,
                                                                                                 e);

                _serializationOperationCanceled = true;

                PostSerializationTask(new DispatcherOperationCallback(OnXPSSerializationCompleted), args);
            }

            return(null);
        }
Esempio n. 21
0
        /// <summary> Called by the browser to serialize the entire journal or just the index of
        /// the current entry. The second case is when an internal Journal update needs to be
        /// reflected in the TravelLog.
        /// </summary>
        /// <param name="arg"> true is the entire Journal is to serialized </param>
        private object _GetSaveHistoryBytesDelegate(object arg)
        {
            bool entireJournal = (bool)arg;

            SaveHistoryReturnInfo info = new SaveHistoryReturnInfo();

            // DevDiv 716414 / DevDiv2 196517 & 224724:
            // Checking _serviceProvider for null due to COM reentrancy issues observed by customers.
            // Users who perform frequent refreshes may experience shutdown while we are still starting up and are not fully initialized.
            // The ServiceProvider field is one of the last things to be set during initialization, so if this is null
            // we know that we have not finished initialization much less run the app and thus have no need to save history.
            if (_serviceProvider == null)
            {
                return(null);
            }

            // When we are here, the browser has just started to shut down, so we should only check
            // whether the application object is shutting down.
            if (Application.IsApplicationObjectShuttingDown == true)
            {
                return(null);
            }

            Invariant.Assert(_rbw.Value != null, "BrowserJournalingError: _rbw should not be null");

            Journal journal = _rbw.Value.Journal;

            Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window");

            JournalEntry entry;

            if (entireJournal) // The application is about to be shut down...
            {
                NavigationService topNavSvc = _rbw.Value.NavigationService;
                try
                {
                    topNavSvc.RequestCustomContentStateOnAppShutdown();
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }
                }

                journal.PruneKeepAliveEntries();

                // Since the current page is not added to the journal until it is replaced,
                // we add it here explicitly to the internal Journal before serializing it.
                entry = topNavSvc.MakeJournalEntry(JournalReason.NewContentNavigation);
                if (entry != null && !entry.IsAlive())
                {
                    if (entry.JEGroupState.JournalDataStreams != null)
                    {
                        entry.JEGroupState.JournalDataStreams.PrepareForSerialization();
                    }
                    journal.UpdateCurrentEntry(entry);
                }
                else // Maybe the current content is null or a PageFunction doesn't want to be journaled.
                {   // Then the previous navigable page, if any, should be remembered as current.
                    entry = journal.GetGoBackEntry();
                    // i. _LoadHistoryStreamDelegate() has a similar special case.
                }
            }
            else
            {   // (Brittle) Assumption: GetSaveHistoryBytes() is called after the current entry has
                // been updated in the internal journal but before the new navigation is committed.
                // This means journal.CurrentEntry is what was just added (or updated).
                // Note that it would be wrong to call topNavSvc.MakeJournalEntry() in this case because
                // the navigation that just took place may be in a different NavigationService (in a
                // frame), and here we don't know which one it is.
                entry = journal.CurrentEntry;

                // The entry may be null here when the user has selected "New Window" or pressed Ctrl+N.
                // In this case the browser calls us on IPersistHistory::Save and then throws that data
                // away.  Hopefully at some point in the future that saved data will be loaded in the new
                // window via IPersistHistory::Load.  This unusual behavior is tracked in bug 1353584.
            }

            if (entry != null)
            {
                info.title   = entry.Name;
                info.entryId = entry.Id;
            }
            else
            {
                info.title = _rbw.Value.Title;
            }

            // We only use the base URI here because the travel log will validate a file URI when making a PIDL.
            // We use the URI stored in the JournalEntry, and the travel log doesn't care what the URI is, so
            // duplicates don't matter.
            info.uri = BindUriHelper.UriToString(Uri);

            MemoryStream saveStream = new MemoryStream();

            saveStream.Seek(0, SeekOrigin.Begin);

            if (entireJournal)
            {
                //Save the Journal and BaseUri also. We don't need BaseUri except for the xaml case
                //since this is set specially for the container case (ssres scheme). Exe case
                //will pretty much set it to the exe path. For the xaml case it is set to the path
                //of the first uri(eg BaseDir\page1.xaml) that was navigated to.
                //BaseDir/Subdir/page2.xaml is also considered to be in the same extent and when
                //we navigate back to the app from a webpage, the baseUri should still be BaseDir
                //not BaseDir/Subdir. We were setting the BaseDir from JournalEntry.Uri but we may
                //end up setting BaseUri to BaseDir/Subdir which is not the same. So explicitly
                //persist BaseUri as well
                BrowserJournal browserJournal = new BrowserJournal(journal, BindUriHelper.BaseUri);

                new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
                try
                {
                    saveStream.WriteByte(BrowserJournalHeader);
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(saveStream, browserJournal);
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }

                    // The application is shutting down and the exception would not be reported anyway.
                    // This is here to help with debugging and failure analysis.
                    Invariant.Assert(false, "Failed to serialize the navigation journal: " + e);
                }
                finally
                {
                    CodeAccessPermission.RevertAll();
                }
            }
            else
            {
                saveStream.WriteByte(JournalIdHeader);
                WriteInt32(saveStream, info.entryId);
            }

            info.saveByteArray = saveStream.ToArray();
            ((IDisposable)saveStream).Dispose();

            return(info);
        }
Esempio n. 22
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            try
            {
                if (value == null)
                {
                    throw GetConvertFromException(value);
                }

                if (((value is string) && (!string.IsNullOrEmpty((string)value))) || (value is Uri))
                {
                    UriHolder uriHolder = TypeConverterHelper.GetUriFromUriContext(context, value);
                    return(BitmapFrame.CreateFromUriOrStream(
                               uriHolder.BaseUri,
                               uriHolder.OriginalUri,
                               null,
                               BitmapCreateOptions.None,
                               BitmapCacheOption.Default,
                               null
                               ));
                }
                else if (value is byte[])
                {
                    byte[] bytes = (byte[])value;

                    if (bytes != null)
                    {
                        Stream memStream = null;

                        //
                        // this might be a magical OLE thing, try that first.
                        //
                        memStream = GetBitmapStream(bytes);

                        if (memStream == null)
                        {
                            //
                            // guess not.  Try plain memory.
                            //
                            memStream = new MemoryStream(bytes);
                        }

                        return(BitmapFrame.Create(
                                   memStream,
                                   BitmapCreateOptions.None,
                                   BitmapCacheOption.Default
                                   ));
                    }
                }
                else if (value is Stream)
                {
                    Stream stream = (Stream)value;

                    return(BitmapFrame.Create(
                               stream,
                               BitmapCreateOptions.None,
                               BitmapCacheOption.Default
                               ));
                }

                return(base.ConvertFrom(context, culture, value));
            }
            catch (Exception e)
            {
                if (!CriticalExceptions.IsCriticalException(e))
                {
                    if (context == null && CoreAppContextSwitches.OverrideExceptionWithNullReferenceException)
                    {
                        throw new NullReferenceException();
                    }

                    IProvideValueTarget ipvt = context?.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                    if (ipvt != null)
                    {
                        IProvidePropertyFallback ippf = ipvt.TargetObject as IProvidePropertyFallback;
                        DependencyProperty       dp   = ipvt.TargetProperty as DependencyProperty;
                        // We only want to call IPPF.SetValue if the target can handle it.
                        // We need to check for non DP scenarios (This is currently an internal interface used
                        //             only by Image so it's okay for now)

                        if (ippf != null && dp != null && ippf.CanProvidePropertyFallback(dp.Name))
                        {
                            return(ippf.ProvidePropertyFallback(dp.Name, e));
                        }
                    }
                }

                // We want to rethrow the exception in the case we can't handle it.
                throw;
            }
        }
Esempio n. 23
0
        ///
        /// Begin a download
        ///
        internal static void BeginDownload(
            BitmapDecoder decoder,
            Uri uri,
            RequestCachePolicy uriCachePolicy,
            Stream stream
            )
        {
            lock (_syncLock)
            {
                if (!_thread.IsAlive)
                {
                    _thread.IsBackground = true;
                    _thread.Start();
                }
            }

            QueueEntry entry;

            // If there is already a download for this uri, just add the decoder to the list
            if (uri != null)
            {
                lock (_syncLock)
                {
                    if (_uriTable[uri] != null)
                    {
                        entry = (QueueEntry)_uriTable[uri];
                        entry.decoders.Add(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(decoder));
            }

            entry.inputUri    = uri;
            entry.inputStream = stream;

            string cacheFolder = MS.Win32.WinInet.InternetCacheFolder.LocalPath;
            bool   passed      = false;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
            try
            {
                // Get the file path
                StringBuilder tmpFileName = new StringBuilder(NativeMethods.MAX_PATH);
                MS.Win32.UnsafeNativeMethods.GetTempFileName(cacheFolder, "WPF", 0, tmpFileName);

                try
                {
                    string         pathToUse  = tmpFileName.ToString();
                    SafeFileHandle fileHandle = MS.Win32.UnsafeNativeMethods.CreateFile(
                        pathToUse,
                        NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, /* dwDesiredAccess */
                        0,                                                        /* dwShare */
                        null,                                                     /* lpSecurityAttributes */
                        NativeMethods.CREATE_ALWAYS,                              /* dwCreationDisposition */
                        NativeMethods.FILE_ATTRIBUTE_TEMPORARY |
                        NativeMethods.FILE_FLAG_DELETE_ON_CLOSE,                  /* dwFlagsAndAttributes */
                        IntPtr.Zero                                               /* hTemplateFile */
                        );

                    if (fileHandle.IsInvalid)
                    {
                        throw new Win32Exception();
                    }

                    entry.outputStream = new FileStream(fileHandle, FileAccess.ReadWrite);
                    entry.streamPath   = pathToUse;
                    passed             = true;
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }

            if (!passed)
            {
                throw new IOException(SR.Get(SRID.Image_CannotCreateTempFile));
            }

            entry.readBuffer    = new byte[READ_SIZE];
            entry.contentLength = -1;
            entry.contentType   = string.Empty;
            entry.lastPercent   = 0;

            // Add the entry to the table if we know the uri
            if (uri != null)
            {
                lock (_syncLock)
                {
                    _uriTable[uri] = entry;
                }
            }

            if (stream == null)
            {
                bool fElevate = false;
                if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
                {
                    SecurityHelper.BlockCrossDomainForHttpsApps(uri);

                    // In this case we first check to see if the consumer has media permissions for
                    // safe media (Site of Origin + Cross domain), if it
                    // does we assert and run the code that requires the assert
                    if (SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.NoAudio,
                                                                MediaPermissionVideo.NoVideo,
                                                                MediaPermissionImage.SafeImage))
                    {
                        fElevate = true;
                    }
                }

                // This is the case where we are accessing an http image from an http site and we have media permission
                if (fElevate)
                {
                    (new WebPermission(NetworkAccess.Connect, BindUriHelper.UriToString(uri))).Assert(); // BlessedAssert
                }
                try
                {
                    entry.webRequest = WpfWebRequestHelper.CreateRequest(uri);
                    if (uriCachePolicy != null)
                    {
                        entry.webRequest.CachePolicy = uriCachePolicy;
                    }
                }
                finally
                {
                    if (fElevate)
                    {
                        WebPermission.RevertAssert();
                    }
                }

                entry.webRequest.BeginGetResponse(_responseCallback, entry);
            }
            else
            {
                _workQueue.Enqueue(entry);
                // Signal
                _waitEvent.Set();
            }
        }
Esempio n. 24
0
        /// <summary>
        /// called when in async mode when get a time slice to read and load the Tree
        /// </summary>
        internal virtual void HandleAsyncQueueItem()
        {
            try
            {
                int startTickCount = MS.Win32.SafeNativeMethods.GetTickCount();
                //bool moreData = true;

                // for debugging, can set the Maximum Async records to
                // read via markup
                // x:AsyncRecords="3" would loop three times
                // Todo: This should either be removed at some point
                int maxRecords = _maxAsynxRecords;

                System.Xaml.XamlReader xamlReader = _textReader;

                IXamlLineInfo         xamlLineInfo         = xamlReader as IXamlLineInfo;
                IXamlLineInfoConsumer xamlLineInfoConsumer = _objectWriter as IXamlLineInfoConsumer;
                bool shouldPassLineNumberInfo = false;
                if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) &&
                    (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo))
                {
                    shouldPassLineNumberInfo = true;
                }

                XamlMember synchronousRecordProperty = _textReader.SchemaContext.GetXamlDirective(XamlLanguage.Xaml2006Namespace, "AsyncRecords");

                while (!xamlReader.IsEof && !_parseCancelled)
                {
                    WpfXamlLoader.TransformNodes(xamlReader, _objectWriter, true /*onlyLoadOneNode*/, _skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, _stack, _styleConnector);

                    if (xamlReader.NodeType == System.Xaml.XamlNodeType.Value && _stack.CurrentFrame.Property == synchronousRecordProperty)
                    {
                        if (xamlReader.Value is int)
                        {
                            _maxAsynxRecords = (int)xamlReader.Value;
                        }
                        else if (xamlReader.Value is String)
                        {
                            _maxAsynxRecords = Int32.Parse(xamlReader.Value as String, TypeConverterHelper.InvariantEnglishUS);
                        }
                        maxRecords = _maxAsynxRecords;
                    }

                    //Debug.Assert (1 >= RootList.Count, "Multiple roots not supported in async mode");

                    // check the timeout
                    int elapsed = MS.Win32.SafeNativeMethods.GetTickCount() - startTickCount;

                    // check for rollover
                    if (elapsed < 0)
                    {
                        startTickCount = 0; // reset to 0,
                    }
                    else if (elapsed > AsyncLoopTimeout)
                    {
                        break;
                    }

                    // decrement and compare with zero so the unitialized -1  and zero case
                    // doesn't break the loop.
                    if (--maxRecords == 0)
                    {
                        break;
                    }
                }
            }
            catch (XamlParseException e)
            {
                _parseException = e;
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e) || !XamlReader.ShouldReWrapException(e, _baseUri))
                {
                    _parseException = e;
                }
                else
                {
                    _parseException = XamlReader.WrapException(e, null, _baseUri);
                }
            }
            finally
            {
                if (_parseException != null || _parseCancelled)
                {
                    TreeBuildComplete();
                }
                else
                {
                    // if not at the EndOfDocument then post another work item
                    if (false == _textReader.IsEof)
                    {
                        Post();
                    }
                    else
                    {
                        // Building of the Tree is complete.
                        TreeBuildComplete();
                    }
                }
            }
        }
Esempio n. 25
0
        /// <summary>Performs validation checks on a value.</summary>
        /// <param name="value">The value to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>The result of the validation.</returns>
        // Token: 0x060044E3 RID: 17635 RVA: 0x001385D4 File Offset: 0x001367D4
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            BindingGroup bindingGroup;

            if ((bindingGroup = (value as BindingGroup)) != null)
            {
                IList items = bindingGroup.Items;
                for (int i = items.Count - 1; i >= 0; i--)
                {
                    IDataErrorInfo dataErrorInfo = items[i] as IDataErrorInfo;
                    if (dataErrorInfo != null)
                    {
                        string error = dataErrorInfo.Error;
                        if (!string.IsNullOrEmpty(error))
                        {
                            return(new ValidationResult(false, error));
                        }
                    }
                }
            }
            else
            {
                BindingExpression bindingExpression;
                if ((bindingExpression = (value as BindingExpression)) == null)
                {
                    throw new InvalidOperationException(SR.Get("ValidationRule_UnexpectedValue", new object[]
                    {
                        this,
                        value
                    }));
                }
                IDataErrorInfo dataErrorInfo2 = bindingExpression.SourceItem as IDataErrorInfo;
                string         text           = (dataErrorInfo2 != null) ? bindingExpression.SourcePropertyName : null;
                if (!string.IsNullOrEmpty(text))
                {
                    string text2;
                    try
                    {
                        text2 = dataErrorInfo2[text];
                    }
                    catch (Exception ex)
                    {
                        if (CriticalExceptions.IsCriticalApplicationException(ex))
                        {
                            throw;
                        }
                        text2 = null;
                        if (TraceData.IsEnabled)
                        {
                            TraceData.Trace(TraceEventType.Error, TraceData.DataErrorInfoFailed(new object[]
                            {
                                text,
                                dataErrorInfo2.GetType().FullName,
                                ex.GetType().FullName,
                                ex.Message
                            }), bindingExpression);
                        }
                    }
                    if (!string.IsNullOrEmpty(text2))
                    {
                        return(new ValidationResult(false, text2));
                    }
                }
            }
            return(ValidationResult.ValidResult);
        }
        private object _GetSaveHistoryBytesDelegate(object arg)
        {
            bool flag = (bool)arg;

            ApplicationProxyInternal.SaveHistoryReturnInfo saveHistoryReturnInfo = new ApplicationProxyInternal.SaveHistoryReturnInfo();
            if (this._serviceProvider == null)
            {
                return(null);
            }
            if (Application.IsApplicationObjectShuttingDown)
            {
                return(null);
            }
            Invariant.Assert(this._rbw.Value != null, "BrowserJournalingError: _rbw should not be null");
            Journal journal = this._rbw.Value.Journal;

            Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window");
            JournalEntry journalEntry;

            if (flag)
            {
                NavigationService navigationService = this._rbw.Value.NavigationService;
                try
                {
                    navigationService.RequestCustomContentStateOnAppShutdown();
                }
                catch (Exception ex)
                {
                    if (CriticalExceptions.IsCriticalException(ex))
                    {
                        throw;
                    }
                }
                journal.PruneKeepAliveEntries();
                journalEntry = navigationService.MakeJournalEntry(JournalReason.NewContentNavigation);
                if (journalEntry != null && !journalEntry.IsAlive())
                {
                    if (journalEntry.JEGroupState.JournalDataStreams != null)
                    {
                        journalEntry.JEGroupState.JournalDataStreams.PrepareForSerialization();
                    }
                    journal.UpdateCurrentEntry(journalEntry);
                }
                else
                {
                    journalEntry = journal.GetGoBackEntry();
                }
            }
            else
            {
                journalEntry = journal.CurrentEntry;
            }
            if (journalEntry != null)
            {
                saveHistoryReturnInfo.title   = journalEntry.Name;
                saveHistoryReturnInfo.entryId = journalEntry.Id;
            }
            else
            {
                saveHistoryReturnInfo.title = this._rbw.Value.Title;
            }
            saveHistoryReturnInfo.uri = BindUriHelper.UriToString(this.Uri);
            MemoryStream memoryStream = new MemoryStream();

            memoryStream.Seek(0L, SeekOrigin.Begin);
            if (flag)
            {
                ApplicationProxyInternal.BrowserJournal browserJournal = new ApplicationProxyInternal.BrowserJournal(journal, BindUriHelper.BaseUri);
                new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
                try
                {
                    memoryStream.WriteByte(2);
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(memoryStream, browserJournal);
                    goto IL_1A6;
                }
                catch (Exception ex2)
                {
                    if (CriticalExceptions.IsCriticalException(ex2))
                    {
                        throw;
                    }
                    Invariant.Assert(false, "Failed to serialize the navigation journal: " + ex2);
                    goto IL_1A6;
                }
                finally
                {
                    CodeAccessPermission.RevertAll();
                }
            }
            memoryStream.WriteByte(1);
            ApplicationProxyInternal.WriteInt32(memoryStream, saveHistoryReturnInfo.entryId);
IL_1A6:
            saveHistoryReturnInfo.saveByteArray = memoryStream.ToArray();
            ((IDisposable)memoryStream).Dispose();
            return(saveHistoryReturnInfo);
        }
Esempio n. 27
0
        // Token: 0x0600226A RID: 8810 RVA: 0x000AAE10 File Offset: 0x000A9010
        private static object Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
        {
            XamlContextStack <WpfXamlFrame> stack = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame());
            int persistId = 1;

            settings.AfterBeginInitHandler = delegate(object sender, XamlObjectEventArgs args)
            {
                if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose))
                {
                    IXamlLineInfo xamlLineInfo2 = xamlReader as IXamlLineInfo;
                    int           num           = -1;
                    int           num2          = -1;
                    if (xamlLineInfo2 != null && xamlLineInfo2.HasLineInfo)
                    {
                        num  = xamlLineInfo2.LineNumber;
                        num2 = xamlLineInfo2.LinePosition;
                    }
                    EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientParseXamlBamlInfo, EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, new object[]
                    {
                        (args.Instance == null) ? 0L : PerfService.GetPerfElementID(args.Instance),
                        num,
                        num2
                    });
                }
                UIElement uielement = args.Instance as UIElement;
                if (uielement != null)
                {
                    UIElement uielement2 = uielement;
                    int       persistId  = persistId;
                    persistId++;
                    uielement2.SetPersistId(persistId);
                }
                XamlSourceInfoHelper.SetXamlSourceInfo(args.Instance, args, baseUri);
                DependencyObject dependencyObject = args.Instance as DependencyObject;
                if (dependencyObject != null && stack.CurrentFrame.XmlnsDictionary != null)
                {
                    XmlnsDictionary xmlnsDictionary = stack.CurrentFrame.XmlnsDictionary;
                    xmlnsDictionary.Seal();
                    XmlAttributeProperties.SetXmlnsDictionary(dependencyObject, xmlnsDictionary);
                }
                stack.CurrentFrame.Instance = args.Instance;
            };
            XamlObjectWriter xamlObjectWriter;

            if (writerFactory != null)
            {
                xamlObjectWriter = writerFactory.GetXamlObjectWriter(settings);
            }
            else
            {
                xamlObjectWriter = new XamlObjectWriter(xamlReader.SchemaContext, settings);
            }
            IXamlLineInfo xamlLineInfo = null;
            object        result;

            try
            {
                xamlLineInfo = (xamlReader as IXamlLineInfo);
                IXamlLineInfoConsumer xamlLineInfoConsumer = xamlObjectWriter;
                bool shouldPassLineNumberInfo = false;
                if (xamlLineInfo != null && xamlLineInfo.HasLineInfo && xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)
                {
                    shouldPassLineNumberInfo = true;
                }
                IStyleConnector styleConnector = rootObject as IStyleConnector;
                WpfXamlLoader.TransformNodes(xamlReader, xamlObjectWriter, false, skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, stack, styleConnector);
                xamlObjectWriter.Close();
                result = xamlObjectWriter.Result;
            }
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalException(ex) || !XamlReader.ShouldReWrapException(ex, baseUri))
                {
                    throw;
                }
                XamlReader.RewrapException(ex, xamlLineInfo, baseUri);
                result = null;
            }
            return(result);
        }