private static bool LoadRecognizerDll()
        {
            // ISSUE-2005/01/14-WAYNEZEN,
            // We may hit the problem when an application already load mshwgst.dll from somewhere rather than the
            // directory we are looking for. The options to resolve this -
            //  1. We fail the recognition functionality.
            //  2. We unload the previous mshwgst.dll
            //  3. We switch the DllImport usage to the new dynamic PInvoke mechanism in Whidbey. Please refer to the blog
            //     http://blogs.msdn.com/junfeng/archive/2004/07/14/181932.aspx. Then we don't have to unload the existing
            //     mshwgst.dll.
            String path = null;
            System.Security.PermissionSet permissionSet = new PermissionSet(null);
            permissionSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read,
                                                        System.Security.AccessControl.AccessControlActions.View,
                                                        GestureRecognizerFullPath));
            permissionSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            permissionSet.Assert();  // BlessedAssert:
            try
            {
                RegistryKey regkey = Registry.LocalMachine;
                RegistryKey recognizerKey = regkey.OpenSubKey(GestureRecognizerPath);
                if (recognizerKey != null)
                {
                    try
                    {
                        // Try to read the recognizer path subkey
                        path = recognizerKey.GetValue(GestureRecognizerValueName) as string;
                        if (path == null)
                        {
                            return false;
                        } 
                    }
                    finally
                    {
                        recognizerKey.Close();
                    }
                }
                else
                {
                    // we couldn't find the path in the registry
                    // no key to close
                    return false;
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
 
            if (path != null)
            {
                IntPtr hModule = MS.Win32.UnsafeNativeMethods.LoadLibrary(path);

                // Check whether GetAlternateList exists in the loaded Dll.
                s_GetAlternateListExists = false;
                if ( hModule != IntPtr.Zero )
                {
                    s_GetAlternateListExists = MS.Win32.UnsafeNativeMethods.GetProcAddressNoThrow(
                        new HandleRef(null, hModule), "GetAlternateList") != IntPtr.Zero ?
                        true : false;
                }

                return hModule != IntPtr.Zero ? true : false; 
            }
            return false; //path was null 
        }
예제 #2
0
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public override Object Invoke(
            Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        {
            INVOCATION_FLAGS invocationFlags = InvocationFlags;

            if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
            {
                ThrowNoInvokeException();
            }

            // check basic method consistency. This call will throw if there are problems in the target/method relationship
            CheckConsistency(obj);

#if FEATURE_APPX
            if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
            {
                StackCrawlMark  stackMark = StackCrawlMark.LookForMyCaller;
                RuntimeAssembly caller    = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
                if (caller != null && !caller.IsSafeForReflection())
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
                }
            }
#endif

            if (obj != null)
            {
#if FEATURE_CORECLR
                // For unverifiable code, we require the caller to be critical.
                // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
                invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
#else // FEATURE_CORECLR
                new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
#endif // FEATURE_CORECLR
            }

#if !FEATURE_CORECLR
            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
            {
                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
                {
                    CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
                }
                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
                {
                    RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
                }
            }
#endif // !FEATURE_CORECLR

            Signature sig = Signature;

            // get the signature
            int formalCount = sig.Arguments.Length;
            int actualCount = (parameters != null) ? parameters.Length : 0;
            if (formalCount != actualCount)
            {
                throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
            }

            // if we are here we passed all the previous checks. Time to look at the arguments
            if (actualCount > 0)
            {
                Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
                Object   retValue  = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
                // copy out. This should be made only if ByRef are present.
                for (int index = 0; index < arguments.Length; index++)
                {
                    parameters[index] = arguments[index];
                }
                return(retValue);
            }
            return(RuntimeMethodHandle.InvokeMethod(obj, null, sig, false));
        }
        /// <include file='doc\ThreadExceptionDialog.uex' path='docs/doc[@for="ThreadExceptionDialog.ThreadExceptionDialog"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Windows.Forms.ThreadExceptionDialog'/> class.
        ///
        ///    </para>
        /// </devdoc>
        public ThreadExceptionDialog(Exception t)
        {
            string messageRes;
            string messageText;

            Button[] buttons;
            bool     detailAnchor = false;

            WarningException w = t as WarningException;

            if (w != null)
            {
                messageRes  = SR.ExDlgWarningText;
                messageText = w.Message;
                if (w.HelpUrl == null)
                {
                    buttons = new Button[] { continueButton };
                }
                else
                {
                    buttons = new Button[] { continueButton, helpButton };
                }
            }
            else
            {
                messageText = t.Message;

                detailAnchor = true;

                if (Application.AllowQuit)
                {
                    if (t is SecurityException)
                    {
                        messageRes = "ExDlgSecurityErrorText";
                    }
                    else
                    {
                        messageRes = "ExDlgErrorText";
                    }
                    buttons = new Button[] { detailsButton, continueButton, quitButton };
                }
                else
                {
                    if (t is SecurityException)
                    {
                        messageRes = "ExDlgSecurityContinueErrorText";
                    }
                    else
                    {
                        messageRes = "ExDlgContinueErrorText";
                    }
                    buttons = new Button[] { detailsButton, continueButton };
                }
            }

            if (messageText.Length == 0)
            {
                messageText = t.GetType().Name;
            }
            if (t is SecurityException)
            {
                messageText = SR.GetString(messageRes, t.GetType().Name, Trim(messageText));
            }
            else
            {
                messageText = SR.GetString(messageRes, Trim(messageText));
            }

            StringBuilder detailsTextBuilder = new StringBuilder();
            string        newline            = "\r\n";
            string        separator          = SR.GetString(SR.ExDlgMsgSeperator);
            string        sectionseparator   = SR.GetString(SR.ExDlgMsgSectionSeperator);

            if (Application.CustomThreadExceptionHandlerAttached)
            {
                detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgHeaderNonSwitchable));
            }
            else
            {
                detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgHeaderSwitchable));
            }
            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.GetString(SR.ExDlgMsgExceptionSection)));
            detailsTextBuilder.Append(t.ToString());
            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.GetString(SR.ExDlgMsgLoadedAssembliesSection)));
            new FileIOPermission(PermissionState.Unrestricted).Assert();
            try {
                foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    AssemblyName name    = asm.GetName();
                    string       fileVer = SR.GetString(SR.NotAvailable);

                    try {
                        // bug 113573 -- if there's a path with an escaped value in it
                        // like c:\temp\foo%2fbar, the AssemblyName call will unescape it to
                        // c:\temp\foo\bar, which is wrong, and this will fail.   It doesn't look like the
                        // assembly name class handles this properly -- even the "CodeBase" property is un-escaped
                        // so we can't circumvent this.
                        //
                        if (name.EscapedCodeBase != null && name.EscapedCodeBase.Length > 0)
                        {
                            Uri codeBase = new Uri(name.EscapedCodeBase);
                            if (codeBase.Scheme == "file")
                            {
                                fileVer = FileVersionInfo.GetVersionInfo(NativeMethods.GetLocalPath(name.EscapedCodeBase)).FileVersion;
                            }
                        }
                    }
                    catch (System.IO.FileNotFoundException) {
                    }
                    detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgLoadedAssembliesEntry, name.Name, name.Version, fileVer, name.EscapedCodeBase));
                    detailsTextBuilder.Append(separator);
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.GetString(SR.ExDlgMsgJITDebuggingSection)));
            if (Application.CustomThreadExceptionHandlerAttached)
            {
                detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgFooterNonSwitchable));
            }
            else
            {
                detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgFooterSwitchable));
            }

            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(newline);

            string detailsText = detailsTextBuilder.ToString();

            Graphics g = message.CreateGraphicsInternal();

            Size textSize = Size.Ceiling(g.MeasureString(messageText, Font, MAXWIDTH - 84));

            textSize.Height += 4;
            g.Dispose();

            if (textSize.Width < 180)
            {
                textSize.Width = 180;
            }
            if (textSize.Height > MAXHEIGHT)
            {
                textSize.Height = MAXHEIGHT;
            }

            int width     = textSize.Width + 84;
            int buttonTop = Math.Max(textSize.Height, 40) + 26;

            // SECREVIEW : We must get a hold of the parent to get at it's text
            //           : to make this dialog look like the parent.
            //
            IntSecurity.GetParent.Assert();
            try {
                Form activeForm = Form.ActiveForm;
                if (activeForm == null || activeForm.Text.Length == 0)
                {
                    Text = SR.GetString(SR.ExDlgCaption);
                }
                else
                {
                    Text = SR.GetString(SR.ExDlgCaption2, activeForm.Text);
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            AcceptButton    = continueButton;
            CancelButton    = continueButton;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox     = false;
            MinimizeBox     = false;
            StartPosition   = FormStartPosition.CenterScreen;
            Icon            = null;
            ClientSize      = new Size(width, buttonTop + 31);
            TopMost         = true;

            pictureBox.Location = new Point(0, 0);
            pictureBox.Size     = new Size(64, 64);
            pictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
            if (t is SecurityException)
            {
                pictureBox.Image = SystemIcons.Information.ToBitmap();
            }
            else
            {
                pictureBox.Image = SystemIcons.Error.ToBitmap();
            }
            Controls.Add(pictureBox);
            message.SetBounds(64,
                              8 + (40 - Math.Min(textSize.Height, 40)) / 2,
                              textSize.Width, textSize.Height);
            message.Text = messageText;
            Controls.Add(message);

            continueButton.Text         = SR.GetString(SR.ExDlgContinue);
            continueButton.FlatStyle    = FlatStyle.Standard;
            continueButton.DialogResult = DialogResult.Cancel;

            quitButton.Text         = SR.GetString(SR.ExDlgQuit);
            quitButton.FlatStyle    = FlatStyle.Standard;
            quitButton.DialogResult = DialogResult.Abort;

            helpButton.Text         = SR.GetString(SR.ExDlgHelp);
            helpButton.FlatStyle    = FlatStyle.Standard;
            helpButton.DialogResult = DialogResult.Yes;

            detailsButton.Text      = SR.GetString(SR.ExDlgShowDetails);
            detailsButton.FlatStyle = FlatStyle.Standard;
            detailsButton.Click    += new EventHandler(DetailsClick);

            Button b          = null;
            int    startIndex = 0;

            if (detailAnchor)
            {
                b = detailsButton;

                expandImage = new Bitmap(this.GetType(), "down.bmp");
                expandImage.MakeTransparent();
                collapseImage = new Bitmap(this.GetType(), "up.bmp");
                collapseImage.MakeTransparent();

                b.SetBounds(8, buttonTop, 100, 23);
                b.Image      = expandImage;
                b.ImageAlign = ContentAlignment.MiddleLeft;
                Controls.Add(b);
                startIndex = 1;
            }

            int buttonLeft = (width - 8 - ((buttons.Length - startIndex) * 105 - 5));

            for (int i = startIndex; i < buttons.Length; i++)
            {
                b = buttons[i];
                b.SetBounds(buttonLeft, buttonTop, 100, 23);
                Controls.Add(b);
                buttonLeft += 105;
            }

            details.Text          = detailsText;
            details.ScrollBars    = ScrollBars.Both;
            details.Multiline     = true;
            details.ReadOnly      = true;
            details.WordWrap      = false;
            details.TabStop       = false;
            details.AcceptsReturn = false;

            details.SetBounds(8, buttonTop + 31, width - 16, 154);
            Controls.Add(details);
        }
예제 #4
0
 internal object Deserialize(HeaderHandler handler, __BinaryParser serParser, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage)
 {
     if (serParser == null)
     {
         throw new ArgumentNullException("serParser", Environment.GetResourceString("ArgumentNull_WithParamName", new object[] { serParser }));
     }
     this.bFullDeserialization = false;
     this.TopObject            = null;
     this.topId             = 0L;
     this.bMethodCall       = false;
     this.bMethodReturn     = false;
     this.bIsCrossAppDomain = isCrossAppDomain;
     this.bSimpleAssembly   = this.formatterEnums.FEassemblyFormat == FormatterAssemblyStyle.Simple;
     if (fCheck)
     {
         CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
     }
     this.handler = handler;
     if (this.bFullDeserialization)
     {
         this.m_objectManager   = new ObjectManager(this.m_surrogates, this.m_context, false, this.bIsCrossAppDomain);
         this.serObjectInfoInit = new SerObjectInfoInit();
     }
     serParser.Run();
     if (this.bFullDeserialization)
     {
         this.m_objectManager.DoFixups();
     }
     if (!this.bMethodCall && !this.bMethodReturn)
     {
         if (this.TopObject == null)
         {
             throw new SerializationException(Environment.GetResourceString("Serialization_TopObject"));
         }
         if (this.HasSurrogate(this.TopObject.GetType()) && (this.topId != 0L))
         {
             this.TopObject = this.m_objectManager.GetObject(this.topId);
         }
         if (this.TopObject is IObjectReference)
         {
             this.TopObject = ((IObjectReference)this.TopObject).GetRealObject(this.m_context);
         }
     }
     if (this.bFullDeserialization)
     {
         this.m_objectManager.RaiseDeserializationEvent();
     }
     if (handler != null)
     {
         this.handlerObject = handler(this.headers);
     }
     if (this.bMethodCall)
     {
         object[] topObject = this.TopObject as object[];
         this.TopObject = this.binaryMethodCall.ReadArray(topObject, this.handlerObject);
     }
     else if (this.bMethodReturn)
     {
         object[] returnA = this.TopObject as object[];
         this.TopObject = this.binaryMethodReturn.ReadArray(returnA, methodCallMessage, this.handlerObject);
     }
     return(this.TopObject);
 }
예제 #5
0
        protected override bool RunDialog(IntPtr hWndOwner)
        {
            bool flag;

            System.Windows.Forms.NativeMethods.WndProc    proc = new System.Windows.Forms.NativeMethods.WndProc(this.HookProc);
            System.Windows.Forms.NativeMethods.CHOOSEFONT cf   = new System.Windows.Forms.NativeMethods.CHOOSEFONT();
            IntPtr dC = System.Windows.Forms.UnsafeNativeMethods.GetDC(System.Windows.Forms.NativeMethods.NullHandleRef);

            System.Windows.Forms.NativeMethods.LOGFONT logFont = new System.Windows.Forms.NativeMethods.LOGFONT();
            Graphics graphics = Graphics.FromHdcInternal(dC);

            System.Windows.Forms.IntSecurity.ObjectFromWin32Handle.Assert();
            try
            {
                this.Font.ToLogFont(logFont, graphics);
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
                graphics.Dispose();
            }
            System.Windows.Forms.UnsafeNativeMethods.ReleaseDC(System.Windows.Forms.NativeMethods.NullHandleRef, new HandleRef(null, dC));
            IntPtr zero = IntPtr.Zero;

            try
            {
                zero = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(System.Windows.Forms.NativeMethods.LOGFONT)));
                Marshal.StructureToPtr(logFont, zero, false);
                cf.lStructSize = Marshal.SizeOf(typeof(System.Windows.Forms.NativeMethods.CHOOSEFONT));
                cf.hwndOwner   = hWndOwner;
                cf.hDC         = IntPtr.Zero;
                cf.lpLogFont   = zero;
                cf.Flags       = (this.Options | 0x40) | 8;
                if ((this.minSize > 0) || (this.maxSize > 0))
                {
                    cf.Flags |= 0x2000;
                }
                if (this.ShowColor || this.ShowEffects)
                {
                    cf.rgbColors = ColorTranslator.ToWin32(this.color);
                }
                else
                {
                    cf.rgbColors = ColorTranslator.ToWin32(System.Drawing.Color.Black);
                }
                cf.lpfnHook  = proc;
                cf.hInstance = System.Windows.Forms.UnsafeNativeMethods.GetModuleHandle(null);
                cf.nSizeMin  = this.minSize;
                if (this.maxSize == 0)
                {
                    cf.nSizeMax = 0x7fffffff;
                }
                else
                {
                    cf.nSizeMax = this.maxSize;
                }
                if (!System.Windows.Forms.SafeNativeMethods.ChooseFont(cf))
                {
                    return(false);
                }
                System.Windows.Forms.NativeMethods.LOGFONT logfont2 = null;
                logfont2 = (System.Windows.Forms.NativeMethods.LOGFONT)System.Windows.Forms.UnsafeNativeMethods.PtrToStructure(zero, typeof(System.Windows.Forms.NativeMethods.LOGFONT));
                if ((logfont2.lfFaceName != null) && (logfont2.lfFaceName.Length > 0))
                {
                    logFont = logfont2;
                    this.UpdateFont(logFont);
                    this.UpdateColor(cf.rgbColors);
                }
                flag = true;
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(zero);
                }
            }
            return(flag);
        }
예제 #6
0
        static internal Dictionary <object, SourceLocation> GetSourceLocations(Activity rootActivity, out string sourcePath, out bool isTemporaryFile, out byte[] checksum)
        {
            isTemporaryFile = false;
            checksum        = null;
            string symbolString = DebugSymbol.GetSymbol(rootActivity) as String;

            if (string.IsNullOrEmpty(symbolString) && rootActivity.Children != null && rootActivity.Children.Count > 0)
            { // In case of actual root is wrapped either in x:Class activity or CorrelationScope
                Activity body             = rootActivity.Children[0];
                string   bodySymbolString = DebugSymbol.GetSymbol(body) as String;
                if (!string.IsNullOrEmpty(bodySymbolString))
                {
                    rootActivity = body;
                    symbolString = bodySymbolString;
                }
            }

            if (!string.IsNullOrEmpty(symbolString))
            {
                try
                {
                    WorkflowSymbol wfSymbol = WorkflowSymbol.Decode(symbolString);
                    if (wfSymbol != null)
                    {
                        sourcePath = wfSymbol.FileName;
                        checksum   = wfSymbol.GetChecksum();
                        // rootActivity is the activity with the attached symbol string.
                        // rootActivity.RootActivity is the workflow root activity.
                        // if they are not the same, then it must be compiled XAML, because loose XAML (i.e. XAMLX) always have the symbol attached at the root.
                        if (rootActivity.RootActivity != rootActivity)
                        {
                            Fx.Assert(rootActivity.Parent != null, "Compiled XAML implementation always have a parent.");
                            rootActivity = rootActivity.Parent;
                        }
                        return(GetSourceLocations(rootActivity, wfSymbol, translateInternalActivityToOrigin: false));
                    }
                }
                catch (SerializationException)
                {
                    // Ignore invalid symbol.
                }
            }

            sourcePath = XamlDebuggerXmlReader.GetFileName(rootActivity) as string;
            Dictionary <object, SourceLocation> mapping;
            Assembly localAssembly;
            bool     permissionRevertNeeded = false;

            // This may not be the local assembly since it may not be the real root for x:Class
            localAssembly = rootActivity.GetType().Assembly;

            if (rootActivity.Parent != null)
            {
                localAssembly = rootActivity.Parent.GetType().Assembly;
            }

            if (rootActivity.Children != null && rootActivity.Children.Count > 0)
            { // In case of actual root is wrapped either in x:Class activity or CorrelationScope
                Activity body           = rootActivity.Children[0];
                string   bodySourcePath = XamlDebuggerXmlReader.GetFileName(body) as string;
                if (!string.IsNullOrEmpty(bodySourcePath))
                {
                    rootActivity = body;
                    sourcePath   = bodySourcePath;
                }
            }

            try
            {
                Fx.Assert(!string.IsNullOrEmpty(sourcePath), "If sourcePath is null, it should have been short-circuited before reaching here.");

                SourceLocation tempSourceLocation;
                Activity       tempRootActivity;

                checksum = SymbolHelper.CalculateChecksum(sourcePath);

                if (TryGetSourceLocation(rootActivity, sourcePath, checksum, out tempSourceLocation)) // already has source location.
                {
                    tempRootActivity = rootActivity;
                }
                else
                {
                    byte[] buffer;

#if NET45
                    // Need to store the file in memory temporary so don't have to re-read the file twice
                    // for XamlDebugXmlReader's BracketLocator.
                    // If there is a debugger attached, Assert FileIOPermission for Read access to the specific file.
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        permissionRevertNeeded = true;
                        FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, sourcePath);
                        permission.Assert();
                    }
#endif

                    try
                    {
                        FileInfo fi = new FileInfo(sourcePath);
                        buffer = new byte[fi.Length];

                        using (FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
                        {
                            fs.Read(buffer, 0, buffer.Length);
                        }
                    }
                    finally
                    {
#if NET45
                        // If we Asserted FileIOPermission, revert it.
                        if (permissionRevertNeeded)
                        {
                            CodeAccessPermission.RevertAssert();
                            permissionRevertNeeded = false;
                        }
#endif
                    }

                    object deserializedObject = Deserialize(buffer, localAssembly);
                    IDebuggableWorkflowTree debuggableWorkflowTree = deserializedObject as IDebuggableWorkflowTree;
                    if (debuggableWorkflowTree != null)
                    { // Declarative Service and x:Class case
                        tempRootActivity = debuggableWorkflowTree.GetWorkflowRoot();
                    }
                    else
                    { // Loose XAML case.
                        tempRootActivity = deserializedObject as Activity;
                    }

                    Fx.Assert(tempRootActivity != null, "Unexpected workflow xaml file");
                }

                mapping = new Dictionary <object, SourceLocation>();
                if (tempRootActivity != null)
                {
                    CollectMapping(rootActivity, tempRootActivity, mapping, sourcePath, checksum);
                }
            }
            catch (Exception)
            {
                //// Only eat the exception if we were running in partial trust.
                //if (!PartialTrustHelpers.AppDomainFullyTrusted)
                //{
                //    // Eat the exception and return an empty dictionary.
                //    return new Dictionary<object, SourceLocation>();
                //}
                //else
                //{
                throw;
                //}
            }

            return(mapping);
        }
        internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop)
        {
            new UIPermission(UIPermissionClipboard.AllClipboard).Assert();
            DataObject dataObject;

            try
            {
                dataObject = new DataObject();
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            string text = This.Selection.Text;

            if (text != string.Empty)
            {
                if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text))
                {
                    TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.Text, text);
                }
                if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText))
                {
                    TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.UnicodeText, text);
                }
            }
            if (This.AcceptsRichContent)
            {
                if (SecurityHelper.CheckUnmanagedCodePermission())
                {
                    Stream stream = null;
                    string text2  = WpfPayload.SaveRange(This.Selection, ref stream, false);
                    if (text2.Length > 0)
                    {
                        if (stream != null && TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage))
                        {
                            dataObject.SetData(DataFormats.XamlPackage, stream);
                        }
                        if (TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf))
                        {
                            string text3 = TextEditorCopyPaste.ConvertXamlToRtf(text2, stream);
                            if (text3 != string.Empty)
                            {
                                dataObject.SetData(DataFormats.Rtf, text3, true);
                            }
                        }
                    }
                    Image image = This.Selection.GetUIElementSelected() as Image;
                    if (image != null && image.Source is BitmapSource)
                    {
                        dataObject.SetImage((BitmapSource)image.Source);
                    }
                }
                StringWriter  stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                XmlTextWriter xmlWriter    = new XmlTextWriter(stringWriter);
                TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, false, null);
                string text4 = stringWriter.ToString();
                if (text4.Length > 0 && TextEditorCopyPaste.ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Xaml))
                {
                    TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.Xaml, text4);
                    PermissionSet permissionSet = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin();
                    string        content       = permissionSet.ToString();
                    TextEditorCopyPaste.CriticalSetDataWrapper(dataObject, DataFormats.ApplicationTrust, content);
                }
            }
            DataObjectCopyingEventArgs dataObjectCopyingEventArgs = new DataObjectCopyingEventArgs(dataObject, isDragDrop);

            This.UiScope.RaiseEvent(dataObjectCopyingEventArgs);
            if (dataObjectCopyingEventArgs.CommandCancelled)
            {
                dataObject = null;
            }
            return(dataObject);
        }
예제 #8
0
        protected override void WndProc(ref Message m)
        {
            JwMdiManager ultraTabbedMdiManager = _manager;

            if (ultraTabbedMdiManager == null)
            {
                base.WndProc(ref m);
                return;
            }
            switch (m.Msg)
            {
            case (int)WinApi.Messages.WM_MDIRESTORE:
            case (int)WinApi.Messages.WM_MDIMAXIMIZE:
            case (int)WinApi.Messages.WM_MDITILE:
            case (int)WinApi.Messages.WM_MDICASCADE:
            case (int)WinApi.Messages.WM_MDIICONARRANGE:
                //if (ultraTabbedMdiManager.Enabled)
                //{
                m.Result = IntPtr.Zero;
                return;

            //}
            //break;
            case (int)WinApi.Messages.WM_MDINEXT:
            {
                Form mdiChild = null;
                if (m.WParam == IntPtr.Zero)
                {
                    Control control = Control.FromChildHandle(base.Handle);
                    if (control is Form)
                    {
                        mdiChild = ((Form)control).ActiveMdiChild;
                    }
                }
                else
                {
                    mdiChild = (Control.FromHandle(m.WParam) as Form);
                }
                bool forward    = m.LParam == IntPtr.Zero;
                Form nextWindow = GetNextWindow(mdiChild, forward);
                if (ultraTabbedMdiManager.TabNavigationMode == MdiTabNavigationMode.VisibleOrder)
                {
                    nextWindow?.Activate();
                    m.Result = IntPtr.Zero;
                    return;
                }
                if (!SendActivationNotification(nextWindow))
                {
                    break;
                }
                if (AllowMdiChildActivate(nextWindow))
                {
                    ultraTabbedMdiManager.SubclasserActivatingMdiChild = true;
                    try
                    {
                        base.WndProc(ref m);
                    }
                    finally
                    {
                        ultraTabbedMdiManager.SubclasserActivatingMdiChild = false;
                        ultraTabbedMdiManager.AfterSubclasserFormActivation(nextWindow);
                    }
                }
                else
                {
                    m.Result = IntPtr.Zero;
                }
                return;
            }

            case (int)WinApi.Messages.WM_MDIACTIVATE:
            {
                Form form = Control.FromHandle(m.WParam) as Form;
                if (!SendActivationNotification(form))
                {
                    break;
                }
                if (AllowMdiChildActivate(form))
                {
                    ultraTabbedMdiManager.SubclasserActivatingMdiChild = true;
                    try
                    {
                        base.WndProc(ref m);
                    }
                    finally
                    {
                        ultraTabbedMdiManager.SubclasserActivatingMdiChild = false;
                        ultraTabbedMdiManager.AfterSubclasserFormActivation(form);
                    }
                }
                else
                {
                    m.Result = IntPtr.Zero;
                }
                return;
            }

            case (int)WinApi.Messages.WM_NCPAINT:
            {
                base.WndProc(ref m);
                if (!IsManagerEnabled)
                {
                    return;
                }
                IntPtr   intPtr   = IntPtr.Zero;
                Graphics graphics = null;
                IntPtr   hWnd     = m.HWnd;
                try
                {
                    Rectangle rectangle = new Rectangle(Point.Empty, DisplayRectangle.Size);
                    if (m.WParam == IntPtr.Zero || m.WParam.ToInt64() == 1)
                    {
                        intPtr = WinApi.GetWindowDC(hWnd);
                    }
                    else
                    {
                        intPtr = WinApi.GetDCEx(hWnd, m.WParam, 129);
                        if (intPtr == IntPtr.Zero)
                        {
                            intPtr = WinApi.GetWindowDC(m.HWnd);
                        }
                    }
                    if (intPtr != IntPtr.Zero)
                    {
                        SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                        securityPermission.Assert();
                        graphics = Graphics.FromHdc(intPtr);
                        CodeAccessPermission.RevertAssert();
                        DrawBorder(graphics, rectangle, rectangle);
                        m.Result = IntPtr.Zero;
                    }
                }
                finally
                {
                    graphics?.Dispose();
                    if (intPtr != IntPtr.Zero)
                    {
                        WinApi.ReleaseDC(hWnd, intPtr);
                    }
                }
                return;
            }

            case (int)WinApi.Messages.WM_NCCALCSIZE:
                if (IsManagerEnabled && m.WParam.ToInt64() == 1)
                {
                    NativeWindowMethods.NCCALCSIZE_PARAMS nCCALCSIZE_PARAMS = (NativeWindowMethods.NCCALCSIZE_PARAMS)m.GetLParam(typeof(NativeWindowMethods.NCCALCSIZE_PARAMS));
                    UIElementBorderWidths borderWidth = GetBorderWidth();
                    displayRect = nCCALCSIZE_PARAMS.rectProposed.Rect;
                    nCCALCSIZE_PARAMS.rectProposed.left   += borderWidth.Left;
                    nCCALCSIZE_PARAMS.rectProposed.right  -= borderWidth.Right;
                    nCCALCSIZE_PARAMS.rectProposed.top    += borderWidth.Top;
                    nCCALCSIZE_PARAMS.rectProposed.bottom -= borderWidth.Bottom;
                    Marshal.StructureToPtr(nCCALCSIZE_PARAMS, m.LParam, fDeleteOld: false);
                }
                break;

            case (int)WinApi.Messages.WM_ERASEBKGND:
                base.WndProc(ref m);
                if (IsManagerEnabled)
                {
                    m.Result = new IntPtr(1);
                }
                return;

            case (int)WinApi.Messages.WM_PARENTNOTIFY:
                if ((m.WParam.ToInt32() & 0xFFFF) == 1)
                {
                    _manager.MdiClientCreateNotification();
                }
                break;
            }
            base.WndProc(ref m);
        }
예제 #9
0
        internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
        {
            CodeDomProvider    provider          = new CSharpCodeProvider();
            CompilerParameters codeDomParameters = xmlParameters.CodeDomParameters;

            codeDomParameters.ReferencedAssemblies.AddRange(this.Imports);
            if (this.debugEnabled)
            {
                codeDomParameters.GenerateInMemory        = false;
                codeDomParameters.IncludeDebugInformation = true;
                codeDomParameters.TempFiles.KeepFiles     = true;
            }
            PermissionSet set = new PermissionSet(PermissionState.None);

            if (xmlParameters.IsNeedTempDirAccess)
            {
                set.AddPermission(TempAssembly.FileIOPermission);
            }
            set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            set.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence));
            set.Assert();
            if ((parent != null) && ((codeDomParameters.OutputAssembly == null) || (codeDomParameters.OutputAssembly.Length == 0)))
            {
                string str = AssemblyNameFromOptions(codeDomParameters.CompilerOptions);
                if (str == null)
                {
                    str = GetTempAssemblyPath(codeDomParameters.TempFiles.TempDir, parent, ns);
                }
                codeDomParameters.OutputAssembly = str;
            }
            if ((codeDomParameters.CompilerOptions == null) || (codeDomParameters.CompilerOptions.Length == 0))
            {
                codeDomParameters.CompilerOptions = "/nostdlib";
            }
            else
            {
                codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /nostdlib";
            }
            codeDomParameters.CompilerOptions = codeDomParameters.CompilerOptions + " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION";
            codeDomParameters.Evidence        = evidence;
            CompilerResults results          = null;
            Assembly        compiledAssembly = null;

            try
            {
                results = provider.CompileAssemblyFromSource(codeDomParameters, new string[] { this.writer.ToString() });
                if (results.Errors.Count > 0)
                {
                    StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
                    writer.WriteLine(Res.GetString("XmlCompilerError", new object[] { results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture) }));
                    bool flag = false;
                    foreach (CompilerError error in results.Errors)
                    {
                        error.FileName = "";
                        if (!error.IsWarning || (error.ErrorNumber == "CS1595"))
                        {
                            flag = true;
                            writer.WriteLine(error.ToString());
                        }
                    }
                    if (flag)
                    {
                        throw new InvalidOperationException(writer.ToString());
                    }
                }
                compiledAssembly = results.CompiledAssembly;
            }
            catch (UnauthorizedAccessException)
            {
                string currentUser = GetCurrentUser();
                if ((currentUser == null) || (currentUser.Length == 0))
                {
                    throw new UnauthorizedAccessException(Res.GetString("XmlSerializerAccessDenied"));
                }
                throw new UnauthorizedAccessException(Res.GetString("XmlIdentityAccessDenied", new object[] { currentUser }));
            }
            catch (FileLoadException exception)
            {
                throw new InvalidOperationException(Res.GetString("XmlSerializerCompileFailed"), exception);
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            if (compiledAssembly == null)
            {
                throw new InvalidOperationException(Res.GetString("XmlInternalError"));
            }
            return(compiledAssembly);
        }
예제 #10
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.Compare(contentType, CoreChannel.SOAPMimeType, StringComparison.Ordinal) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }

            bool bClientIsClr = true;

            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }

                if (_protocol == Protocol.Http)
                {
                    String userAgent = (String)requestHeaders["User-Agent"];
                    if (userAgent != null)
                    {
                        if (userAgent.IndexOf("MS .NET Remoting") == -1)
                        {
                            // user agent string did not contain ".NET Remoting", so it is someone else
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }

                bool   bIsCustomErrorEnabled = true;
                object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"];
                if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool)
                {
                    bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled;
                }
                CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled);

                String   soapActionToVerify;
                Header[] h = GetChannelHeaders(requestHeaders, out soapActionToVerify);

                PermissionSet currentPermissionSet = null;
                if (this.TypeFilterLevel != TypeFilterLevel.Full)
                {
                    currentPermissionSet = new PermissionSet(PermissionState.None);
                    currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }

                try {
                    if (currentPermissionSet != null)
                    {
                        currentPermissionSet.PermitOnly();
                    }

                    // Deserialize Request - Stream to IMessage
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, h, _strictBinding, this.TypeFilterLevel);
                }
                finally {
                    if (currentPermissionSet != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }

                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }

                // verify soap action if necessary
                if ((soapActionToVerify != null) &&
                    (!SoapServices.IsSoapActionValidForMethodBase(
                         soapActionToVerify, ((IMethodMessage)requestMsg).MethodBase)))
                {
                    throw new RemotingException(
                              String.Format(
                                  CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"),
                                  soapActionToVerify)
                              );
                }

                // Dispatch Call
                sinkStack.Push(this, null);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg, bClientIsClr,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing  = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                //
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = CoreChannel.SOAPContentType;
                }
            }
            finally{
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }

            return(processing);
        } // ProcessMessage
        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);
        }
        public static void SetDataObject(object data, bool copy, int retryTimes, int retryDelay)
        {
            if (Application.OleRequired() != ApartmentState.STA)
            {
                throw new ThreadStateException(System.Windows.Forms.SR.GetString("ThreadMustBeSTA"));
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (retryTimes < 0)
            {
                object[] args = new object[] { "retryTimes", retryTimes.ToString(CultureInfo.CurrentCulture), 0.ToString(CultureInfo.CurrentCulture) };
                throw new ArgumentOutOfRangeException("retryTimes", System.Windows.Forms.SR.GetString("InvalidLowBoundArgumentEx", args));
            }
            if (retryDelay < 0)
            {
                object[] objArray2 = new object[] { "retryDelay", retryDelay.ToString(CultureInfo.CurrentCulture), 0.ToString(CultureInfo.CurrentCulture) };
                throw new ArgumentOutOfRangeException("retryDelay", System.Windows.Forms.SR.GetString("InvalidLowBoundArgumentEx", objArray2));
            }
            DataObject obj2 = null;

            if (!(data is System.Runtime.InteropServices.ComTypes.IDataObject))
            {
                obj2 = new DataObject(data);
            }
            bool flag = false;

            try
            {
                System.Windows.Forms.IntSecurity.ClipboardRead.Demand();
            }
            catch (SecurityException)
            {
                flag = true;
            }
            if (flag)
            {
                if (obj2 == null)
                {
                    obj2 = data as DataObject;
                }
                if (!IsFormatValid(obj2))
                {
                    throw new SecurityException(System.Windows.Forms.SR.GetString("ClipboardSecurityException"));
                }
            }
            if (obj2 != null)
            {
                obj2.RestrictedFormats = flag;
            }
            int num2 = retryTimes;

            System.Windows.Forms.IntSecurity.UnmanagedCode.Assert();
            try
            {
                int num;
                do
                {
                    if (data is System.Runtime.InteropServices.ComTypes.IDataObject)
                    {
                        num = System.Windows.Forms.UnsafeNativeMethods.OleSetClipboard((System.Runtime.InteropServices.ComTypes.IDataObject)data);
                    }
                    else
                    {
                        num = System.Windows.Forms.UnsafeNativeMethods.OleSetClipboard(obj2);
                    }
                    if (num != 0)
                    {
                        if (num2 == 0)
                        {
                            ThrowIfFailed(num);
                        }
                        num2--;
                        Thread.Sleep(retryDelay);
                    }
                }while (num != 0);
                if (copy)
                {
                    num2 = retryTimes;
                    do
                    {
                        num = System.Windows.Forms.UnsafeNativeMethods.OleFlushClipboard();
                        if (num != 0)
                        {
                            if (num2 == 0)
                            {
                                ThrowIfFailed(num);
                            }
                            num2--;
                            Thread.Sleep(retryDelay);
                        }
                    }while (num != 0);
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
예제 #13
0
        // VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
        // are required for showing the print dialog on Win2k and newer OS'.
        private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data)
        {
            data.Flags     = GetFlags();
            data.nCopies   = PrinterSettings.Copies;
            data.hwndOwner = hwndOwner;

            IntSecurity.AllPrintingAndUnmanagedCode.Assert();
            try {
                if (PageSettings == null)
                {
                    data.hDevMode = PrinterSettings.GetHdevmode();
                }
                else
                {
                    data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
                }

                data.hDevNames = PrinterSettings.GetHdevnames();
            }
            catch (InvalidPrinterException) {
                data.hDevMode  = IntPtr.Zero;
                data.hDevNames = IntPtr.Zero;
                // Leave those fields null; Windows will fill them in
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                // Windows doesn't like it if page numbers are invalid
                if (AllowSomePages)
                {
                    if (PrinterSettings.FromPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.FromPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.ToPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "ToPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.FromPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }

                    unsafe {
                        int *pageRangeField = (int *)data.pageRanges;
                        *    pageRangeField = PrinterSettings.FromPage;
                        pageRangeField += 1;
                        *pageRangeField = PrinterSettings.ToPage;
                    }
                    data.nPageRanges = 1;

                    data.nMinPage = PrinterSettings.MinimumPage;
                    data.nMaxPage = PrinterSettings.MaximumPage;
                }

                //
                // The flags NativeMethods.PD_SHOWHELP and NativeMethods.PD_NONETWORKBUTTON don't work with
                // PrintDlgEx. So we have to strip them out.
                data.Flags &= ~(NativeMethods.PD_SHOWHELP | NativeMethods.PD_NONETWORKBUTTON);

                int hr = UnsafeNativeMethods.PrintDlgEx(data);
                if (NativeMethods.Failed(hr) || data.dwResultAction == NativeMethods.PD_RESULT_CANCEL)
                {
                    return(false);
                }

                IntSecurity.AllPrintingAndUnmanagedCode.Assert();
                try {
                    UpdatePrinterSettings(data.hDevMode, data.hDevNames, (short)data.nCopies, data.Flags, PrinterSettings, PageSettings);
                }
                finally {
                    CodeAccessPermission.RevertAssert();
                }
                PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
                PrinterSettings.PrintToFile = PrintToFile;
                if (AllowSomePages)
                {
                    unsafe {
                        int *pageRangeField = (int *)data.pageRanges;
                        PrinterSettings.FromPage = *pageRangeField;
                        pageRangeField          += 1;
                        PrinterSettings.ToPage   = *pageRangeField;
                    }
                }

                // Fix Dev10 #575399, when the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
                // PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
                // to print, and the PD_COLLATE flag in the Flags member indicates
                // whether the user wants to print them collated.
                // Due to a Windows OS Bug 558734, we don't need to consider Windows XP and before
                if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0)
                {
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        PrinterSettings.Copies  = (short)(data.nCopies);
                        PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
                    }
                }

                // We should return true only if the user pressed the "Print" button while dismissing the dialog.
                // Please refer to VsW: 403124 for more details.
                return(data.dwResultAction == NativeMethods.PD_RESULT_PRINT);
            }
            finally {
                if (data.hDevMode != IntPtr.Zero)
                {
                    UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                }
                if (data.hDevNames != IntPtr.Zero)
                {
                    UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
                }
                if (data.pageRanges != IntPtr.Zero)
                {
                    UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.pageRanges));
                }
            }
        }
예제 #14
0
        // VSWhidbey 93449: Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods
        // are required for showing the print dialog on Win2k and newer OS'.
        private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data)
        {
            data.Flags         = GetFlags();
            data.nCopies       = (short)PrinterSettings.Copies;
            data.hwndOwner     = hwndOwner;
            data.lpfnPrintHook = hookProcPtr;

            IntSecurity.AllPrintingAndUnmanagedCode.Assert();

            try {
                if (PageSettings == null)
                {
                    data.hDevMode = PrinterSettings.GetHdevmode();
                }
                else
                {
                    data.hDevMode = PrinterSettings.GetHdevmode(PageSettings);
                }

                data.hDevNames = PrinterSettings.GetHdevnames();
            }
            catch (InvalidPrinterException) {
                data.hDevMode  = IntPtr.Zero;
                data.hDevNames = IntPtr.Zero;
                // Leave those fields null; Windows will fill them in
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                // Windows doesn't like it if page numbers are invalid
                if (AllowSomePages)
                {
                    if (PrinterSettings.FromPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.FromPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.MinimumPage ||
                        PrinterSettings.ToPage > PrinterSettings.MaximumPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "ToPage"));
                    }
                    if (PrinterSettings.ToPage < PrinterSettings.FromPage)
                    {
                        throw new ArgumentException(SR.GetString(SR.PDpageOutOfRange, "FromPage"));
                    }

                    data.nFromPage = (short)PrinterSettings.FromPage;
                    data.nToPage   = (short)PrinterSettings.ToPage;
                    data.nMinPage  = (short)PrinterSettings.MinimumPage;
                    data.nMaxPage  = (short)PrinterSettings.MaximumPage;
                }

                if (!UnsafeNativeMethods.PrintDlg(data))
                {
                    return(false);
                }

                IntSecurity.AllPrintingAndUnmanagedCode.Assert();
                try {
                    UpdatePrinterSettings(data.hDevMode, data.hDevNames, data.nCopies, data.Flags, settings, PageSettings);
                }
                finally {
                    CodeAccessPermission.RevertAssert();
                }
                PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0);
                PrinterSettings.PrintToFile = PrintToFile;

                if (AllowSomePages)
                {
                    PrinterSettings.FromPage = data.nFromPage;
                    PrinterSettings.ToPage   = data.nToPage;
                }

                // Fix Dev10 #575399, when the flag PD_USEDEVMODECOPIESANDCOLLATE is not set,
                // PRINTDLG.nCopies or PRINTDLG.nCopies indicates the number of copies the user wants
                // to print, and the PD_COLLATE flag in the Flags member indicates
                // whether the user wants to print them collated.
                // Due to a Windows OS Bug 558734, we don't need to consider Windows XP and before
                if ((data.Flags & NativeMethods.PD_USEDEVMODECOPIESANDCOLLATE) == 0)
                {
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        PrinterSettings.Copies  = data.nCopies;
                        PrinterSettings.Collate = ((data.Flags & NativeMethods.PD_COLLATE) == NativeMethods.PD_COLLATE);
                    }
                }

                return(true);
            }
            finally {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
        private Bitmap GetBitmap(int index)
        {
            if ((index < 0) || (index >= this.Images.Count))
            {
                throw new ArgumentOutOfRangeException("index", System.Windows.Forms.SR.GetString("InvalidArgument", new object[] { "index", index.ToString(CultureInfo.CurrentCulture) }));
            }
            Bitmap image = null;

            if (this.ColorDepth == System.Windows.Forms.ColorDepth.Depth32Bit)
            {
                System.Windows.Forms.NativeMethods.IMAGEINFO pImageInfo = new System.Windows.Forms.NativeMethods.IMAGEINFO();
                if (System.Windows.Forms.SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, pImageInfo))
                {
                    Bitmap     bitmap2    = null;
                    BitmapData bmpData    = null;
                    BitmapData targetData = null;
                    System.Windows.Forms.IntSecurity.ObjectFromWin32Handle.Assert();
                    try
                    {
                        bitmap2 = Image.FromHbitmap(pImageInfo.hbmImage);
                        bmpData = bitmap2.LockBits(new Rectangle(pImageInfo.rcImage_left, pImageInfo.rcImage_top, pImageInfo.rcImage_right - pImageInfo.rcImage_left, pImageInfo.rcImage_bottom - pImageInfo.rcImage_top), ImageLockMode.ReadOnly, bitmap2.PixelFormat);
                        int stride = bmpData.Stride;
                        int height = this.imageSize.Height;
                        if (BitmapHasAlpha(bmpData))
                        {
                            image      = new Bitmap(this.imageSize.Width, this.imageSize.Height, PixelFormat.Format32bppArgb);
                            targetData = image.LockBits(new Rectangle(0, 0, this.imageSize.Width, this.imageSize.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                            this.CopyBitmapData(bmpData, targetData);
                        }
                    }
                    finally
                    {
                        CodeAccessPermission.RevertAssert();
                        if (bitmap2 != null)
                        {
                            if (bmpData != null)
                            {
                                bitmap2.UnlockBits(bmpData);
                            }
                            bitmap2.Dispose();
                        }
                        if ((image != null) && (targetData != null))
                        {
                            image.UnlockBits(targetData);
                        }
                    }
                }
            }
            if (image == null)
            {
                image = new Bitmap(this.imageSize.Width, this.imageSize.Height);
                using (Graphics graphics = Graphics.FromImage(image))
                {
                    IntPtr hdc = graphics.GetHdc();
                    try
                    {
                        System.Windows.Forms.SafeNativeMethods.ImageList_DrawEx(new HandleRef(this, this.Handle), index, new HandleRef(graphics, hdc), 0, 0, this.imageSize.Width, this.imageSize.Height, -1, -1, 1);
                    }
                    finally
                    {
                        graphics.ReleaseHdcInternal(hdc);
                    }
                }
            }
            image.MakeTransparent(fakeTransparencyColor);
            return(image);
        }
예제 #16
0
        public override SecurityElement ToXml()
        {
            SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement(this, "System.Security.Permissions.GacIdentityPermission");

            return(securityElement);
        }
예제 #17
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override void FromXml(SecurityElement esd)
        {
            CodeAccessPermission.ValidateElement(esd, this);
            String et;

            if (XMLUtil.IsUnrestricted(esd))
            {
                m_unrestricted = true;
                return;
            }


            m_unrestricted = false;

            et = esd.Attribute("Read");
            if (et != null)
            {
                m_read = new FileIOAccess(et);
            }
            else
            {
                m_read = null;
            }

            et = esd.Attribute("Write");
            if (et != null)
            {
                m_write = new FileIOAccess(et);
            }
            else
            {
                m_write = null;
            }

            et = esd.Attribute("Append");
            if (et != null)
            {
                m_append = new FileIOAccess(et);
            }
            else
            {
                m_append = null;
            }

            et = esd.Attribute("PathDiscovery");
            if (et != null)
            {
                m_pathDiscovery = new FileIOAccess(et);
                m_pathDiscovery.PathDiscovery = true;
            }
            else
            {
                m_pathDiscovery = null;
            }

            et = esd.Attribute("ViewAcl");
            if (et != null)
            {
                m_viewAcl = new FileIOAccess(et);
            }
            else
            {
                m_viewAcl = null;
            }

            et = esd.Attribute("ChangeAcl");
            if (et != null)
            {
                m_changeAcl = new FileIOAccess(et);
            }
            else
            {
                m_changeAcl = null;
            }
        }
예제 #18
0
 public override void FromXml(SecurityElement securityElement)
 {
     CodeAccessPermission.ValidateElement(securityElement, this);
 }
예제 #19
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);
        }
예제 #20
0
        private void StartRaisingEvents()
        {
            //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
            if (this.disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            try {
                new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                {
                    throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // If we're called when "Initializing" is true, set enabled to true
            if (IsSuspended())
            {
                enabled = true;
                return;
            }

            if (!readGranted)
            {
                string fullPath;
                // Consider asserting path discovery permission here.
                fullPath = System.IO.Path.GetFullPath(directory);

                FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, fullPath);
                permission.Demand();
                readGranted = true;
            }


            // If we're attached, don't do anything.
            if (!IsHandleInvalid)
            {
                return;
            }

            // Create handle to directory being monitored
            directoryHandle = NativeMethods.CreateFile(directory,                               // Directory name
                                                       UnsafeNativeMethods.FILE_LIST_DIRECTORY, // access (read-write) mode
                                                       UnsafeNativeMethods.FILE_SHARE_READ |
                                                       UnsafeNativeMethods.FILE_SHARE_DELETE |
                                                       UnsafeNativeMethods.FILE_SHARE_WRITE,     // share mode
                                                       null,                                     // security descriptor
                                                       UnsafeNativeMethods.OPEN_EXISTING,        // how to create
                                                       UnsafeNativeMethods.FILE_FLAG_BACKUP_SEMANTICS |
                                                       UnsafeNativeMethods.FILE_FLAG_OVERLAPPED, // file attributes
                                                       new SafeFileHandle(IntPtr.Zero, false)    // file with attributes to copy
                                                       );

            if (IsHandleInvalid)
            {
                throw new FileNotFoundException(SR.GetString(SR.FSW_IOError, directory));
            }

            stopListening = false;
            // Start ignoring all events that were initiated before this.
            Interlocked.Increment(ref currentSession);

            // Attach handle to thread pool

            //SECREVIEW: At this point at least FileIOPermission has already been demanded.
            SecurityPermission secPermission = new SecurityPermission(PermissionState.Unrestricted);

            secPermission.Assert();
            try {
                ThreadPool.BindHandle(directoryHandle);
            }
            finally {
                SecurityPermission.RevertAssert();
            }
            enabled = true;

            // Setup IO completion port
            Monitor(null);
        }
예제 #21
0
        internal DefaultProxySectionInternal(DefaultProxySection section)
        {
            // If enabled is false, skip everything.
            if (!section.Enabled)
            {
                return;
            }

            // If nothing else is set, use the system default.
            if (section.Proxy.AutoDetect == ProxyElement.AutoDetectValues.Unspecified &&
                section.Proxy.ScriptLocation == null &&
                String.IsNullOrEmpty(section.Module.Type) &&
                section.Proxy.UseSystemDefault != ProxyElement.UseSystemDefaultValues.True &&
                section.Proxy.ProxyAddress == null &&
                section.Proxy.BypassOnLocal == ProxyElement.BypassOnLocalValues.Unspecified &&
                section.BypassList.Count == 0)
            {
                // Old-style indication to turn off the proxy.
                if (section.Proxy.UseSystemDefault == ProxyElement.UseSystemDefaultValues.False)
                {
                    this.webProxy = new EmptyWebProxy();

                    // Intentionally ignoring UseDefaultCredentials in this case.
                    return;
                }

                // Suspend impersonation.
                try {
                    new SecurityPermission(SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.UnmanagedCode).Assert();
#if !FEATURE_PAL
                    using (WindowsIdentity.Impersonate(IntPtr.Zero))
#endif // !FEATURE_PAL
                    {
                        CodeAccessPermission.RevertAssert();
                        this.webProxy = new WebRequest.WebProxyWrapper(new WebProxy(true));
                    }
                } catch {
                    throw;
                }
            }
            else
            {
                // First, check out if we are using a different module type
                if (!String.IsNullOrEmpty(section.Module.Type))
                {
                    Type theType = Type.GetType(section.Module.Type, true, true);

                    if ((theType.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public)
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.net_config_proxy_module_not_public));
                    }

                    // verify that its of the proper type of IWebProxy
                    if (!typeof(IWebProxy).IsAssignableFrom(theType))
                    {
                        throw new InvalidCastException(SR.GetString(SR.net_invalid_cast,
                                                                    theType.FullName,
                                                                    "IWebProxy"));
                    }
                    this.webProxy = (IWebProxy)Activator.CreateInstance(
                        theType,
                        BindingFlags.CreateInstance
                        | BindingFlags.Instance
                        | BindingFlags.NonPublic
                        | BindingFlags.Public,
                        null,                      // Binder
                        new object[0],             // no arguments
                        CultureInfo.InvariantCulture
                        );
                }
                else if (section.Proxy.UseSystemDefault == ProxyElement.UseSystemDefaultValues.True &&
                         section.Proxy.AutoDetect == ProxyElement.AutoDetectValues.Unspecified &&
                         section.Proxy.ScriptLocation == null)
                {
                    // Suspend impersonation.  This setting is deprecated but required for Everett compat.
                    try {
                        new SecurityPermission(SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.UnmanagedCode).Assert();
#if !FEATURE_PAL
                        using (WindowsIdentity.Impersonate(IntPtr.Zero))
#endif // !FEATURE_PAL
                        {
                            CodeAccessPermission.RevertAssert();
                            this.webProxy = new WebProxy(false);
                        }
                    } catch {
                        throw;
                    }
                }
                else
                {
                    this.webProxy = new WebProxy();
                }

                WebProxy tempProxy = this.webProxy as WebProxy;

                if (tempProxy != null)
                {
                    if (section.Proxy.AutoDetect != ProxyElement.AutoDetectValues.Unspecified)
                    {
                        tempProxy.AutoDetect = section.Proxy.AutoDetect == ProxyElement.AutoDetectValues.True;
                    }
                    if (section.Proxy.ScriptLocation != null)
                    {
                        tempProxy.ScriptLocation = section.Proxy.ScriptLocation;
                    }
                    if (section.Proxy.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
                    {
                        tempProxy.BypassProxyOnLocal = section.Proxy.BypassOnLocal == ProxyElement.BypassOnLocalValues.True;
                    }
                    if (section.Proxy.ProxyAddress != null)
                    {
                        tempProxy.Address = section.Proxy.ProxyAddress;
                    }
                    int bypassListSize = section.BypassList.Count;
                    if (bypassListSize > 0)
                    {
                        string[] bypassList = new string[section.BypassList.Count];
                        for (int index = 0; index < bypassListSize; ++index)
                        {
                            bypassList[index] = section.BypassList[index].Address;
                        }
                        tempProxy.BypassList = bypassList;
                    }

                    // Wrap it if type not explicitly specified in Module.
                    if (section.Module.Type == null)
                    {
                        this.webProxy = new WebRequest.WebProxyWrapper(tempProxy);
                    }
                }
            }

            // Now apply UseDefaultCredentials if there's a proxy.
            if (this.webProxy != null && section.UseDefaultCredentials)
            {
                this.webProxy.Credentials = SystemNetworkCredential.defaultCredential;
            }
        }
예제 #22
0
        // This method doesn't really open the streamName for write.  Instead, using WriteFileContext
        // it opens a stream on a temporary file created in the same directory as streamName.
        //
        // Parameters:
        //  assertPermissions - If true, then we'll assert all required permissions.  Used by ClientSettingsConfigurationHost.
        //                      to allow low-trust apps to use ClientSettingsStore.
        static internal Stream StaticOpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext, bool assertPermissions)
        {
            bool revertAssert = false;

            if (string.IsNullOrEmpty(streamName))
            {
                throw new ConfigurationErrorsException(SR.GetString(SR.Config_no_stream_to_write));
            }

            // Create directory if it does not exist.
            // Ignore errors, allow any failure to come when trying to open the file.
            string dir = Path.GetDirectoryName(streamName);

            try {
                if (!Directory.Exists(dir))
                {
                    //



                    if (assertPermissions)
                    {
                        new FileIOPermission(PermissionState.Unrestricted).Assert();
                        revertAssert = true;
                    }

                    Directory.CreateDirectory(dir);
                }
            }
            catch {
            }
            finally {
                if (revertAssert)
                {
                    CodeAccessPermission.RevertAssert();
                }
            }

            Stream           stream;
            WriteFileContext writeFileContext = null;

            revertAssert = false;

            if (assertPermissions)
            {
                // If we're asked to assert permission, we will assert allAccess on the directory (instead of just the file).
                // We need to assert for the whole directory because WriteFileContext will call TempFileCollection.AddExtension,
                // which will generate a temporary file and make a AllAccess Demand on that file.
                // Since we don't know the name of the temporary file right now, we need to assert for the whole dir.
                new FileIOPermission(FileIOPermissionAccess.AllAccess, dir).Assert();
                revertAssert = true;
            }

            try {
                writeFileContext = new WriteFileContext(streamName, templateStreamName);

                if (File.Exists(streamName))
                {
                    FileInfo       fi    = new FileInfo(streamName);
                    FileAttributes attrs = fi.Attributes;
                    if ((int)(attrs & InvalidAttributesForWrite) != 0)
                    {
                        throw new IOException(SR.GetString(SR.Config_invalid_attributes_for_write, streamName));
                    }
                }

                try {
                    stream = new FileStream(writeFileContext.TempNewFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                }
                // Wrap all exceptions so that we provide a meaningful filename - otherwise the end user
                // will just see the temporary file name, which is meaningless.
                catch (Exception e) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_write_failed, streamName), e);
                }
            }
            catch {
                if (writeFileContext != null)
                {
                    writeFileContext.Complete(streamName, false);
                }
                throw;
            }
            finally {
                if (revertAssert)
                {
                    CodeAccessPermission.RevertAssert();
                }
            }

            writeContext = writeFileContext;
            return(stream);
        }
예제 #23
0
        internal Type FastBindToType(string assemblyName, string typeName)
        {
            Type          typeFromAssembly = null;
            TypeNAssembly cachedValue      = (TypeNAssembly)this.typeCache.GetCachedValue(typeName);

            if ((cachedValue == null) || (cachedValue.assemblyName != assemblyName))
            {
                Assembly assm = null;
                if (this.bSimpleAssembly)
                {
                    try
                    {
                        sfileIOPermission.Assert();
                        try
                        {
                            assm = ResolveSimpleAssemblyName(new AssemblyName(assemblyName));
                        }
                        finally
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                    }
                    catch (Exception)
                    {
                    }
                    if (assm == null)
                    {
                        return(null);
                    }
                    GetSimplyNamedTypeFromAssembly(assm, typeName, ref typeFromAssembly);
                }
                else
                {
                    try
                    {
                        sfileIOPermission.Assert();
                        try
                        {
                            assm = Assembly.Load(assemblyName);
                        }
                        finally
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                    }
                    catch (Exception)
                    {
                    }
                    if (assm == null)
                    {
                        return(null);
                    }
                    typeFromAssembly = FormatterServices.GetTypeFromAssembly(assm, typeName);
                }
                if (typeFromAssembly == null)
                {
                    return(null);
                }
                CheckTypeForwardedTo(assm, typeFromAssembly.Assembly, typeFromAssembly);
                cachedValue = new TypeNAssembly {
                    type         = typeFromAssembly,
                    assemblyName = assemblyName
                };
                this.typeCache.SetCachedValue(cachedValue);
            }
            return(cachedValue.type);
        }
예제 #24
0
        private static Uri Resolve(string partialUri)
        {
            Uri uri = null;

            if (!string.IsNullOrEmpty(partialUri))
            {
                try
                {
                    uri = new Uri(partialUri);
                }
                catch (UriFormatException)
                {
                }
                catch (ArgumentNullException)
                {
                }
            }
            if ((uri != null) && (uri.Scheme == "file"))
            {
                string localPath = System.Windows.Forms.NativeMethods.GetLocalPath(partialUri);
                new FileIOPermission(FileIOPermissionAccess.Read, localPath).Assert();
                try
                {
                    if (!System.IO.File.Exists(localPath))
                    {
                        uri = null;
                    }
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }
            if (uri == null)
            {
                try
                {
                    uri = new Uri(new Uri(AppDomain.CurrentDomain.SetupInformation.ApplicationBase), partialUri);
                }
                catch (UriFormatException)
                {
                }
                catch (ArgumentNullException)
                {
                }
                if ((uri == null) || !(uri.Scheme == "file"))
                {
                    return(uri);
                }
                string path = uri.LocalPath + uri.Fragment;
                new FileIOPermission(FileIOPermissionAccess.Read, path).Assert();
                try
                {
                    if (!System.IO.File.Exists(path))
                    {
                        uri = null;
                    }
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }
            return(uri);
        }
예제 #25
0
        public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly)
        {
            if (savedLicenseKeys == null || savedLicenseKeys[type.AssemblyQualifiedName] == null)
            {
                Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "savedLicenseKey is null or doesnt contain our type");
                if (savedLicenseKeys == null)
                {
                    savedLicenseKeys = new Hashtable();
                }

                Uri licenseFile = null;

                if (resourceAssembly == null)
                {
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "resourceAssembly is null");
                    string rawFile = (string)AppDomain.CurrentDomain.SetupInformation.LicenseFile;
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "rawfile: " + rawFile);
                    string codeBase;

#if !DISABLE_CAS_USE
                    // FileIOPermission is required for ApplicationBase in URL-hosted domains
                    FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                    perm.Assert();
                    try {
                        codeBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
#else
                    codeBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
#endif
                    if (rawFile != null && codeBase != null)
                    {
                        licenseFile = new Uri(new Uri(codeBase), rawFile);
                    }
                }

                if (licenseFile == null)
                {
                    if (resourceAssembly == null)
                    {
                        resourceAssembly = Assembly.GetEntryAssembly();
                    }

                    if (resourceAssembly == null)
                    {
                        Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "resourceAssembly is null");
                        // If Assembly.EntryAssembly returns null, then we will
                        // try everything!
                        //
                        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            // Though, I could not repro this, we seem to be hitting an AssemblyBuilder
                            // when walking through all the assemblies in the current app domain. This throws an
                            // exception on Assembly.CodeBase and we bail out. Catching exceptions here is not a
                            // bad thing.
                            if (asm.IsDynamic)
                            {
                                continue;
                            }

                            // file://fullpath/foo.exe
                            //
                            string fileName;
#if !DISABLE_CAS_USE
                            FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                            perm.Assert();
                            try
                            {
                                fileName = GetLocalPath(asm.EscapedCodeBase);
                                fileName = new FileInfo(fileName).Name;
                            }
                            finally
                            {
                                CodeAccessPermission.RevertAssert();
                            }
#else
                            fileName = GetLocalPath(asm.EscapedCodeBase);
                            fileName = new FileInfo(fileName).Name;
#endif

                            Stream s = asm.GetManifestResourceStream(fileName + ".licenses");
                            if (s == null)
                            {
                                //Since the casing may be different depending on how the assembly was loaded,
                                //we'll do a case insensitive lookup for this manifest resource stream...
                                s = CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses");
                            }

                            if (s != null)
                            {
                                DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
                                break;
                            }
                        }
                    }
                    else if (!resourceAssembly.IsDynamic)  // EscapedCodeBase won't be supported by emitted assemblies anyway
                    {
                        Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "resourceAssembly is not null");
                        string           fileName;
                        FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                        perm.Assert();
                        try
                        {
                            fileName = GetLocalPath(resourceAssembly.EscapedCodeBase);
                        }
                        finally
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                        fileName = Path.GetFileName(fileName); // we don't want to use FileInfo here... it requests FileIOPermission that we
                        // might now have... see VSWhidbey 527758
                        string licResourceName = fileName + ".licenses";
                        // first try the filename
                        Stream s = resourceAssembly.GetManifestResourceStream(licResourceName);
                        if (s == null)
                        {
                            string      resolvedName      = null;
                            CompareInfo comparer          = CultureInfo.InvariantCulture.CompareInfo;
                            string      shortAssemblyName = resourceAssembly.GetName().Name;
                            //  if the assembly has been renamed, we try our best to find a good match in the available resources
                            // by looking at the assembly name (which doesn't change even after a file rename) + ".exe.licenses" or + ".dll.licenses"
                            foreach (String existingName in resourceAssembly.GetManifestResourceNames())
                            {
                                if (comparer.Compare(existingName, licResourceName, CompareOptions.IgnoreCase) == 0 ||
                                    comparer.Compare(existingName, shortAssemblyName + ".exe.licenses", CompareOptions.IgnoreCase) == 0 ||
                                    comparer.Compare(existingName, shortAssemblyName + ".dll.licenses", CompareOptions.IgnoreCase) == 0)
                                {
                                    resolvedName = existingName;
                                    break;
                                }
                            }
                            if (resolvedName != null)
                            {
                                s = resourceAssembly.GetManifestResourceStream(resolvedName);
                            }
                        }
                        if (s != null)
                        {
                            DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
                        }
                    }
                }


                if (licenseFile != null)
                {
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "licenseFile: " + licenseFile.ToString());
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "opening licenses file over URI " + licenseFile.ToString());
                    Stream s = OpenRead(licenseFile);
                    if (s != null)
                    {
                        string[] segments    = licenseFile.Segments;
                        string   licFileName = segments[segments.Length - 1];
                        string   key         = licFileName.Substring(0, licFileName.LastIndexOf("."));
                        DesigntimeLicenseContextSerializer.Deserialize(s, key.ToUpper(CultureInfo.InvariantCulture), this);
                    }
                }
            }
            Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "returning : " + (string)savedLicenseKeys[type.AssemblyQualifiedName]);
            return((string)savedLicenseKeys[type.AssemblyQualifiedName]);
        }
예제 #26
0
        internal CompilerResults Compile(CompilerParameters parameters, IEnumerable <SyntaxTree> syntaxTrees, TextWriter outputWriter)
        {
            var compilerResults = new CompilerResults(parameters.TempFiles)
            {
                NativeCompilerReturnValue = 1
            };

            var commonCompilationArguments = this.ArgumentsFromParametersNoThrow(parameters, outputWriter);

            if (commonCompilationArguments == null)
            {
                return(compilerResults);
            }
            if (commonCompilationArguments.CmdArguments.DisplayLogo)
            {
                this.PrintLogo(outputWriter);
            }
            if (commonCompilationArguments.CmdArguments.DisplayHelp)
            {
                this.PrintHelp(outputWriter);
                return(null);
            }
            if (this.ErrorInDiagnostics(commonCompilationArguments.CmdArguments.Errors, compilerResults, outputWriter))
            {
                return(compilerResults);
            }
            Compilation compilation = this.CreateCompilation(commonCompilationArguments, syntaxTrees, outputWriter);

            if (compilation == null ||
                this.ErrorInDiagnostics(compilation.GetParseDiagnostics(default(CancellationToken)), compilerResults, outputWriter) ||
                this.ErrorInDiagnostics(compilation.GetDeclarationDiagnostics(default(CancellationToken)), compilerResults, outputWriter))
            {
                return(compilerResults);
            }
            SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);

            securityPermission.Assert();
            try
            {
                compilerResults.Evidence = parameters.Evidence;
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            bool         flag         = false;
            MemoryStream outputStream = new MemoryStream();
            MemoryStream pdbStream    = null;

            if (commonCompilationArguments.FinalPdbFilePath != null)
            {
                pdbStream = new MemoryStream();
            }
            CompilerResults result;

            using (outputStream)
            {
                using (pdbStream)
                {
                    try
                    {
                        FileStream documentationStream = null;
                        string     documentationPath   = commonCompilationArguments.CmdArguments.DocumentationPath;
                        if (documentationPath != null)
                        {
                            documentationStream = OpenFile(documentationPath, outputWriter, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read | FileShare.Write | FileShare.Delete);
                            if (documentationStream == null)
                            {
                                result = compilerResults;
                                return(result);
                            }
                            documentationStream.SetLength(0L);
                        }
                        Stream win32resourceFileStream = null;
                        if (!string.IsNullOrWhiteSpace(commonCompilationArguments.Win32ResourceFile))
                        {
                            win32resourceFileStream = OpenFile(commonCompilationArguments.Win32ResourceFile, outputWriter, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                        }
                        EmitResult emitResult;
                        using (win32resourceFileStream)
                        {
                            using (documentationStream)
                            {
                                //// Obsolete
                                //emitResult = compilation.Emit(outputStream,
                                //    commonCompilationArguments.OutputFileName,
                                //    commonCompilationArguments.FinalPdbFilePath,
                                //    pdbStream, documentationStream, default(CancellationToken),
                                //    win32resourceFileStream, commonCompilationArguments.CmdArguments.ManifestResources);

                                //var emitOptions = new EmitOptions();

                                emitResult = compilation.Emit(outputStream,
                                                              pdbStream,
                                                              null,
                                                              win32resourceFileStream,
                                                              commonCompilationArguments.CmdArguments.ManifestResources,
                                                              null,
                                                              null);
                            }
                        }
                        if (this.ErrorInDiagnostics(emitResult.Diagnostics, compilerResults, outputWriter))
                        {
                            result = compilerResults;
                        }
                        else
                        {
                            if (!parameters.GenerateInMemory)
                            {
                                if (!CommonCompiler.WriteMemoryStreamToFile(outputStream, commonCompilationArguments.FinalOutputPath, outputWriter))
                                {
                                    flag   = true;
                                    result = compilerResults;
                                    return(result);
                                }
                                if (commonCompilationArguments.FinalPdbFilePath != null && !CommonCompiler.WriteMemoryStreamToFile(pdbStream, commonCompilationArguments.FinalPdbFilePath, outputWriter))
                                {
                                    flag   = true;
                                    result = compilerResults;
                                    return(result);
                                }
                                compilerResults.PathToAssembly = parameters.OutputAssembly;
                            }
                            else
                            {
                                byte[] rawAssembly    = outputStream.ToArray();
                                byte[] rawSymbolStore = null;
                                if (pdbStream != null)
                                {
                                    try
                                    {
                                        rawSymbolStore = pdbStream.ToArray();
                                    }
                                    catch
                                    {
                                    }
                                }
                                SecurityPermission securityPermission2 = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
                                securityPermission2.Assert();
                                try
                                {
                                    compilerResults.CompiledAssembly = Assembly.Load(rawAssembly, rawSymbolStore, parameters.Evidence);
                                }
                                finally
                                {
                                    CodeAccessPermission.RevertAssert();
                                }
                                compilerResults.CompiledAssembly = Assembly.Load(rawAssembly, rawSymbolStore);
                            }
                            compilerResults.NativeCompilerReturnValue = 0;
                            result = compilerResults;
                        }
                    }
                    finally
                    {
                        if (flag)
                        {
                            if (commonCompilationArguments.FinalOutputPath != null)
                            {
                                CommonCompiler.TryDeleteFile(commonCompilationArguments.FinalOutputPath);
                            }
                            if (commonCompilationArguments.FinalPdbFilePath != null)
                            {
                                CommonCompiler.TryDeleteFile(commonCompilationArguments.FinalPdbFilePath);
                            }
                        }
                    }
                }
            }
            return(result);
        }
예제 #27
0
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        {
            INVOCATION_FLAGS invocationFlags = InvocationFlags;

            // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context
            RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle;

            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
            {
                ThrowNoInvokeException();
            }

#if FEATURE_APPX
            if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
            {
                StackCrawlMark  stackMark = StackCrawlMark.LookForMyCaller;
                RuntimeAssembly caller    = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
                if (caller != null && !caller.IsSafeForReflection())
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
                }
            }
#endif

#if !FEATURE_CORECLR
            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0)
            {
                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
                {
                    CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
                }
                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
                {
                    RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE));
                }
                if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0)
                {
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                }
            }
#endif // !FEATURE_CORECLR

            // get the signature
            Signature sig = Signature;

            int formalCount = sig.Arguments.Length;
            int actualCount = (parameters != null) ? parameters.Length : 0;
            if (formalCount != actualCount)
            {
                throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
            }

            // We don't need to explicitly invoke the class constructor here,
            // JIT/NGen will insert the call to .cctor in the instance ctor.

            // if we are here we passed all the previous checks. Time to look at the arguments
            if (actualCount > 0)
            {
                Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
                Object   retValue  = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
                // copy out. This should be made only if ByRef are present.
                for (int index = 0; index < arguments.Length; index++)
                {
                    parameters[index] = arguments[index];
                }
                return(retValue);
            }
            return(RuntimeMethodHandle.InvokeMethod(null, null, sig, true));
        }
        internal static Type GetBrowserCapabilitiesType()
        {
            //Need to assert here to check directories and files
            InternalSecurityPermissions.Unrestricted.Assert();

            BuildResult result = null;

            try {
                // Try the cache first, and if it's not there, compile it
                result = BuildManager.GetBuildResultFromCache(browerCapabilitiesCacheKey);
                if (result == null)
                {
                    DateTime utcStart = DateTime.UtcNow;

                    VirtualDirectory directory = AppBrowsersVirtualDir.GetDirectory();

                    // first try if app browser dir exists
                    string physicalDir = HostingEnvironment.MapPathInternal(AppBrowsersVirtualDir);

                    /* DevDivBugs 173531
                     * For the App_Browsers scenario, we need to cache the generated browser caps processing
                     * code. We need to add path dependency on all files so that changes to them will
                     * invalidate the cache entry and cause recompilation. */
                    if (directory != null && Directory.Exists(physicalDir))
                    {
                        ArrayList browserFileList             = new ArrayList();
                        ArrayList browserFileDependenciesList = new ArrayList();
                        bool      hasCustomCaps = AddBrowserFilesToList(directory, browserFileList, false);
                        if (hasCustomCaps)
                        {
                            AddBrowserFilesToList(directory, browserFileDependenciesList, true);
                        }
                        else
                        {
                            browserFileDependenciesList = browserFileList;
                        }

                        if (browserFileDependenciesList.Count > 0)
                        {
                            ApplicationBrowserCapabilitiesBuildProvider buildProvider = new ApplicationBrowserCapabilitiesBuildProvider();
                            foreach (string virtualPath in browserFileList)
                            {
                                buildProvider.AddFile(virtualPath);
                            }

                            BuildProvidersCompiler bpc = new BuildProvidersCompiler(null /*configPath*/,
                                                                                    BuildManager.GenerateRandomAssemblyName(BuildManager.AppBrowserCapAssemblyNamePrefix));

                            bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));
                            CompilerResults results  = bpc.PerformBuild();
                            Assembly        assembly = results.CompiledAssembly;
                            // Get the type we want from the assembly
                            Type t = assembly.GetType(
                                BaseCodeDomTreeGenerator.defaultNamespace + "." + ApplicationBrowserCapabilitiesCodeGenerator.FactoryTypeName);
                            // Cache it for next time
                            result             = new BuildResultCompiledType(t);
                            result.VirtualPath = AppBrowsersVirtualDir;
                            result.AddVirtualPathDependencies(browserFileDependenciesList);

                            BuildManager.CacheBuildResult(browerCapabilitiesCacheKey, result, utcStart);
                        }
                    }
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // Simply return the global factory type.
            if (result == null)
            {
                return(_browserCapabilitiesFactoryBaseType);
            }

            // Return the compiled type
            return(((BuildResultCompiledType)result).ResultType);
        }
 /// <summary>Initializes a new instance of the <see cref="T:System.Security.Permissions.StrongNameIdentityPermission" /> class with the specified <see cref="T:System.Security.Permissions.PermissionState" />.</summary>
 /// <param name="state">One of the <see cref="T:System.Security.Permissions.PermissionState" /> values. </param>
 /// <exception cref="T:System.ArgumentException">The <paramref name="state" /> parameter is not a valid value of <see cref="T:System.Security.Permissions.PermissionState" />. </exception>
 public StrongNameIdentityPermission(PermissionState state)
 {
     this._state = CodeAccessPermission.CheckPermissionState(state, true);
     this._list  = new ArrayList();
     this._list.Add(StrongNameIdentityPermission.SNIP.CreateDefault());
 }
예제 #30
0
 private void OnCopy(object sender, ExecutedRoutedEventArgs e)
 {
     if (this.HasSelection && this._selectionRect.Width > 0.0 && this._selectionRect.Height > 0.0)
     {
         string text = this.GetText();
         object obj  = null;
         bool   flag = false;
         if (this._scope is DocumentGrid && ((DocumentGrid)this._scope).DocumentViewerOwner is DocumentApplicationDocumentViewer)
         {
             if (!e.UserInitiated && !this.HasRubberBandCopyPermissions())
             {
                 return;
             }
             flag = true;
         }
         else
         {
             flag = this.HasRubberBandCopyPermissions();
         }
         if (flag)
         {
             obj = SystemDrawingHelper.GetBitmapFromBitmapSource(this.GetImage());
         }
         new UIPermission(UIPermissionClipboard.AllClipboard).Assert();
         IDataObject dataObject;
         try
         {
             dataObject = new DataObject();
             dataObject.SetData(DataFormats.Text, text, true);
             dataObject.SetData(DataFormats.UnicodeText, text, true);
             if (obj != null)
             {
                 dataObject.SetData(DataFormats.Bitmap, obj, true);
             }
         }
         finally
         {
             CodeAccessPermission.RevertAssert();
         }
         PermissionSet permissionSet = new PermissionSet(PermissionState.None);
         permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
         permissionSet.AddPermission(new UIPermission(UIPermissionClipboard.AllClipboard));
         permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
         if (flag)
         {
             CodeAccessPermission perm = SecurityHelper.CreateMediaAccessPermission(null);
             permissionSet.AddPermission(perm);
         }
         permissionSet.Assert();
         try
         {
             Clipboard.SetDataObject(dataObject, true);
         }
         catch (ExternalException)
         {
         }
         finally
         {
             CodeAccessPermission.RevertAssert();
         }
     }
 }