private void FillSigningKey(SecurityTokenServiceDescriptor sts)
        {
            KeyDescriptor signingKey = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            sts.Keys.Add(signingKey);
        }
        private KeyDescriptor GetSigningKeyDescriptor()
        {
            var certificate = _options.SigningCertificate;

            var clause = new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>();
            var key = new KeyDescriptor(new SecurityKeyIdentifier(clause));
            key.Use = KeyType.Signing;

            return key;
        }
Esempio n. 3
0
        /// <summary>
        /// Generate a sample MetadataBase.
        /// </summary>
        /// <remarks>
        /// In a production system this would be generated from the STS configuration.
        /// </remarks>
        public static MetadataBase GetFederationMetadata()
        {
            string endpointId = "http://localhost:61754/";
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(endpointId);

            // Define the signing key
            string signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);
            metadata.SigningCredentials = new X509SigningCredentials(cert);

            // Create role descriptor for security token service
            SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
            stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
            metadata.RoleDescriptors.Add(stsRole);

            // Add a contact name
            ContactPerson person = new ContactPerson(ContactType.Administrative);
            person.GivenName = "contactName";
            stsRole.Contacts.Add(person);

            // Include key identifier for signing key in metadata
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
            SecurityKeyIdentifier ski = new SecurityKeyIdentifier(clause);
            KeyDescriptor signingKey = new KeyDescriptor(ski);
            signingKey.Use = KeyType.Signing;
            stsRole.Keys.Add(signingKey);

            // Add endpoints
            string activeSTSUrl = "http://localhost:61754/";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                                   null,
                                                                   null, GetMetadataReader(activeSTSUrl), null);
            stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

            // Add a collection of offered claims
            // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
            //       In a production system, there would be some common data store that both use
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
            // Add a special claim for the QuoteService
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

            return metadata;
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            EndpointAddress realm = new EndpointAddress(identifier);
            EndpointAddress passiveEndpoint = new EndpointAddress(passiveSignInUrl);

            // Create metadata document for relying party
            EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);
            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream stream = new MemoryStream();
            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return stream.ToArray();
        }
        public override async Task <bool> KeyPress(KeyDescriptor descriptor)
        {
            var result = await base.KeyPress(descriptor);

            if (descriptor.SpecialKey == SpecialKey.Return)
            {
                if (Editor.Options.IndentStyle == MonoDevelop.Ide.Editor.IndentStyle.Virtual)
                {
                    if (Editor.GetLine(Editor.CaretLine).Length == 0)
                    {
                        Editor.CaretColumn = Editor.GetVirtualIndentationColumn(Editor.CaretLine);
                    }
                }
                else
                {
                    DoReSmartIndent();
                }
            }

            return(result);
        }
Esempio n. 6
0
        public async Task TestSemicolon()
        {
            await Simulate(@"class Foo
{
	void Test ()
	{
		Console.WriteLine ()      ;$
	}
}", (content, ext) => {
                ext.KeyPress(KeyDescriptor.FromGtk(Gdk.Key.semicolon, ';', Gdk.ModifierType.None));

                var newText = content.Text;
                Assert.AreEqual(@"class Foo
{
	void Test ()
	{
		Console.WriteLine();
	}
}", newText);
            });
        }
        public override bool KeyPress(KeyDescriptor descriptor)
        {
            if (DebuggingService.ExceptionCaughtMessage != null &&
                !DebuggingService.ExceptionCaughtMessage.IsMinimized &&
                DebuggingService.ExceptionCaughtMessage.File.CanonicalPath == new FilePath(DocumentContext.Name).CanonicalPath)
            {
                if (descriptor.SpecialKey == SpecialKey.Escape)
                {
                    DebuggingService.ExceptionCaughtMessage.ShowMiniButton();
                    return(true);
                }

                if (descriptor.SpecialKey == SpecialKey.Return)
                {
                    DebuggingService.ExceptionCaughtMessage.ShowDialog();
                    return(false);
                }
            }

            return(base.KeyPress(descriptor));
        }
        public XElement GetFederationMetadata(string endPoint, IList <string> claims)
        {
            System.ServiceModel.EndpointAddress item = new System.ServiceModel.EndpointAddress(endPoint + "/_sts/");
            EntityDescriptor entityDescriptor        = new EntityDescriptor(new EntityId(this.TokenIssuerName));
            SecurityTokenServiceDescriptor securityTokenServiceDescriptor = new SecurityTokenServiceDescriptor();

            entityDescriptor.RoleDescriptors.Add(securityTokenServiceDescriptor);
            KeyDescriptor keyDescriptor = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier);

            keyDescriptor.Use = KeyType.Signing;
            securityTokenServiceDescriptor.Keys.Add(keyDescriptor);
            for (int i = 0; i < claims.Count; i++)
            {
                securityTokenServiceDescriptor.ClaimTypesOffered.Add(new DisplayClaim(claims[i], claims[i], string.Empty));
            }

            var endPointReference = new EndpointReference(item.Uri.ToString());

            securityTokenServiceDescriptor.PassiveRequestorEndpoints.Add(endPointReference);
            securityTokenServiceDescriptor.ProtocolsSupported.Add(new System.Uri("http://docs.oasis-open.org/wsfed/federation/200706"));
            securityTokenServiceDescriptor.SecurityTokenServiceEndpoints.Add(endPointReference);
            entityDescriptor.SigningCredentials = base.SigningCredentials;
            MetadataSerializer metadataSerializer = new MetadataSerializer();
            XElement           result             = null;

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                metadataSerializer.WriteMetadata(memoryStream, entityDescriptor);
                memoryStream.Flush();
                memoryStream.Seek(0L, System.IO.SeekOrigin.Begin);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments   = true;
                settings.IgnoreWhitespace = true;
                XmlReader reader = XmlReader.Create(memoryStream);
                result = XElement.Load(reader);
            }


            return(result);
        }
 public override bool KeyPress(KeyDescriptor descriptor)
 {
     if (Editor.Options.IndentStyle == IndentStyle.Smart)
     {
         var newLine = Editor.CaretLine + 1;
         var ret     = base.KeyPress(descriptor);
         if (descriptor.SpecialKey == SpecialKey.Return && Editor.CaretLine == newLine)
         {
             string indent    = GetLineIndent(newLine);
             var    oldIndent = Editor.GetLineIndent(newLine);
             var    seg       = Editor.GetLine(newLine);
             if (oldIndent != indent)
             {
                 using (var undo = Editor.OpenUndoGroup()) {
                     Editor.ReplaceText(seg.Offset, oldIndent.Length, indent);
                 }
             }
         }
         return(ret);
     }
     return(base.KeyPress(descriptor));
 }
Esempio n. 10
0
        public bool CompleteWord(ref KeyActions ka, KeyDescriptor descriptor)
        {
            if (SelectedItemIndex == -1 || completionDataList == null)
            {
                return(false);
            }
            var item = completionDataList [SelectedItemIndex];

            if (item == null)
            {
                return(false);
            }
            IsInCompletion = true;
            try {
                // first close the completion list, then insert the text.
                // this is required because that's the logical event chain, otherwise things could be messed up
                CloseCompletionList();

                /*			var cdItem = (CompletionData)item;
                 *                      cdItem.InsertCompletionText (this, ref ka, closeChar, keyChar, modifier);
                 *                      AddWordToHistory (PartialWord, cdItem.CompletionText);
                 *                      OnWordCompleted (new CodeCompletionContextEventArgs (CompletionWidget, CodeCompletionContext, cdItem.CompletionText));
                 */
                if (item.HasOverloads && declarationviewwindow != null && declarationviewwindow.CurrentOverload >= 0 && declarationviewwindow.CurrentOverload < item.OverloadedData.Count)
                {
                    item.OverloadedData[declarationviewwindow.CurrentOverload].InsertCompletionText(facade, ref ka, descriptor);
                }
                else
                {
                    item.InsertCompletionText(facade, ref ka, descriptor);
                }
                cache.CommitCompletionData(item);
                OnWordCompleted(new CodeCompletionContextEventArgs(CompletionWidget, CodeCompletionContext, item.DisplayText));
            } finally {
                IsInCompletion = false;
                CompletionWindowManager.HideWindow();
            }
            return(true);
        }
 bool ExtensionKeyPress(Gdk.Key key, uint ch, Gdk.ModifierType state)
 {
     isInKeyStroke = true;
     try {
         if (needToAddLastExtension)
         {
             var ext = EditorExtension;
             while (ext.Next != null)
             {
                 ext = ext.Next;
             }
             ext.Next = new LastEditorExtension(this);
             needToAddLastExtension = false;
         }
         return(EditorExtension.KeyPress(KeyDescriptor.FromGtk(key, (char)ch, state)));
     } catch (Exception ex) {
         ReportExtensionError(ex);
     } finally {
         isInKeyStroke = false;
     }
     return(false);
 }
        public async Task TestBug16174_VirtualIndent()
        {
            await Simulate("namespace Foo\n{\n\tpublic class Bar\n\t{\n$\t\tvoid Test()\n\t\t{\n\t\t}\n\t}\n}\n", (content, ext) => {
                var options = new CustomEditorOptions {
                    IndentStyle  = IndentStyle.Virtual,
                    TabsToSpaces = false
                };

                ext.Editor.Options = options;
                EditActions.NewLine(ext.Editor);
                ext.KeyPress(KeyDescriptor.FromGtk(Gdk.Key.Return, '\n', Gdk.ModifierType.None));

                var newText = content.Text;

                var expected = "namespace Foo\n{\n\tpublic class Bar\n\t{\n\n\t\tvoid Test()\n\t\t{\n\t\t}\n\t}\n}\n";
                if (newText != expected)
                {
                    Console.WriteLine(newText);
                }
                Assert.AreEqual(expected, newText);
            });
        }
Esempio n. 13
0
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            PropertyDescriptorCollection ps = base.GetProperties(context, value, attributes);
            ICustomPropertyConverter     s  = value as ICustomPropertyConverter;

            if (s == null)
            {
                throw new InvalidOperationException();
            }
            //keep given properties and add one for each key
            PropertyDescriptor[] props = new PropertyDescriptor[ps.Count + s.GetKeys().Count];
            int i = 0;

            foreach (PropertyDescriptor p in ps)
            {
                props[i++] = p;
            }
            foreach (object key in s.GetKeys())
            {
                //create attributes for s
                ArrayList attrs = new ArrayList();
                attrs.Add(new DescriptionAttribute(s.DescriptionOf(key)));
                attrs.Add(new ReadOnlyAttribute(s.IsReadOnly(key)));
                attrs.Add(new CategoryAttribute(s.CategoryOf(key)));
                attrs.Add(RefreshPropertiesAttribute.All);
                string customEditor = s.CustomEditorOf(key);
                if (customEditor != null)
                {
                    attrs.Add(new EditorAttribute(customEditor, typeof(System.Drawing.Design.UITypeEditor)));
                }
                object v = s.ValueOf(key);
                props[i++] = new KeyDescriptor(s.GetType(), key, s.DisplayNameOf(key), (v == null ? "":v).GetType(),
                                               (Attribute[])attrs.ToArray(typeof(Attribute)),
                                               s.IsDefaultExpanded(key));
            }
            PropertyDescriptorCollection res = new PropertyDescriptorCollection(props);

            return(res);
        }
        public async Task TestCloseBrace()
        {
            await Simulate(@"class Foo
{
	void Test ()
	{
		Console.WriteLine()                   ;
	}$
}", (content, ext) => {
                ext.KeyPress(KeyDescriptor.FromGtk(Gdk.Key.braceright, '}', Gdk.ModifierType.None));

                var newText = content.Text;
                Console.WriteLine(newText);
                Assert.AreEqual(@"class Foo
{
	void Test()
	{
		Console.WriteLine();
	}
}", newText);
            });
        }
Esempio n. 15
0
        public IIndex <IData, IData> OpenXIndex(KeyDescriptor keyDescriptor, RecordDescriptor recordDescriptor, params string[] path)
        {
            var  keyType      = keyDescriptor.DataType;
            bool keySupported = keyType.IsPrimitive || (keyType.IsSlotes && keyType.AreAllTypesPrimitive);

            if (!keySupported)
            {
                throw new NotSupportedException(keyType.ToString());
            }

            var  recordType      = recordDescriptor.DataType;
            bool recordSupported = recordType.IsPrimitive || (recordType.IsSlotes && recordType.AreAllTypesPrimitive);

            if (!recordSupported)
            {
                throw new NotSupportedException(recordType.ToString());
            }

            ILocator locator = Locator.Obtain(StructureType.XINDEX, keyDescriptor, recordDescriptor, path);

            return(new XIndex(this, locator));
        }
        public async Task TestIssue5951()
        {
            using (var data = await Create(@"
using System;

namespace MyLibrary
{
	public class MyClass
	{
		public MyClass()
		{
		}
$
	}
}")) {
                data.Document.Editor.Options = new CustomEditorOptions(data.Document.Editor.Options)
                {
                    IndentStyle = IndentStyle.Smart,
                    RemoveTrailingWhitespaces = false
                };
                var indent = new CSharpTextEditorIndentation();
                indent.Initialize(data.Document.Editor, data.Document);
                indent.KeyPress(KeyDescriptor.FromGtk(Gdk.Key.Return, '\n', Gdk.ModifierType.None));
                CheckOutput(data, @"
using System;

namespace MyLibrary
{
	public class MyClass
	{
		public MyClass()
		{
		}
		$
	}
}", indent);
            }
        }
Esempio n. 17
0
        async Task <string> Test(string input, string type, string member, Gdk.Key key = Gdk.Key.Return)
        {
            string result = null;

            await Setup(input, async testCase => {
                var ext        = testCase.Content.GetContent <CSharpCompletionTextEditorExtension> ();
                var listWindow = new CompletionListWindow();
                var widget     = new TestCompletionWidget(ext.Editor, ext.DocumentContext);
                listWindow.CompletionWidget      = widget;
                listWindow.CodeCompletionContext = widget.CurrentCodeCompletionContext;
                var sm = await ext.DocumentContext.AnalysisDocument.GetSemanticModelAsync();

                var t              = sm.Compilation.GetTypeByMetadataName(type);
                var foundMember    = t.GetMembers().First(m => m.Name == member);
                var data           = new CompletionData(foundMember.Name);
                data.DisplayFlags |= DisplayFlags.NamedArgument;
                KeyActions ka      = KeyActions.Process;
                data.InsertCompletionText(listWindow, ref ka, KeyDescriptor.FromGtk(key, (char)key, Gdk.ModifierType.None));
                result = widget.CompletedWord;
            });

            return(result);
        }
Esempio n. 18
0
        protected override bool ProcessKeyPressEvent(Gtk.KeyPressEventArgs args)
        {
            keyHandled = false;

            keyChar  = (char)args.Event.Key;
            keyValue = args.Event.KeyValue;
            modifier = args.Event.State;
            key      = args.Event.Key;

            if ((args.Event.Key == Gdk.Key.Down || args.Event.Key == Gdk.Key.Up))
            {
                keyChar = '\0';
            }

            if (currentCompletionData != null)
            {
                if ((keyHandled = CompletionWindowManager.PreProcessKeyEvent(KeyDescriptor.FromGtk(key, keyChar, modifier))))
                {
                    return(true);
                }
            }

            return(base.ProcessKeyPressEvent(args));
        }
Esempio n. 19
0
        internal static string Encrypt(this IdentityCoreKeyHandler handler, KeyDescriptor keyDescriptor, string payload)
        {
            string EncryptionKey = keyDescriptor?.SecretKey?.Secret;
            var    signature     = keyDescriptor.KeySignature.Signature;
            var    lastKey       = EncryptionKey.Insert(EncryptionKey.Length, signature);

            byte[] clearBytes = Encoding.Unicode.GetBytes(payload);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(lastKey, new byte[] { 0x64, 0x76, 0x65, 0x64, 0x65, 0x76, 0x79, 0x88, 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    payload = Convert.ToBase64String(ms.ToArray());
                }
            }
            return(payload);
        }
Esempio n. 20
0
        public async Task TestCorrectReindentNextLine()
        {
            await Simulate(@"
class Foo
{
	void Bar ()
	{
		try {
		} catch (Exception e) {$}
	}
}
", (content, ext) => {
                ext.ReindentOnTab();
                EditActions.NewLine(ext.Editor);
                ext.KeyPress(KeyDescriptor.FromGtk((Gdk.Key) '\n', '\n', Gdk.ModifierType.None));

                var newText = content.Text;

                var expected = @"
class Foo
{
	void Bar ()
	{
		try {
		} catch (Exception e) {
		}
	}
}
";
                if (newText != expected)
                {
                    Console.WriteLine(newText);
                }
                Assert.AreEqual(expected, newText);
            });
        }
        public async Task TestBug44747()
        {
            await Simulate(@"class Foo
{
	void Test()
	{
		#$
	}
}", (content, ext) => {
                content.Data.Options = new CustomEditorOptions {
                    IndentStyle = IndentStyle.Virtual
                };
                ext.KeyPress(KeyDescriptor.FromGtk((Gdk.Key) '#', '#', Gdk.ModifierType.None));

                var newText = content.Text;
                Assert.AreEqual(@"class Foo
{
	void Test()
	{
#
	}
}", newText);
            });
        }
        public override bool Handle(TextEditor editor, DocumentContext ctx, KeyDescriptor descriptor)
        {
            char closingBrace;

            if (!IsSupportedOpeningBrace(descriptor.KeyChar, out closingBrace) || !CheckCodeContext(editor, ctx, editor.CaretOffset - 1, descriptor.KeyChar, default(CancellationToken)))
            {
                return(false);
            }

            var session = CreateEditorSession(editor, ctx, editor.CaretOffset, descriptor.KeyChar, default(CancellationToken));

            session.SetEditor(editor);
            if (session == null | !((ICheckPointEditSession)session).CheckOpeningPoint(editor, ctx, default(CancellationToken)))
            {
                return(false);
            }
            using (var undo = editor.OpenUndoGroup()) {
                editor.EnsureCaretIsNotVirtual();
                editor.InsertAtCaret(closingBrace.ToString());
                editor.CaretOffset--;
                editor.StartSession(session);
            }
            return(true);
        }
Esempio n. 23
0
        public virtual Task <KeyActions> InsertCompletionText(CompletionListWindow window, KeyActions ka, KeyDescriptor descriptor)
        {
            var currentWord = GetCurrentWord(window, descriptor);

            window.CompletionWidget.SetCompletionText(window.CodeCompletionContext, currentWord, CompletionText);
            return(Task.FromResult(ka));
        }
        public override bool KeyPress(KeyDescriptor descriptor)
        {
            completionWindowWasVisible   = CompletionWindowManager.IsVisible;
            cursorPositionBeforeKeyPress = Editor.CaretOffset;
            bool isSomethingSelected = Editor.IsSomethingSelected;

            if (descriptor.SpecialKey == SpecialKey.BackSpace && Editor.CaretOffset == lastInsertedSemicolon)
            {
                EditActions.Undo(Editor);
                lastInsertedSemicolon = -1;
                return(false);
            }

            lastInsertedSemicolon = -1;
            if (descriptor.KeyChar == ';' && Editor.EditMode == EditMode.Edit && !DoInsertTemplate() && !isSomethingSelected && PropertyService.Get(
                    "SmartSemicolonPlacement",
                    false
                    ) && !(stateTracker.IsInsideComment || stateTracker.IsInsideString))
            {
                bool   retval  = base.KeyPress(descriptor);
                var    curLine = Editor.GetLine(Editor.CaretLine);
                string text    = Editor.GetTextAt(curLine);
                if (!(text.EndsWith(";", StringComparison.Ordinal) || text.Trim().StartsWith("for", StringComparison.Ordinal)))
                {
                    int guessedOffset;

                    if (GuessSemicolonInsertionOffset(Editor, curLine, Editor.CaretOffset, out guessedOffset))
                    {
                        using (var undo = Editor.OpenUndoGroup()) {
                            Editor.RemoveText(Editor.CaretOffset - 1, 1);
                            Editor.CaretOffset    = guessedOffset;
                            lastInsertedSemicolon = Editor.CaretOffset + 1;
                            retval = base.KeyPress(descriptor);
                        }
                    }
                }
                return(retval);
            }

            if (descriptor.SpecialKey == SpecialKey.Tab && descriptor.ModifierKeys == ModifierKeys.None && !CompletionWindowManager.IsVisible)
            {
                SafeUpdateIndentEngine(Editor.CaretOffset);
                if (stateTracker.IsInsideStringLiteral && !Editor.IsSomethingSelected)
                {
                    var lexer = new ICSharpCode.NRefactory.CSharp.Completion.CSharpCompletionEngineBase.MiniLexer(Editor.GetTextAt(0, Editor.CaretOffset));
                    lexer.Parse();
                    if (lexer.IsInString)
                    {
                        Editor.InsertAtCaret("\\t");
                        return(false);
                    }
                }
            }


            if (descriptor.SpecialKey == SpecialKey.Tab && DefaultSourceEditorOptions.Instance.TabIsReindent && !CompletionWindowManager.IsVisible && Editor.EditMode == EditMode.Edit && !DoInsertTemplate() && !isSomethingSelected)
            {
                ReindentOnTab();

                return(false);
            }

            SafeUpdateIndentEngine(Editor.CaretOffset);
            if (!stateTracker.IsInsideOrdinaryCommentOrString)
            {
                if (descriptor.KeyChar == '@')
                {
                    var retval = base.KeyPress(descriptor);
                    int cursor = Editor.CaretOffset;
                    if (cursor < Editor.Length && Editor.GetCharAt(cursor) == '"')
                    {
                        ConvertNormalToVerbatimString(Editor, cursor + 1);
                    }
                    return(retval);
                }
            }


            //do the smart indent
            if (!indentationDisabled)
            {
                bool retval;
                //capture some of the current state
                int  oldBufLen = Editor.Length;
                int  oldLine   = Editor.CaretLine + 1;
                bool reIndent  = false;

                //pass through to the base class, which actually inserts the character
                //and calls HandleCodeCompletion etc to handles completion
                using (var undo = Editor.OpenUndoGroup()) {
                    DoPreInsertionSmartIndent(descriptor.SpecialKey);
                }
                wasInStringLiteral = stateTracker.IsInsideStringLiteral;


                bool returnBetweenBraces =
                    descriptor.SpecialKey == SpecialKey.Return &&
                    descriptor.ModifierKeys == ModifierKeys.None &&
                    Editor.CaretOffset > 0 && Editor.CaretOffset < Editor.Length &&
                    Editor.GetCharAt(Editor.CaretOffset - 1) == '{' && Editor.GetCharAt(Editor.CaretOffset) == '}' && !stateTracker.IsInsideOrdinaryCommentOrString;

                bool automaticReindent;
                // need to be outside of an undo group - otherwise it interferes with other text editor extension
                // esp. the documentation insertion undo steps.
                retval = base.KeyPress(descriptor);


                if (descriptor.KeyChar == '/' && stateTracker.IsInsideMultiLineComment)
                {
                    if (Editor.CaretOffset - 3 >= 0 && Editor.GetCharAt(Editor.CaretOffset - 3) == '*' && Editor.GetCharAt(Editor.CaretOffset - 2) == ' ')
                    {
                        using (var undo = Editor.OpenUndoGroup()) {
                            Editor.RemoveText(Editor.CaretOffset - 2, 1);
                        }
                    }
                }

                //handle inserted characters
                if (Editor.CaretOffset <= 0 || Editor.IsSomethingSelected)
                {
                    return(retval);
                }

                lastCharInserted = TranslateKeyCharForIndenter(descriptor.SpecialKey, descriptor.KeyChar, Editor.GetCharAt(Editor.CaretOffset - 1));
                if (lastCharInserted == '\0')
                {
                    return(retval);
                }
                using (var undo = Editor.OpenUndoGroup()) {
                    if (returnBetweenBraces)
                    {
                        var oldOffset = Editor.CaretOffset;
                        Editor.InsertAtCaret(Editor.EolMarker);
                        DoReSmartIndent();
                        Editor.CaretOffset = oldOffset;
                    }

                    SafeUpdateIndentEngine(Editor.CaretOffset);

                    if (descriptor.SpecialKey == SpecialKey.Return && descriptor.ModifierKeys == ModifierKeys.Control)
                    {
                        FixLineStart(Editor, stateTracker, Editor.CaretLine + 1);
                    }
                    else
                    {
                        if (!(oldLine == Editor.CaretLine + 1 && lastCharInserted == '\n') && (oldBufLen != Editor.Length || lastCharInserted != '\0'))
                        {
                            DoPostInsertionSmartIndent(lastCharInserted, out reIndent);
                        }
                        else
                        {
                            reIndent = lastCharInserted == '\n';
                        }
                    }
                    //reindent the line after the insertion, if needed
                    //N.B. if the engine says we need to reindent, make sure that it's because a char was
                    //inserted rather than just updating the stack due to moving around

                    SafeUpdateIndentEngine(Editor.CaretOffset);
                    // Automatically reindent in text link mode will cause the mode exiting, therefore we need to prevent that.
                    automaticReindent = (stateTracker.NeedsReindent && lastCharInserted != '\0') && Editor.EditMode == EditMode.Edit;
                    if (descriptor.SpecialKey == SpecialKey.Return && (reIndent || automaticReindent))
                    {
                        if (Editor.Options.IndentStyle == IndentStyle.Virtual)
                        {
                            if (Editor.GetLine(Editor.CaretLine).Length == 0)
                            {
                                Editor.CaretColumn = Editor.GetVirtualIndentationColumn(Editor.CaretLine);
                            }
                        }
                        else
                        {
                            DoReSmartIndent();
                        }
                    }
                }

                SafeUpdateIndentEngine(Editor.CaretOffset);
                lastCharInserted = '\0';
                CheckXmlCommentCloseTag(descriptor.KeyChar);
                return(retval);
            }

            if (Editor.Options.IndentStyle == IndentStyle.Auto && DefaultSourceEditorOptions.Instance.TabIsReindent && descriptor.SpecialKey == SpecialKey.Tab)
            {
                bool retval = base.KeyPress(descriptor);
                DoReSmartIndent();
                CheckXmlCommentCloseTag(descriptor.KeyChar);
                return(retval);
            }

            //pass through to the base class, which actually inserts the character
            //and calls HandleCodeCompletion etc to handles completion
            var result = base.KeyPress(descriptor);

            CheckXmlCommentCloseTag(descriptor.KeyChar);

            return(result);
        }
Esempio n. 25
0
        public override void InsertCompletionText(CompletionListWindow window, ref KeyActions ka, KeyDescriptor descriptor)
        {
            // insert add/remove event handler code after +=/-=
            var editor = factory.Ext.Editor;


            bool AddSemicolon = true;
            var  position     = window.CodeCompletionContext.TriggerOffset;

            editor.ReplaceText(position, editor.CaretOffset - position, this.DisplayText + (AddSemicolon ? ";" : ""));


            var document       = IdeApp.Workbench.ActiveDocument;
            var parsedDocument = document.UpdateParseDocument().Result;
            var semanticModel  = parsedDocument.GetAst <SemanticModel> ();

            var declaringType   = semanticModel.GetEnclosingSymbol <INamedTypeSymbol> (position, default(CancellationToken));
            var enclosingSymbol = semanticModel.GetEnclosingSymbol <ISymbol> (position, default(CancellationToken));

            var insertionPoints = InsertionPointService.GetInsertionPoints(
                document.Editor,
                parsedDocument,
                declaringType,
                editor.CaretOffset
                );
            var options = new InsertionModeOptions(
                GettextCatalog.GetString("Create new method"),
                insertionPoints,
                point => {
                if (!point.Success)
                {
                    return;
                }
                var indent = "\t";
                var sb     = new StringBuilder();
                if (enclosingSymbol != null && enclosingSymbol.IsStatic)
                {
                    sb.Append("static ");
                }
                sb.Append("void ");
                int pos2 = sb.Length;
                sb.Append(this.DisplayText);
                sb.Append(' ');
                sb.Append("(");

                var delegateMethod = delegateType.GetDelegateInvokeMethod();
                for (int k = 0; k < delegateMethod.Parameters.Length; k++)
                {
                    if (k > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(RoslynCompletionData.SafeMinimalDisplayString(delegateMethod.Parameters [k], semanticModel, position, MonoDevelop.Ide.TypeSystem.Ambience.LabelFormat));
                }
                sb.Append(")");

                sb.Append(editor.EolMarker);
                sb.Append(indent);
                sb.Append("{");
                sb.Append(editor.EolMarker);
                sb.Append(indent);
                sb.Append(editor.Options.GetIndentationString());
                //int cursorPos = pos + sb.Length;
                sb.Append(editor.EolMarker);
                sb.Append(indent);
                sb.Append("}");
                point.InsertionPoint.Insert(document.Editor, document, sb.ToString());
                //			// start text link mode after insert
                //			var links = new List<TextLink> ();
                //			var link = new TextLink ("name");
                //
                //			link.AddLink (new TextSegment (initialOffset, this.DisplayText.Length));
                //			link.AddLink (new TextSegment (initialOffset + pos + pos2, this.DisplayText.Length));
                //			links.Add (link);
                //			editor.StartTextLinkMode (new TextLinkModeOptions (links));
            }
                );

            editor.StartInsertionMode(options);
        }
        /// <summary>
        /// Takes the configuration class and converts it to a SAML2.0 metadata document.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="keyInfo">The keyInfo.</param>
        private void ConvertToMetadata(Saml2Configuration config, KeyInfo keyInfo)
        {
            var entity = CreateDefaultEntity();

            entity.EntityID   = config.ServiceProvider.Id;
            entity.ValidUntil = DateTime.Now.AddDays(7);

            var serviceProviderDescriptor = new SpSsoDescriptor
            {
                ProtocolSupportEnumeration = new[] { Saml20Constants.Protocol },
                AuthnRequestsSigned        = XmlConvert.ToString(true),
                WantAssertionsSigned       = XmlConvert.ToString(true)
            };

            if (config.ServiceProvider.NameIdFormats.Count > 0)
            {
                serviceProviderDescriptor.NameIdFormat = new string[config.ServiceProvider.NameIdFormats.Count];
                var count = 0;
                foreach (var elem in config.ServiceProvider.NameIdFormats)
                {
                    serviceProviderDescriptor.NameIdFormat[count++] = elem.Format;
                }
            }

            var baseUrl = new Uri(config.ServiceProvider.Server);
            var logoutServiceEndpoints = new List <Endpoint>();
            var signonServiceEndpoints = new List <IndexedEndpoint>();

            var artifactResolutionEndpoints = new List <IndexedEndpoint>(2);

            // Include endpoints.
            foreach (var endpoint in config.ServiceProvider.Endpoints)
            {
                if (endpoint.Type == EndpointType.SignOn)
                {
                    var loginEndpoint = new IndexedEndpoint
                    {
                        Index     = endpoint.Index,
                        IsDefault = true,
                        Location  = new Uri(baseUrl, endpoint.LocalPath).ToString(),
                        Binding   = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost)
                    };
                    signonServiceEndpoints.Add(loginEndpoint);

                    var artifactSignonEndpoint = new IndexedEndpoint
                    {
                        Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                        Index    = loginEndpoint.Index,
                        Location = loginEndpoint.Location
                    };
                    artifactResolutionEndpoints.Add(artifactSignonEndpoint);

                    continue;
                }

                if (endpoint.Type == EndpointType.Logout)
                {
                    var logoutEndpoint = new Endpoint
                    {
                        Location = new Uri(baseUrl, endpoint.LocalPath).ToString()
                    };
                    logoutEndpoint.ResponseLocation = logoutEndpoint.Location;
                    logoutEndpoint.Binding          = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost);
                    logoutServiceEndpoints.Add(logoutEndpoint);

                    // TODO: Look at this...
                    logoutEndpoint = new Endpoint
                    {
                        Location = new Uri(baseUrl, endpoint.LocalPath).ToString()
                    };
                    logoutEndpoint.ResponseLocation = logoutEndpoint.Location;
                    logoutEndpoint.Binding          = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpRedirect);
                    logoutServiceEndpoints.Add(logoutEndpoint);

                    var artifactLogoutEndpoint = new IndexedEndpoint
                    {
                        Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                        Index    = endpoint.Index,
                        Location = logoutEndpoint.Location
                    };
                    artifactResolutionEndpoints.Add(artifactLogoutEndpoint);

                    continue;
                }
            }

            serviceProviderDescriptor.SingleLogoutService      = logoutServiceEndpoints.ToArray();
            serviceProviderDescriptor.AssertionConsumerService = signonServiceEndpoints.ToArray();

            // Attribute consuming service.
            if (config.Metadata.RequestedAttributes.Count > 0)
            {
                var attConsumingService = new AttributeConsumingService();
                serviceProviderDescriptor.AttributeConsumingService = new[] { attConsumingService };
                attConsumingService.Index       = signonServiceEndpoints[0].Index;
                attConsumingService.IsDefault   = true;
                attConsumingService.ServiceName = new[] { new LocalizedName("SP", "en") };

                attConsumingService.RequestedAttribute = new RequestedAttribute[config.Metadata.RequestedAttributes.Count];

                for (var i = 0; i < config.Metadata.RequestedAttributes.Count; i++)
                {
                    attConsumingService.RequestedAttribute[i] = new RequestedAttribute
                    {
                        Name = config.Metadata.RequestedAttributes[i].Name
                    };
                    if (config.Metadata.RequestedAttributes[i].IsRequired)
                    {
                        attConsumingService.RequestedAttribute[i].IsRequired = true;
                    }

                    attConsumingService.RequestedAttribute[i].NameFormat = SamlAttribute.NameformatBasic;
                }
            }
            else
            {
                serviceProviderDescriptor.AttributeConsumingService = new AttributeConsumingService[0];
            }

            if (config.Metadata == null || !config.Metadata.ExcludeArtifactEndpoints)
            {
                serviceProviderDescriptor.ArtifactResolutionService = artifactResolutionEndpoints.ToArray();
            }

            entity.Items = new object[] { serviceProviderDescriptor };

            // Keyinfo
            var keySigning    = new KeyDescriptor();
            var keyEncryption = new KeyDescriptor();

            serviceProviderDescriptor.KeyDescriptor = new[] { keySigning, keyEncryption };

            keySigning.Use          = KeyTypes.Signing;
            keySigning.UseSpecified = true;

            keyEncryption.Use          = KeyTypes.Encryption;
            keyEncryption.UseSpecified = true;

            // Ugly conversion between the .Net framework classes and our classes ... avert your eyes!!
            keySigning.KeyInfo    = Serialization.DeserializeFromXmlString <Schema.XmlDSig.KeyInfo>(keyInfo.GetXml().OuterXml);
            keyEncryption.KeyInfo = keySigning.KeyInfo;

            // apply the <Organization> element
            if (config.Metadata.Organization != null)
            {
                entity.Organization = new Schema.Metadata.Organization
                {
                    OrganizationName = new[] { new LocalizedName {
                                                   Value = config.Metadata.Organization.Name
                                               } },
                    OrganizationDisplayName = new[] { new LocalizedName {
                                                          Value = config.Metadata.Organization.DisplayName
                                                      } },
                    OrganizationURL = new[] { new LocalizedURI {
                                                  Value = config.Metadata.Organization.Url
                                              } }
                };
            }

            if (config.Metadata.Contacts != null && config.Metadata.Contacts.Any())
            {
                entity.ContactPerson = config.Metadata.Contacts.Select(x => new Schema.Metadata.Contact
                {
                    ContactType =
                        (Schema.Metadata.ContactType)
                            ((int)x.Type),
                    Company         = x.Company,
                    GivenName       = x.GivenName,
                    SurName         = x.SurName,
                    EmailAddress    = new[] { x.Email },
                    TelephoneNumber = new[] { x.Phone }
                }).ToArray();
            }
        }
Esempio n. 27
0
 public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
 {
     PropertyDescriptorCollection ps = base.GetProperties(context, value, attributes);
       ICustomPropertyConverter s = value as ICustomPropertyConverter;
       if (s == null) throw new InvalidOperationException();
       //keep given properties and add one for each key
       PropertyDescriptor[] props = new PropertyDescriptor[ps.Count + s.GetKeys().Count];
       int i = 0;
       foreach (PropertyDescriptor p in ps) props[i++] = p;
       foreach (object key in s.GetKeys())
       {
     //create attributes for s
     ArrayList attrs = new ArrayList();
     attrs.Add(new DescriptionAttribute(s.DescriptionOf(key)));
     attrs.Add(new ReadOnlyAttribute(s.IsReadOnly(key)));
     attrs.Add(new CategoryAttribute(s.CategoryOf(key)));
     attrs.Add(RefreshPropertiesAttribute.All);
     string customEditor = s.CustomEditorOf(key);
     if (customEditor != null)
       attrs.Add(new EditorAttribute(customEditor,typeof(System.Drawing.Design.UITypeEditor)));
     object v = s.ValueOf(key);
     props[i++] = new KeyDescriptor(s.GetType(), key, s.DisplayNameOf(key), (v==null ? "":v).GetType(),
       (Attribute[])attrs.ToArray(typeof(Attribute)),
       s.IsDefaultExpanded(key));
       }
       PropertyDescriptorCollection res = new PropertyDescriptorCollection(props);
       return res;
 }
        private static void CreateIdentityProviderMetadata(SamlIdpData idpData, string fileName, Encoding encoding)
        {
            if ( string.IsNullOrEmpty(idpData.SigninCertificateCn))
                throw new ApplicationException("no CN for a Certificate supplied");

            string signingCertificateSubjectName = idpData.SigninCertificateCn;

            Constants.NameIdType nidFmt = idpData.NameIdType;

            MetadataSerializer serializer = new MetadataSerializer();
            IdentityProviderSingleSignOnDescriptor item = new IdentityProviderSingleSignOnDescriptor();

            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(idpData.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(signingCertificateSubjectName);
            KeyDescriptor descriptor = new KeyDescriptor(
                new SecurityKeyIdentifier(
                    new SecurityKeyIdentifierClause[]
                    {
                        new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>()
                    }));

            descriptor.Use = KeyType.Signing;
            item.Keys.Add(descriptor);

            //using 2.0
            if (Constants.NameIdType.Saml20 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Transient);

            //using 1.1
            if (Constants.NameIdType.Saml11 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Unspecified);

            foreach (var attributeName in idpData.AttributeNames)
            {
                Saml2Attribute at1 = new Saml2Attribute(attributeName.Name)
                {
                    NameFormat = new Uri(Constants.Saml20AttributeNameFormat)
                };
                item.SupportedAttributes.Add(at1);
            }

            item.ProtocolsSupported.Add(new Uri(Constants.Saml20Protocol));
            item.SingleSignOnServices.Add(new ProtocolEndpoint(new Uri(idpData.BindingType), new Uri(idpData.BindingLocation)));

            metadata.RoleDescriptors.Add(item);

            metadata.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = idpData.MainContact.Company,
                GivenName = idpData.MainContact.GivenName,
                Surname = idpData.MainContact.SurName,
                EmailAddresses = { idpData.MainContact.Email },
                TelephoneNumbers = { idpData.MainContact.Phone }
            });

            XmlTextWriter writer = new XmlTextWriter(fileName, encoding);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
Esempio n. 29
0
 public void PostProcessKeyEvent(KeyDescriptor descriptor)
 {
     window.PostProcessKeyEvent(descriptor);
 }
        public override async Task <KeyActions> InsertCompletionText(CompletionListWindow window, KeyActions ka, KeyDescriptor descriptor)
        {
            var  editor     = ext.Editor;
            bool isExplicit = false;
            //			if (member.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
            //				foreach (var m in type.Members) {
            //					if (m.Name == member.Name && !m.ReturnType.Equals (member.ReturnType)) {
            //						isExplicit = true;
            //						break;
            //					}
            //				}
            //			}
            //			var resolvedType = type.Resolve (ext.Project).GetDefinition ();
            //			if (ext.Project != null)
            //				generator.PolicyParent = ext.Project.Policies;

            var    result    = CSharpCodeGenerator.CreateProtocolMemberImplementation(ext.DocumentContext, ext.Editor, currentType, currentType.Locations.First(), Symbol, isExplicit, factory.SemanticModel);
            string sb        = result.Code.TrimStart();
            int    trimStart = result.Code.Length - sb.Length;

            sb = sb.TrimEnd();

            var lastRegion = result.BodyRegions.LastOrDefault();
            var region     = lastRegion == null ? null
                                : new CodeGeneratorBodyRegion(lastRegion.StartOffset - trimStart, lastRegion.EndOffset - trimStart);

            int targetCaretPosition;
            int selectionEndPosition = -1;

            if (region != null && region.IsValid)
            {
                targetCaretPosition = declarationBegin + region.StartOffset;
                if (region.Length > 0)
                {
                    if (GenerateBody)
                    {
                        selectionEndPosition = declarationBegin + region.EndOffset;
                    }
                    else
                    {
                        //FIXME: if there are multiple regions, remove all of them
                        sb = sb.Substring(0, region.StartOffset) + sb.Substring(region.EndOffset);
                    }
                }
            }
            else
            {
                targetCaretPosition = declarationBegin + sb.Length;
            }

            editor.ReplaceText(declarationBegin, editor.CaretOffset - declarationBegin, sb);
            if (selectionEndPosition > 0)
            {
                editor.CaretOffset = selectionEndPosition;
                editor.SetSelection(targetCaretPosition, selectionEndPosition);
            }
            else
            {
                editor.CaretOffset = targetCaretPosition;
            }

            await OnTheFlyFormatter.Format(editor, ext.DocumentContext, declarationBegin, declarationBegin + sb.Length);

            return(ka);
        }
Esempio n. 31
0
        public virtual void InsertCompletionText(CompletionListWindow window, ref KeyActions ka, KeyDescriptor descriptor)
        {
            var currentWord = GetCurrentWord(window, descriptor);

            window.CompletionWidget.SetCompletionText(window.CodeCompletionContext, currentWord, CompletionText);
        }
Esempio n. 32
0
        public override void InsertCompletionText(CompletionListWindow window, ref KeyActions ka, KeyDescriptor descriptor)
        {
            var ext = window.Extension;

            base.InsertCompletionText(window, ref ka, descriptor);

            //FIXME: why is SkipSession private?! it's not even possible to recreate it, as editor.EndSession is private
            var skipSessionType = typeof(EditSession).Assembly.GetType("MonoDevelop.Ide.Editor.SkipCharSession");
            var skipSession     = (EditSession)Activator.CreateInstance(skipSessionType, skipchar);

            ext.Editor.StartSession(skipSession);

            //retrigger completion as soon as the item is committed
            Gtk.Application.Invoke((s, e) => ext.TriggerCompletion(CompletionTriggerReason.CharTyped));
        }
        static void CreatePassiveStsMetadata(StsData data, string fileName, Encoding encoding)
        {
            MetadataSerializer serializer = new MetadataSerializer();
            SecurityTokenServiceDescriptor item = new SecurityTokenServiceDescriptor();
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(data.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(data.SigninCertificateCn);

            metadata.SigningCredentials = new X509SigningCredentials(certificate);
            KeyDescriptor descriptor3 = new KeyDescriptor(new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() }));
            descriptor3.Use = KeyType.Signing;
            item.Keys.Add(descriptor3);

            if (data.Claims != null)
            {
                foreach (var claim in data.Claims)
                {
                    DisplayClaim dc = new DisplayClaim(claim.ClaimType, claim.DisplayTag, claim.Description)
                    {
                        Optional = claim.Optional
                    };

                    item.ClaimTypesOffered.Add(dc);
                }
            }

            item.PassiveRequestorEndpoints.Add(new EndpointAddress( new Uri(data.PassiveRequestorEndpoint).AbsoluteUri));

            if (data.Protocols != null)
            {
                foreach (Protocol protocol in data.Protocols)
                {
                    item.ProtocolsSupported.Add(new Uri(protocol.ProtocolNamespace));
                }
            }

            item.SecurityTokenServiceEndpoints.Add(new EndpointAddress( new Uri(data.ActiveStsEndpoint).AbsoluteUri));
            item.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = data.MainContact.Company,
                GivenName = data.MainContact.GivenName,
                Surname = data.MainContact.SurName,
                EmailAddresses = { data.MainContact.Email },
                TelephoneNumbers = { data.MainContact.Phone }
            });

            metadata.RoleDescriptors.Add(item);

            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
Esempio n. 34
0
        public bool PreProcessKeyEvent(KeyDescriptor descriptor)
        {
            if (descriptor.SpecialKey == SpecialKey.Escape)
            {
                CompletionWindowManager.HideWindow();
                return(true);
            }

            KeyActions ka         = KeyActions.None;
            bool       keyHandled = false;

            if (CompletionDataList != null)
            {
                foreach (ICompletionKeyHandler handler in CompletionDataList.KeyHandler)
                {
                    if (handler.PreProcessKey(facade, descriptor, out ka))
                    {
                        keyHandled = true;
                        break;
                    }
                }
            }
            if (!keyHandled)
            {
                ka = PreProcessKey(descriptor);
            }
            if ((ka & KeyActions.Complete) != 0)
            {
                CompleteWord(ref ka, descriptor);
            }

            if ((ka & KeyActions.CloseWindow) != 0)
            {
                CompletionWindowManager.HideWindow();
                OnWindowClosed(EventArgs.Empty);
            }

            if ((ka & KeyActions.Ignore) != 0)
            {
                return(true);
            }
            if ((ka & KeyActions.Process) != 0)
            {
                if (descriptor.SpecialKey == SpecialKey.Left || descriptor.SpecialKey == SpecialKey.Right)
                {
                    // Close if there's a modifier active EXCEPT lock keys and Modifiers
                    // Makes an exception for Mod1Mask (usually alt), shift, control, meta and super
                    // This prevents the window from closing if the num/scroll/caps lock are active
                    // FIXME: modifier mappings depend on X server settings

//					if ((modifier & ~(Gdk.ModifierType.LockMask | (Gdk.ModifierType.ModifierMask & ~(Gdk.ModifierType.ShiftMask | Gdk.ModifierType.Mod1Mask | Gdk.ModifierType.ControlMask | Gdk.ModifierType.MetaMask | Gdk.ModifierType.SuperMask)))) != 0) {
                    // this version doesn't work for my system - seems that I've a modifier active
                    // that gdk doesn't know about. How about the 2nd version - should close on left/rigt + shift/mod1/control/meta/super
                    if ((descriptor.ModifierKeys & (ModifierKeys.Shift | ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Command)) != 0)
                    {
                        CompletionWindowManager.HideWindow();
                        OnWindowClosed(EventArgs.Empty);
                        return(false);
                    }

                    if (declarationviewwindow != null && declarationviewwindow.Multiple)
                    {
                        if (descriptor.SpecialKey == SpecialKey.Left)
                        {
                            declarationviewwindow.OverloadLeft();
                        }
                        else
                        {
                            declarationviewwindow.OverloadRight();
                        }
                    }
                    else
                    {
                        CompletionWindowManager.HideWindow();
                        OnWindowClosed(EventArgs.Empty);
                        return(false);
                    }
                    return(true);
                }
                if (completionDataList != null && completionDataList.CompletionSelectionMode == CompletionSelectionMode.OwnTextField)
                {
                    return(true);
                }
            }
            return(false);
        }
Esempio n. 35
0
        // Creates a KeyDescriptor from the supplied X.509 certificate
        private static KeyDescriptor CreateKeyDescriptor(X509Certificate2 x509Certificate)
        {
            KeyDescriptor keyDescriptor = new KeyDescriptor();
            KeyInfo keyInfo = CreateKeyInfo(x509Certificate);
            keyDescriptor.KeyInfo = keyInfo.GetXml();

            // Set the encryption method by specifying the entire XML.
            //XmlDocument xmlDocument = new XmlDocument();
            //xmlDocument.PreserveWhitespace = true;
            //xmlDocument.LoadXml("<md:EncryptionMethod xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>");
            //keyDescriptor.EncryptionMethods.Add(xmlDocument.DocumentElement);

            // Set the encryption method by specifying just the algorithm.
            //keyDescriptor.AddEncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes256-cbc");

            return keyDescriptor;
        }
Esempio n. 36
0
        public override Task <KeyActions> InsertCompletionText(CompletionListWindow window, KeyActions ka, KeyDescriptor descriptor)
        {
            var buf = window.CompletionWidget;

            if (buf != null)
            {
                int deleteStartOffset = window.CodeCompletionContext.TriggerOffset;
                if (text.StartsWith(docTypeStart))
                {
                    int start = window.CodeCompletionContext.TriggerOffset - docTypeStart.Length;
                    if (start >= 0)
                    {
                        string readback = buf.GetText(start, window.CodeCompletionContext.TriggerOffset);
                        if (string.Compare(readback, docTypeStart, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            deleteStartOffset -= docTypeStart.Length;
                        }
                    }
                }

                buf.Replace(deleteStartOffset, buf.CaretOffset - deleteStartOffset, text);
            }
            return(Task.FromResult(ka));
        }
Esempio n. 37
0
        public override bool Handle(TextEditor editor, DocumentContext ctx, KeyDescriptor descriptor)
        {
            if (Array.IndexOf(excludedMimeTypes, editor.MimeType) >= 0)
            {
                return(false);
            }
            int braceIndex = openBrackets.IndexOf(descriptor.KeyChar);

            if (braceIndex < 0)
            {
                return(false);
            }


            var line = editor.GetLine(editor.CaretLine);

            if (line == null)
            {
                return(false);
            }

            bool inStringOrComment = false;

            var stack = editor.SyntaxHighlighting.GetScopeStackAsync(Math.Max(0, editor.CaretOffset - 2), CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            foreach (var span in stack)
            {
                if (string.IsNullOrEmpty(span))
                {
                    continue;
                }
                if (span.Contains("string") ||
                    span.Contains("comment"))
                {
                    inStringOrComment = true;
                    break;
                }
            }
            char insertionChar         = '\0';
            bool insertMatchingBracket = false;

            if (!inStringOrComment)
            {
                char closingBrace = closingBrackets [braceIndex];
                char openingBrace = openBrackets [braceIndex];

                int count = 0;
                foreach (char curCh in GetTextWithoutCommentsAndStrings(editor, 0, editor.Length))
                {
                    if (curCh == openingBrace)
                    {
                        count++;
                    }
                    else if (curCh == closingBrace)
                    {
                        count--;
                    }
                }

                if (count >= 0)
                {
                    insertMatchingBracket = true;
                    insertionChar         = closingBrace;
                }
            }

            if (insertMatchingBracket)
            {
                using (var undo = editor.OpenUndoGroup()) {
                    editor.EnsureCaretIsNotVirtual();
                    editor.InsertAtCaret(insertionChar.ToString());
                    editor.CaretOffset--;
                    editor.StartSession(new SkipCharSession(insertionChar));
                }
                return(true);
            }

            return(false);
        }
Esempio n. 38
0
 public bool PreProcessKeyEvent(KeyDescriptor descriptor)
 {
     return(window.PreProcessKeyEvent(descriptor));
 }