예제 #1
0
 public override async void Up()
 {
     using (var client = CosmosDbHelper.GetDocumentClient())
     {
         await CreatePostsCollectionAsync(client);
     }
 }
        public async Task <IActionResult> AzureAdLateralMovement()
        {
            var tenantId = ((ClaimsIdentity)User.Identity)
                           .FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            await CosmosDbHelper.InitializeCosmosDb(tenantId);

            var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

            var azureActiveDirectoryHelper = new AzureActiveDirectoryHelper(graphClient, HttpContext);

            List <string> lateralMovementDataList = null;

            try
            {
                lateralMovementDataList = await azureActiveDirectoryHelper.RunAzureActiveDirectoryApplication();
            }
            catch (ServiceException e)
            {
                if (e.Error.Code == "TokenNotFound")
                {
                    foreach (var cookie in Request.Cookies.Keys)
                    {
                        Response.Cookies.Delete(cookie);
                    }
                    return(RedirectToAction(nameof(Index), "Home"));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction(nameof(Index), "Home"));
            }

            return(View(lateralMovementDataList));
        }
예제 #3
0
        public async Task <ActionResult> Diagnostics()
        {
            //await Planetzine.MvcApplication.DatabaseReady.Task; // Make sure database and collection is created before continuing

            var diagnostics = new DiagnosticsModel();

            diagnostics.Results = CosmosDbHelper.Diagnostics();
            return(View(diagnostics));
        }
        public void RequestDocument_Success()
        {
            FeedResponse <WishList> response = CosmosDbHelper.RequestDocument <WishList>(testContext, this.doc);

            Debug.WriteLine(String.Format("RequestDocument response request charge: {0}", response.RequestCharge));
            Assert.IsTrue(response.RequestCharge < 50, string.Format("Request charge ({0} RU) wooh! what did you do? way too much RU.", response.RequestCharge));
            Assert.IsTrue(response.RequestCharge < 3, string.Format("Request charge ({0} RU) is really expensive!", response.RequestCharge));
            Assert.IsTrue(response.RequestCharge < 1.1, string.Format("Request charge ({0} RU) to expensive!", response.RequestCharge));
        }
예제 #5
0
 /// <summary>
 /// Creates a new database if it does not already exist
 /// </summary>
 /// <returns></returns>
 private async Task CreateAsync()
 {
     using (var client = CosmosDbHelper.GetDocumentClient())
     {
         await client.CreateDatabaseIfNotExistsAsync(new Database
         {
             Id = Constants.CosmosDb.DatabaseId
         });
     }
 }
        public async Task <ActionResult> AzureActiveDirectoryLateralMovement()
        {
            var azureActiveDirectoryApplication = new Models.AzureActiveDirectoryApplication(HttpContext);
            var tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            await CosmosDbHelper.InitializeCosmosDb(tenantID);

            var outputView = await azureActiveDirectoryApplication.RunAzureActiveDirectoryApplication();

            return(View(outputView));
        }
        public void Initialise()
        {
            config = CosmosDbClientConfig.CreateDocDbConfigFromAppConfig(System.Configuration.ConfigurationManager.AppSettings);

            testContext =
                DocumentCollectionContextFactory.CreateCollectionContext(
                    config
                    );

            doc = CosmosDbHelper.CreateDocument(testContext, CreateWishList());
        }
예제 #8
0
        public async Task RunTests()
        {
            if (Parallelism < 1)
                Parallelism = 1;
            if (NumberOfQueryResults < 1)
                NumberOfQueryResults = 1;

            Writes = await RunCreateTest("Writes", NumberOfWrites);
            Query = await RunTest("Query", async () => articles = await CosmosDbHelper.ExecuteQueryAsync<Article>($"SELECT TOP {NumberOfQueryResults} * FROM {Article.CollectionId} AS c", Article.CollectionId, true), NumberOfQueryResults);
            RandomReads = await RunRandomReadTest("RandomReads", NumberOfRandomReads, articles);
            Upserts = await RunUpsertTest("Upserts", NumberOfUpserts, articles);
        }
예제 #9
0
        public async Task <HttpResponseMessage> VSTSAuth([FromQuery] string code, [FromQuery] string state)
        {
            var queryParams = state;
            var cfbytes     = WebEncoders.Base64UrlDecode(queryParams);
            var _cf         = JsonConvert.DeserializeObject <ConversationReference>(System.Text.Encoding.UTF8.GetString(cfbytes));

            TokenModel token = new TokenModel();
            String     error = null;

            if (!String.IsNullOrEmpty(code))
            {
                error = PerformTokenRequest(GenerateRequestPostData(code), out token);
                if (!String.IsNullOrEmpty(error))
                {
                    Debug.WriteLine(error);
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }

            CosmosDbHelper cdh = new CosmosDbHelper("VSTSDb", "VSTSToken");

            BotAdapter ba = new BotFrameworkAdapter(Environment.GetEnvironmentVariable("MicrosoftAppId"), Environment.GetEnvironmentVariable("MicrosoftAppPassword"));

            await ba.ContinueConversation(Environment.GetEnvironmentVariable("MicrosoftAppId"), _cf, async (context) =>
            {
                // Write token to the database associated with a specific user
                var usertoken = new
                {
                    userId = context.Activity.From.Id,
                    token
                };

                try
                {
                    var document = await cdh.docClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("VSTSDb", "VSTSToken"), usertoken);
                }
                catch (Exception ex)
                {
                    // TODO: More logic for what to do on a failed write can be added here
                    await context.SendActivity("exception in storing token");
                    throw ex;
                }

                await context.SendActivity("You are logged in VSTS!");
            });


            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
예제 #10
0
        public async Task <ActionResult> Diagnostics(string button)
        {
            button = button.ToLower();
            if (button == "delete")
            {
                await CosmosDbHelper.DeleteDatabaseAsync();

                ViewBag.Message = "Database deleted! It will be recreated next time you restart the application.";
            }
            if (button == "reset")
            {
                //await DbHelper.DeleteCollection(Article.CollectionId);
                //await DbHelper.CreateCollection(Article.CollectionId, Article.PartitionKey);
                await CosmosDbHelper.DeleteAllDocumentsAsync(Article.CollectionId);

                await Article.Create(await Article.GetSampleArticles());

                ViewBag.Message = "Articles deleted and recreated.";
            }

            var diagnostics = new DiagnosticsModel();

            return(View(diagnostics));
        }
        public OrderController(IOptions <CosmosSettings> settings)
        {
            CosmosSettings cosmosSettings = settings.Value;

            cosmosDbHelper = new CosmosDbHelper(cosmosSettings);
        }
예제 #12
0
        public async Task OnTurn(ITurnContext context)
        {
            if (context.Activity.Type is ActivityTypes.Message)
            {
                var message = context.Activity;

                //check mentions in the message -> MSTEAMS
                if (context.Activity.ChannelId == "msteams")
                {
                    Mention[] m = context.Activity.GetMentions();

                    for (int i = 0; i < m.Length; i++)
                    {
                        if (m[i].Mentioned.Id == context.Activity.Recipient.Id)
                        {
                            //Bot is in the @mention list.
                            //The below example will strip the bot name out of the message, so you can parse it as if it wasn't included. Note that the Text object will contain the full bot name, if applicable.
                            if (m[i].Text != null)
                            {
                                message.Text = message.Text.Replace(m[i].Text, "").Trim();
                            }
                        }
                    }
                }

                //when user ask about info in VSTS, he/she should be authenticated
                if (message.AsMessageActivity().Text == "vsts")
                {
                    //check in the DB if there is a valid token for the specific user
                    CosmosDbHelper cdh = new CosmosDbHelper("VSTSDb", "VSTSToken");
                    var            tk  = await cdh.ReadTokenFromDB("VSTSDb", "VSTSToken", context.Activity.From.Id);

                    if (tk != null)
                    {
                        //TODO: query VSTS to retrieve information
                        await context.SendActivity("Here there will be the result of a custom query...");
                    }
                    else
                    {
                        //if there isn't a token for the user get ConversationReference
                        var cf = TurnContext.GetConversationReference(context.Activity);

                        //and generate the URL for user authentication
                        var      url = AuthenticationHelper.GenerateAuthorizeUrl(cf);
                        Activity replyToConversation = message.CreateReply();
                        replyToConversation.Attachments = new List <Attachment>();

                        List <CardAction> cardButtons = new List <CardAction>();

                        CardAction plButton = new CardAction()
                        {
                            Value = url,
                            Type  = "openUrl",
                            Title = "Connect"
                        };

                        cardButtons.Add(plButton);

                        SigninCard plCard = new SigninCard(text: "You need to authorize me", buttons: cardButtons);

                        Attachment plAttachment = plCard.ToAttachment();
                        replyToConversation.Attachments.Add(plAttachment);

                        var reply = await context.SendActivity(replyToConversation);

                        await context.SendActivity(url);
                    }
                }
                else
                {
                    // send the information about the Activity, at the moment
                    //TODO: manage other features for the bot
                    await context.SendActivity(
                        $"ConversationId " + context.Activity.Conversation.Id + "\n" +
                        "BotId " + context.Activity.Recipient.Id + "\n" +
                        "BotName " + context.Activity.Name + "\n" +
                        "tenantId " + context.Activity.ChannelData);
                }
            }
        }
예제 #13
0
 public void Document_Read_Success()
 {
     WishList Doc = CosmosDbHelper.ReadDocument <WishList>(testContext, this.doc.Id, this.doc.CustomerId);
 }
예제 #14
0
 public void Teardown()
 {
     CosmosDbHelper.DeleteDocument(this.testContext, this.doc, this.doc.CustomerId);
 }