public static List <AppRoleAssignment> GetAssignedRolesForUser(string userName, string enterpiseAppId)
        {
            const string uriTemplate = "https://graph.microsoft.com/beta/users/{0}/appRoleAssignments?filter=resourceId eq {1}&format=application/json;odata=nometadata";
            string       uri         = string.Format(uriTemplate, userName, enterpiseAppId);

            JwtSecurityToken token = TokenUtilities.GetTokenFromClientCredentials("https://graph.microsoft.com/");

            HttpWebRequest request = WebRequest.CreateHttp(uri);

            request.Method      = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Authorization", token.RawData);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        string responseJson = reader.ReadToEnd();

                        GraphResults results = JsonConvert.DeserializeObject <GraphResults>(responseJson);
                        return(results.AppRoleAssignments);
                    }
                }
            }
        }
Пример #2
0
        internal void Test(
            Func <SyntaxGenerator, SyntaxNode> nodeCreator,
            string cs, string vb)
        {
            var hostServices = MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider());
            var workspace    = new AdhocWorkspace(hostServices);

            if (cs != null)
            {
                var csharpCodeGenService = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService <ICodeGenerationService>();
                var codeDefFactory       = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();
                TokenUtilities.AssertTokensEqual(cs, node.ToFullString(), LanguageNames.CSharp);
            }

            if (vb != null)
            {
                var visualBasicCodeGenService = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService <ICodeGenerationService>();
                var codeDefFactory            = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();
                TokenUtilities.AssertTokensEqual(vb, node.ToString(), LanguageNames.VisualBasic);
            }
        }
        // GET: /Organisation/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.GetOrganisationsAsync(accessToken, xeroTenantId);

            var organisation_info = new Organisation();

            organisation_info = response._Organisations[0];

            return(View(organisation_info));
        }
Пример #4
0
 public void Dispose()
 {
     try
     {
         if (!_ignoreResult)
         {
             this.Document = this.Result;
             if (_compareTokens)
             {
                 var actual = string.Join(" ", Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result.GetSyntaxRootAsync().Result.DescendantTokens());
                 TokenUtilities.AssertTokensEqual(_expected, actual, _language);
             }
             else
             {
                 var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result
                              .GetSyntaxRootAsync().Result.ToFullString();
                 Assert.Equal(_expected, actual);
             }
         }
     }
     finally
     {
         _workspace.Dispose();
     }
 }
Пример #5
0
        // GET: /InvoiceSync/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();


            var sevenDaysAgo   = DateTime.Now.AddDays(-7).ToString("yyyy, MM, dd");
            var invoicesFilter = "Date >= DateTime(" + sevenDaysAgo + ")";

            var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId, null, invoicesFilter);

            var invoices = response._Invoices;

            return(View(invoices));
        }
Пример #6
0
        protected async Task TestActionsOnLinkedFiles(
            TestWorkspace workspace,
            string expectedText,
            int index,
            ImmutableArray <CodeAction> actions,
            string expectedPreviewContents = null,
            bool ignoreTrivia = true)
        {
            var operations = await VerifyInputsAndGetOperationsAsync(index, actions);

            await VerifyPreviewContents(workspace, expectedPreviewContents, operations);

            var applyChangesOperation = operations.OfType <ApplyChangesOperation>().First();

            applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None);

            foreach (var document in workspace.Documents)
            {
                var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();

                var actualText = ignoreTrivia ? fixedRoot.ToString() : fixedRoot.ToFullString();

                if (ignoreTrivia)
                {
                    TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
                }
                else
                {
                    Assert.Equal(expectedText, actualText);
                }
            }
        }
Пример #7
0
        // GET: ContactsInfo
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.GetContactsAsync(accessToken, xeroTenantId);

            var contacts = response._Contacts;

            return(View(contacts));
        }
Пример #8
0
        public void GetTokenFrequencyCaseInsensitiveTest()
        {
            var freq = TokenUtilities.GetTokenFrequency(Sample, true);

            Assert.AreEqual(3, freq["a"]);
            Assert.AreEqual(3, freq["A"]);
        }
        /// <summary>
        /// Returns all <see cref="SecurityKey"/> to use when validating the signature of a token.
        /// </summary>
        /// <param name="token">The <see cref="string"/> representation of the token that is being validated.</param>
        /// <param name="samlToken">The <see cref="SecurityToken"/> that is being validated.</param>
        /// <param name="tokenKeyInfo">The <see cref="KeyInfo"/> field of the token being validated</param>
        /// <param name="validationParameters">A <see cref="TokenValidationParameters"/> required for validation.</param>
        /// <param name="keyMatched">A <see cref="bool"/> to represent if a a issuer signing key matched with token kid or x5t</param>
        /// <returns>Returns all <see cref="SecurityKey"/> to use for signature validation.</returns>
        internal static IEnumerable <SecurityKey> GetKeysForTokenSignatureValidation(string token, SecurityToken samlToken, KeyInfo tokenKeyInfo, TokenValidationParameters validationParameters, out bool keyMatched)
        {
            keyMatched = false;

            if (validationParameters.IssuerSigningKeyResolver != null)
            {
                return(validationParameters.IssuerSigningKeyResolver(token, samlToken, tokenKeyInfo?.Id, validationParameters));
            }
            else
            {
                SecurityKey key = ResolveTokenSigningKey(tokenKeyInfo, validationParameters);

                if (key != null)
                {
                    keyMatched = true;
                    return(new List <SecurityKey> {
                        key
                    });
                }
                else
                {
                    keyMatched = false;
                    if (validationParameters.TryAllIssuerSigningKeys)
                    {
                        return(TokenUtilities.GetAllSigningKeys(validationParameters));
                    }
                }
            }
            return(null);
        }
Пример #10
0
        protected void TestActionsOnLinkedFiles(
            TestWorkspace workspace,
            string expectedText,
            int index,
            IList <CodeAction> actions,
            string expectedPreviewContents = null,
            bool compareTokens             = true)
        {
            var operations = VerifyInputsAndGetOperations(index, actions);

            VerifyPreviewContents(workspace, expectedPreviewContents, operations);

            var applyChangesOperation = operations.OfType <ApplyChangesOperation>().First();

            applyChangesOperation.Apply(workspace, CancellationToken.None);

            foreach (var document in workspace.Documents)
            {
                var fixedRoot  = workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync().Result;
                var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString();

                if (compareTokens)
                {
                    TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
                }
                else
                {
                    Assert.Equal(expectedText, actualText);
                }
            }
        }
        public async Task <ActionResult> Create(string Name, string Number)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var asset = new Asset()
            {
                AssetName   = Name,
                AssetNumber = Number
            };

            var AssetApi = new AssetApi();
            var response = await AssetApi.CreateAssetAsync(accessToken, xeroTenantId, asset);

            return(RedirectToAction("Index", "AssetsInfo"));
        }
Пример #12
0
        public static List <AppRole> GetRolesForApplication(string appId)
        {
            const string uriTemplate = "https://graph.microsoft.com/v1.0/applications?$filter=appId eq '{0}'&$select=appRoles&$format=application/json;odata=nometadata";
            string       uri         = string.Format(uriTemplate, appId);

            JwtSecurityToken token = TokenUtilities.GetTokenFromClientCredentials("https://graph.microsoft.com/");

            HttpWebRequest request = WebRequest.CreateHttp(uri);

            request.Method      = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Authorization", token.RawData);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        string responseJson = reader.ReadToEnd();

                        GraphResults results = JsonConvert.DeserializeObject <GraphResults>(responseJson);
                        return(results.Applications.FirstOrDefault().AppRoles);
                    }
                }
            }
        }
        private void TestAnnotations(
            string expectedText,
            IList <TextSpan> expectedSpans,
            SyntaxNode fixedRoot,
            string annotationKind,
            bool compareTokens,
            ParseOptions parseOptions = null)
        {
            expectedSpans = expectedSpans ?? new List <TextSpan>();
            var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList();

            Assert.Equal(expectedSpans.Count, annotatedTokens.Count);

            if (expectedSpans.Count > 0)
            {
                var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage(), parseOptions));
                var actualTokens   = TokenUtilities.GetTokens(fixedRoot);

                for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++)
                {
                    var expectedToken = expectedTokens[i];
                    var actualToken   = actualTokens[i];

                    var actualIsConflict   = annotatedTokens.Contains(actualToken);
                    var expectedIsConflict = expectedSpans.Contains(expectedToken.Span);
                    Assert.Equal(expectedIsConflict, actualIsConflict);
                }
            }
        }
Пример #14
0
        public async Task <ActionResult> Create(string Name, string EmailAddress)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact();

            contact.Name         = Name;
            contact.EmailAddress = EmailAddress;
            var contacts = new Contacts();

            contacts._Contacts = new List <Contact>()
            {
                contact
            };

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateContactsAsync(accessToken, xeroTenantId, contacts);

            return(RedirectToAction("Index", "ContactsInfo"));
        }
        // GET: /Authorization/Callback
        public async Task <ActionResult> Callback(string code, string state)
        {
            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            var client = new XeroClient(XeroConfig, httpClientFactory);

            var xeroToken = (XeroOAuth2Token)await client.RequestXeroTokenAsync(code);

            List <Tenant> tenants = await client.GetConnectionsAsync(xeroToken);

            Tenant firstTenant = tenants[0];

            TokenUtilities.StoreToken(xeroToken);

            return(RedirectToAction("Index", "OrganisationInfo"));
        }
        protected async Task <Tuple <Solution, Solution> > TestOperationsAsync(
            TestWorkspace workspace,
            string expectedText,
            ImmutableArray <CodeActionOperation> operations,
            ImmutableArray <TextSpan> conflictSpans,
            ImmutableArray <TextSpan> renameSpans,
            ImmutableArray <TextSpan> warningSpans,
            ImmutableArray <TextSpan> navigationSpans,
            DocumentId expectedChangedDocumentId,
            ParseOptions parseOptions = null)
        {
            var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
            var oldSolution    = appliedChanges.Item1;
            var newSolution    = appliedChanges.Item2;

            if (TestWorkspace.IsWorkspaceElement(expectedText))
            {
                await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolution);

                return(Tuple.Create(oldSolution, newSolution));
            }

            var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution);

            var fixedRoot = await document.GetSyntaxRootAsync();

            var actualText = fixedRoot.ToFullString();

            Assert.Equal(expectedText, actualText);

            TestAnnotations(conflictSpans, ConflictAnnotation.Kind);
            TestAnnotations(renameSpans, RenameAnnotation.Kind);
            TestAnnotations(warningSpans, WarningAnnotation.Kind);
            TestAnnotations(navigationSpans, NavigationAnnotation.Kind);

            return(Tuple.Create(oldSolution, newSolution));

            void TestAnnotations(ImmutableArray <TextSpan> expectedSpans, string annotationKind)
            {
                var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList();

                Assert.Equal(expectedSpans.Length, annotatedTokens.Count);

                if (expectedSpans.Length > 0)
                {
                    var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage(), parseOptions));
                    var actualTokens   = TokenUtilities.GetTokens(fixedRoot);

                    for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++)
                    {
                        var expectedToken = expectedTokens[i];
                        var actualToken   = actualTokens[i];

                        var actualIsConflict   = annotatedTokens.Contains(actualToken);
                        var expectedIsConflict = expectedSpans.Contains(expectedToken.Span);
                        Assert.Equal(expectedIsConflict, actualIsConflict);
                    }
                }
            }
        }
Пример #17
0
        public async Task <ActionResult> Create(string Name, string LineDescription, string LineQuantity, string LineUnitAmount, string LineAccountCode)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact();

            contact.Name = Name;

            var line = new LineItem()
            {
                Description = LineDescription,
                Quantity    = decimal.Parse(LineQuantity),
                UnitAmount  = decimal.Parse(LineUnitAmount),
                AccountCode = LineAccountCode
            };

            var lines = new List <LineItem>()
            {
                line
            };

            var invoice = new Invoice()
            {
                Type      = Invoice.TypeEnum.ACCREC,
                Contact   = contact,
                Date      = DateTime.Today,
                DueDate   = DateTime.Today.AddDays(30),
                LineItems = lines
            };

            var invoiceList = new List <Invoice>();

            invoiceList.Add(invoice);

            var invoices = new Invoices();

            invoices._Invoices = invoiceList;

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateInvoicesAsync(accessToken, xeroTenantId, invoices);

            var updatedUTC = response._Invoices[0].UpdatedDateUTC;

            return(RedirectToAction("Index", "InvoiceSync"));
        }
        protected void TestActions(
            TestWorkspace workspace,
            string expectedText,
            int index,
            IList <CodeAction> actions,
            IList <TextSpan> expectedConflictSpans = null,
            IList <TextSpan> expectedRenameSpans   = null,
            IList <TextSpan> expectedWarningSpans  = null,
            string expectedPreviewContents         = null,
            bool compareTokens = true,
            bool compareExpectedTextAfterApply = false)
        {
            var operations = VerifyInputsAndGetOperations(index, actions);

            VerifyPreviewContents(workspace, expectedPreviewContents, operations);

            // Test annotations from the operation's new solution

            var applyChangesOperation = operations.OfType <ApplyChangesOperation>().First();

            var oldSolution = workspace.CurrentSolution;

            var newSolutionFromOperation = applyChangesOperation.ChangedSolution;
            var documentFromOperation    = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionFromOperation);
            var fixedRootFromOperation   = documentFromOperation.GetSyntaxRootAsync().Result;

            TestAnnotations(expectedText, expectedConflictSpans, fixedRootFromOperation, ConflictAnnotation.Kind, compareTokens);
            TestAnnotations(expectedText, expectedRenameSpans, fixedRootFromOperation, RenameAnnotation.Kind, compareTokens);
            TestAnnotations(expectedText, expectedWarningSpans, fixedRootFromOperation, WarningAnnotation.Kind, compareTokens);

            // Test final text

            string actualText;

            if (compareExpectedTextAfterApply)
            {
                applyChangesOperation.Apply(workspace, CancellationToken.None);
                var newSolutionAfterApply = workspace.CurrentSolution;

                var documentFromAfterApply  = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionAfterApply);
                var fixedRootFromAfterApply = documentFromAfterApply.GetSyntaxRootAsync().Result;
                actualText = compareTokens ? fixedRootFromAfterApply.ToString() : fixedRootFromAfterApply.ToFullString();
            }
            else
            {
                actualText = compareTokens ? fixedRootFromOperation.ToString() : fixedRootFromOperation.ToFullString();
            }

            if (compareTokens)
            {
                TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
            }
            else
            {
                Assert.Equal(expectedText, actualText);
            }
        }
Пример #19
0
        protected async Task TestMoveTypeToNewFileAsync(
            string originalCode,
            string expectedSourceTextAfterRefactoring,
            string expectedDocumentName,
            string destinationDocumentText,
            IList <string> destinationDocumentContainers = null,
            bool expectedCodeAction = true,
            int index         = 0,
            bool ignoreTrivia = true,
            Action <Workspace> onAfterWorkspaceCreated = null)
        {
            var testOptions = new TestParameters();

            if (expectedCodeAction)
            {
                using (var workspace = await CreateWorkspaceFromFileAsync(originalCode, testOptions))
                {
                    onAfterWorkspaceCreated?.Invoke(workspace);

                    // replace with default values on null.
                    if (destinationDocumentContainers == null)
                    {
                        destinationDocumentContainers = Array.Empty <string>();
                    }

                    var sourceDocumentId = workspace.Documents[0].Id;

                    // Verify the newly added document and its text
                    var oldSolutionAndNewSolution = await TestAddDocumentAsync(
                        testOptions, workspace,
                        destinationDocumentText, index, expectedDocumentName,
                        destinationDocumentContainers, ignoreTrivia);

                    // Verify source document's text after moving type.
                    var oldSolution        = oldSolutionAndNewSolution.Item1;
                    var newSolution        = oldSolutionAndNewSolution.Item2;
                    var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);
                    Assert.True(changedDocumentIds.Contains(sourceDocumentId), "source document was not changed.");

                    var modifiedSourceDocument = newSolution.GetDocument(sourceDocumentId);

                    if (ignoreTrivia)
                    {
                        TokenUtilities.AssertTokensEqual(
                            expectedSourceTextAfterRefactoring, (await modifiedSourceDocument.GetTextAsync()).ToString(), GetLanguage());
                    }
                    else
                    {
                        Assert.Equal(expectedSourceTextAfterRefactoring, (await modifiedSourceDocument.GetTextAsync()).ToString());
                    }
                }
            }
            else
            {
                await TestMissingAsync(originalCode);
            }
        }
Пример #20
0
 /// <summary>
 /// Return tokenized set of a string.
 /// </summary>
 /// <param name="word">input</param>
 /// <returns>tokenized version of a string as a set</returns>
 public Collection <string> TokenizeToSet(string word)
 {
     if (!String.IsNullOrEmpty(word))
     {
         SuppliedWord = word;
         return(TokenUtilities.CreateSet(Tokenize(word)));
     }
     return(null);
 }
Пример #21
0
        public void GetUniqueTokensCaseInsensitiveTest()
        {
            var set = TokenUtilities.GetUniqueTokens(Sample, true);

            Assert.AreEqual(3, set.Count);
            Assert.True(set.Contains("a"));
            Assert.True(set.Contains("A"));
            Assert.False(set.Contains("x"));
        }
        public IActionResult Index()
        {
            bool firstTimeConnection = false;

            if (TokenUtilities.TokenExists())
            {
                firstTimeConnection = true;
            }

            return(View(firstTimeConnection));
        }
 /// <summary>
 /// Merges <paramref name="claims"/> and <paramref name="subjectClaims"/>
 /// </summary>
 /// <param name="claims"> A dictionary of claims.</param>
 /// <param name="subjectClaims"> A collection of <see cref="Claim"/>'s</param>
 /// <returns> A merged list of <see cref="Claim"/>'s.</returns>
 internal static IEnumerable <Claim> GetAllClaims(IDictionary <string, object> claims, IEnumerable <Claim> subjectClaims)
 {
     if (claims == null)
     {
         return(subjectClaims);
     }
     else
     {
         return(TokenUtilities.MergeClaims(CreateClaimsFromDictionary(claims), subjectClaims));
     }
 }
Пример #24
0
        public void GetTokenFrequencyTest()
        {
            var freq = TokenUtilities.GetTokenFrequency(Sample, false);

            Assert.AreEqual(4, freq.Count);

            Assert.AreEqual(2, freq["a"]);
            Assert.AreEqual(1, freq["A"]);
            Assert.AreEqual(1, freq["b"]);
            Assert.AreEqual(2, freq["c"]);
        }
Пример #25
0
        public async Task <bool> TokenIsValid()
        {
            var token = await this.secureStorage.Get <string>(StorageConstants.ACCESS_TOKEN);

            if (string.IsNullOrEmpty(token))
            {
                return(false);
            }
            var expirationString = await this.secureStorage.Get <string>(StorageConstants.EXPIRATION_DATE);

            return(TokenUtilities.TokenIsValid(token, expirationString));
        }
Пример #26
0
        internal void Test(
            Func <SyntaxGenerator, SyntaxNode> nodeCreator,
            string cs, string csSimple,
            string vb, string vbSimple)
        {
            Assert.True(cs != null || csSimple != null || vb != null || vbSimple != null,
                        $"At least one of {nameof(cs)}, {nameof(csSimple)}, {nameof(vb)}, {nameof(vbSimple)} must be provided");

            var hostServices = VisualStudioMefHostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic);
            var workspace    = new AdhocWorkspace(hostServices);

            if (cs != null || csSimple != null)
            {
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();

                if (cs != null)
                {
                    TokenUtilities.AssertTokensEqual(cs, node.ToFullString(), LanguageNames.CSharp);
                }

                if (csSimple != null)
                {
                    var simplifiedRootNode = Simplify(workspace, WrapExpressionInBoilerplate(node, codeDefFactory), LanguageNames.CSharp);
                    var expression         = simplifiedRootNode.DescendantNodes().OfType <EqualsValueClauseSyntax>().First().Value;

                    TokenUtilities.AssertTokensEqual(csSimple, expression.NormalizeWhitespace().ToFullString(), LanguageNames.CSharp);
                }
            }

            if (vb != null || vbSimple != null)
            {
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();

                if (vb != null)
                {
                    TokenUtilities.AssertTokensEqual(vb, node.ToFullString(), LanguageNames.VisualBasic);
                }

                if (vbSimple != null)
                {
                    var simplifiedRootNode = Simplify(workspace, WrapExpressionInBoilerplate(node, codeDefFactory), LanguageNames.VisualBasic);
                    var expression         = simplifiedRootNode.DescendantNodes().OfType <EqualsValueSyntax>().First().Value;

                    TokenUtilities.AssertTokensEqual(vbSimple, expression.NormalizeWhitespace().ToFullString(), LanguageNames.VisualBasic);
                }
            }
        }
        public async Task <ActionResult> Create(string firstName, string lastName, string DateOfBirth)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            // var contact = new Contact();
            // contact.Name = Name;
            // contact.EmailAddress = EmailAddress;
            // var contacts = new Contacts();
            // contacts._Contacts = new List<Contact>() { contact };

            DateTime dob = DateTime.Today.AddYears(-20);

            HomeAddress homeAddress = new HomeAddress()
            {
                AddressLine1 = "6 MeatMe Street",
                AddressLine2 = " ",
                Region       = State.VIC,
                City         = "Long Island",
                PostalCode   = "9999",
                Country      = "New York"
            };

            Employee employee = new Employee()
            {
                FirstName   = firstName,
                LastName    = lastName,
                DateOfBirth = dob,
                HomeAddress = homeAddress
            };

            var employees = new List <Employee>()
            {
                employee
            };

            var PayrollAUApi = new PayrollAuApi();
            var response     = await PayrollAUApi.CreateEmployeeAsync(accessToken, xeroTenantId, employees);

            return(RedirectToAction("Index", "EmployeesInfo"));
        }
Пример #28
0
        // GET /Authorization/Callback
        public async Task <ActionResult> Callback(string code, string state)
        {
            var client    = new XeroClient(XeroConfig.Value, httpClientFactory);
            var xeroToken = (XeroOAuth2Token)await client.RequestXeroTokenAsync(code);

            List <Tenant> tenants = await client.GetConnectionsAsync(xeroToken);

            Tenant firstTenant = tenants[0];

            TokenUtilities.StoreToken(xeroToken);

            return(RedirectToAction("Index", "OrganisationInfo"));
        }
Пример #29
0
        // GET /Authorization/Callback
        public async Task <ActionResult> Callback(string code, string state)
        {
            var client    = new XeroClient(XeroConfig.Value);
            var xeroToken = (XeroOAuth2Token)await client.RequestAccessTokenAsync(code);

            List <Tenant> tenants = await client.GetConnectionsAsync(xeroToken);

            Tenant firstTenant = tenants[0];

            TokenUtilities.StoreToken(xeroToken);

            return(Redirect("http://localhost:3000/home"));
        }
Пример #30
0
        public async Task <TokenEntity> GetToken()
        {
            var token = await this.secureStorage.Get <string>(StorageConstants.ACCESS_TOKEN);

            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            var tokenDeserialized = TokenUtilities.DeserializeToken(token);

            return(tokenDeserialized);
        }