コード例 #1
0
        public async Async.Task OneNoteAddPageWithMultipart()
        {
            try
            {
                string title    = "OneNoteAddPageMultipart test created this";
                string htmlBody = $@"<!DOCTYPE html><html><head><title>{title}</title></head>
                                    <body>Generated from the test
                                        <p>
                                            <img src=""name:imageBlock1"" alt=""an image on the page"" width=""300"" />
                                        </p>
                                    </body></html>
";

                string boundary    = "MultiPartBoundary32541";
                string contentType = "multipart/form-data; boundary=" + boundary;

                // Create the presentation part.
                StringContent presentation = new StringContent(htmlBody);
                presentation.Headers.ContentDisposition      = new ContentDispositionHeaderValue("form-data");
                presentation.Headers.ContentDisposition.Name = "Presentation";
                presentation.Headers.ContentType             = new MediaTypeHeaderValue("text/html");

                StreamContent image;

                // Get an image stream.
                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                var buff = (byte[])converter.ConvertTo(Microsoft.Graph.Test.Properties.Resources.hamilton, typeof(byte[]));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))
                {
                    // Create the image part.
                    image = new StreamContent(ms);
                    image.Headers.ContentDisposition      = new ContentDispositionHeaderValue(@"form-data");
                    image.Headers.ContentDisposition.Name = "imageBlock1";
                    image.Headers.ContentType             = new MediaTypeHeaderValue("image/png");

                    // Put the multiparts together
                    MultipartContent multiPartContent = new MultipartContent("form-data", boundary);
                    multiPartContent.Add(presentation);
                    multiPartContent.Add(image);

                    // Get the multiPart stream and then send the request to add a page using the stream.
                    testPage = await graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().AddAsync(multiPartContent);
                }

                Assert.IsNotNull(testPage, "We didn't deserialize the OnenotePage object.");
                Assert.IsTrue(testPage.GetType() == typeof(OnenotePage), $"Expected a OnenotePage object. Actual type is {testPage.GetType().ToString()} ");
                StringAssert.Contains(htmlBody, testPage.Title, "Expected: title returned in the OneNotePage object is found in the source HTML. Actual: not found.");

                TestPageCleanUp();
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.Fail("Error code: {0}", e.Error.Code);
            }

            catch (Exception e)
            {
                Assert.Fail("Error code: {0}", e.Message);
            }
        }
コード例 #2
0
        public async Task <OnenotePage> CreateNotebookPage(
            string sectionId,
            string html,
            HttpClient httpClient = null)
        {
            httpClient = GetAuthenticatedHttpClient(httpClient);

            Uri Uri = new Uri($"https://graph.microsoft.com/v1.0/users/me/onenote/sections/{sectionId}/pages");

            HttpContent httpContent = new StringContent(html, System.Text.Encoding.UTF8, "application/xhtml+xml");

            var response = await httpClient.PostAsync(Uri, httpContent);

            var json = await response.Content.ReadAsStringAsync();

            OnenotePage page = null;

            try
            {
                page = JsonConvert.DeserializeObject <OnenotePage>(json);
            }
            catch (Exception)
            {
            }

            return(page);
        }
コード例 #3
0
        public async Task OneNoteAddPageWithMultipart()
        {
            try
            {
                string title    = "OneNoteAddPageMultipart test created this";
                string htmlBody = $@"<!DOCTYPE html><html><head><title>{title}</title></head>
                                    <body>Generated from the test
                                        <p>
                                            <img src=""name:imageBlock1"" alt=""an image on the page"" width=""300"" />
                                        </p>
                                    </body></html>
";

                string boundary    = "MultiPartBoundary32541";
                string contentType = "multipart/form-data; boundary=" + boundary;

                // Create the presentation part.
                StringContent presentation = new StringContent(htmlBody);
                presentation.Headers.ContentDisposition      = new ContentDispositionHeaderValue("form-data");
                presentation.Headers.ContentDisposition.Name = "Presentation";
                presentation.Headers.ContentType             = new MediaTypeHeaderValue("text/html");

                StreamContent image;

                // Get an image stream.
                using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.Hamilton))
                {
                    // Create the image part.
                    image = new StreamContent(ms);
                    image.Headers.ContentDisposition      = new ContentDispositionHeaderValue(@"form-data");
                    image.Headers.ContentDisposition.Name = "imageBlock1";
                    image.Headers.ContentType             = new MediaTypeHeaderValue("image/png");

                    // Put the multiparts together
                    MultipartContent multiPartContent = new MultipartContent("form-data", boundary);
                    multiPartContent.Add(presentation);
                    multiPartContent.Add(image);

                    // Get the multiPart stream and then send the request to add a page using the stream.
                    testPage = await graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().AddAsync(multiPartContent);
                }

                Assert.NotNull(testPage);
                Assert.True(testPage.GetType() == typeof(OnenotePage));
                Assert.Contains(testPage.Title, htmlBody);

                TestPageCleanUp();
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.True(false, $"Error code: {e.Error.Code}");
            }

            catch (Exception e)
            {
                Assert.True(false, $"Error code: {e.Message}");
            }
        }
コード例 #4
0
        private async void UpdatePageUsingPlainHttp(OnenotePage page, List <ReplacementData> updateRequestData)
        {
            string graphURL  = "https://graph.microsoft.com/v1.0/users/" + currentUser.Id + "/onenote/pages/" + page.Id + "/content";
            string patchBody = preparePatchStringRequestBody(updateRequestData);

            sendHttpRequest(graphURL, patchBody);
            Console.WriteLine("page {0} is fixed up!", page.Title);
            logger.Info("page {0} is fixed up!", page.Title);
        }
コード例 #5
0
        public async Async.Task OneNoteAddPageHtmlWorkaround()
        {
            try
            {
                // Get the request URL for adding a page.
                string requestUrl = graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().RequestUrl;

                string title    = "OneNoteAddPageHtml test created this";
                string htmlBody = $"<!DOCTYPE html><html><head><title>{title}</title></head>" +
                                  "<body>Generated from the test</body></html> ";

                // Create the request message and add the content.
                HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                hrm.Content = new StringContent(htmlBody, System.Text.Encoding.UTF8, "text/html");

                // Authenticate (add access token) our HttpRequestMessage
                await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

                // Send the request and get the response.
                HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

                // Get the OneNote page that we created.
                if (response.IsSuccessStatusCode)
                {
                    // Deserialize into OneNotePage object.
                    var content = await response.Content.ReadAsStringAsync();

                    testPage = graphClient.HttpProvider.Serializer.DeserializeObject <OnenotePage>(content);

                    Assert.IsNotNull(testPage, "We didn't deserialize the OnenotePage object.");
                    StringAssert.Contains(testPage.Title, title, "Expected: title from the posted body matches the title in the OneNotePage object. That didn't happen");
                    Assert.IsNull(testPage.Content, "Expected: content property does not contain anything. Actual: there's an unexpected object in the content property.");

                    TestPageCleanUp();
                }
                else
                {
                    throw new ServiceException(
                              new Error
                    {
                        Code    = response.StatusCode.ToString(),
                        Message = await response.Content.ReadAsStringAsync()
                    });
                }
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.Fail("Error code: {0}", e.Error.Code);
            }

            catch (Exception e)
            {
                Assert.Fail("Error code: {0}", e.Message);
            }
        }
コード例 #6
0
        public static async Task <IOnenotePagesCollectionPage> GetMeAsyncPages(string bearer)
        {
            try
            {
                var allpages = await graphClient.Me.Onenote.Pages.Request().GetAsync();

                var firstPage = allpages[0];
                var newPage   = new OnenotePage();


                foreach (var aPage in allpages)
                {
                    string pageId     = aPage.Id;
                    string requestUrl = $"https://graph.microsoft.com/v1.0/me/onenote/pages/{pageId}/content";
                    string body       = @"[{
                            'target': 'body',
                            'action': 'append',
                            'position': 'after',
                            'content': '<div> added new </div>'}]";

                    var content            = new StringContent(body, System.Text.Encoding.UTF8, "application/json");
                    HttpRequestMessage req = new HttpRequestMessage()
                    {
                        Method     = new HttpMethod("PATCH"),
                        Content    = content,
                        RequestUri = new Uri(requestUrl)
                    };
                    HttpClient client = new HttpClient()
                    {
                        BaseAddress = new Uri(requestUrl),
                    };
                    client.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Bearer " + bearer);
                    HttpResponseMessage response = await client.SendAsync(req);



                    Stream pageContent = await graphClient.Me.Onenote.Pages[aPage.Id]
                                         .Content //
                                         .Request()
                                         .GetAsync();
                    StreamReader r = new StreamReader(pageContent);
                    string       t = r.ReadToEnd();
                    System.Diagnostics.Debug.WriteLine(t);
                }
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting signed-in user: {ex.Message}");
                return(null);
            }

            return(null);
        }
コード例 #7
0
        public async Task OneNoteAddPageHtmlWorkaround()
        {
            try
            {
                // Get the request URL for adding a page.
                string requestUrl = graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().RequestUrl;

                string title    = "OneNoteAddPageHtml test created this";
                string htmlBody = $"<!DOCTYPE html><html><head><title>{title}</title></head>" +
                                  "<body>Generated from the test</body></html> ";

                // Create the request message and add the content.
                HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                hrm.Content = new StringContent(htmlBody, System.Text.Encoding.UTF8, "text/html");

                // Send the request and get the response.
                HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

                // Get the OneNote page that we created.
                if (response.IsSuccessStatusCode)
                {
                    // Deserialize into OneNotePage object.
                    var content = await response.Content.ReadAsStringAsync();

                    testPage = graphClient.HttpProvider.Serializer.DeserializeObject <OnenotePage>(content);

                    Assert.NotNull(testPage);
                    Assert.Contains(testPage.Title, title);
                    Assert.Null(testPage.Content);

                    TestPageCleanUp();
                }
                else
                {
                    throw new ServiceException(
                              new Error
                    {
                        Code    = response.StatusCode.ToString(),
                        Message = await response.Content.ReadAsStringAsync()
                    });
                }
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.True(false, $"Error code: {e.Error.Code}");
            }

            catch (Exception e)
            {
                Assert.True(false, $"Error code: {e.Message}");
            }
        }
コード例 #8
0
ファイル: GraphPageFactory.cs プロジェクト: VicBirin/OneNote
 private async Task <Stream> LoadPageContent(OnenotePage page)
 {
     // load page content
     try
     {
         return(await client.Me.Onenote.Pages[page.Id].Content.Request().WithMaxRetry(10).GetAsync());
     }
     catch (Exception ex)
     {
         Thread.Sleep(5000);
         return(await client.Me.Onenote.Pages[page.Id].Content.Request().WithMaxRetry(10).GetAsync());
     }
 }
コード例 #9
0
        public static async Task CreatePageAsync(OnenotePage page)
        {
            var graphClient = GetAuthenticatedClient();

            string htmlBody = $"<!DOCTYPE html><html><head><title>{page.Title}</title></head>";

            byte[] byteArray = Encoding.ASCII.GetBytes(htmlBody);

            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                await graphClient.Me.Onenote.Sections[page.ParentSection.Id].Pages.Request()
                .AddAsync(stream, "text/html");
            }
        }
コード例 #10
0
        public async Async.Task OneNoteAddPageWithHtml()
        {
            string testString = ". Choose positive.";

            // Create the request body.
            string htmlBody = $"<!DOCTYPE html><html><head><title>OneNoteAddPageHtmlWithStream test created this{testString}</title></head>" +
                              "<body>Generated from the test with the partial</body></html> ";

            testPage = await graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().AddAsync(htmlBody, "text/html");

            Assert.IsNotNull(testPage, "EXPECTED: A OneNote page, ACTUAL: null");
            StringAssert.Contains(testPage.Title, testString, "EXPECTED: Test string from the create action in the title.");

            TestPageCleanUp();
        }
コード例 #11
0
 /// <summary>
 /// Update the navigation property pages in groups
 /// <param name="body"></param>
 /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
 /// </summary>
 public RequestInformation CreatePatchRequestInformation(OnenotePage body, Action<OnenotePageItemRequestBuilderPatchRequestConfiguration> requestConfiguration = default) {
     _ = body ?? throw new ArgumentNullException(nameof(body));
     var requestInfo = new RequestInformation {
         HttpMethod = Method.PATCH,
         UrlTemplate = UrlTemplate,
         PathParameters = PathParameters,
     };
     requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
     if (requestConfiguration != null) {
         var requestConfig = new OnenotePageItemRequestBuilderPatchRequestConfiguration();
         requestConfiguration.Invoke(requestConfig);
         requestInfo.AddRequestOptions(requestConfig.Options);
         requestInfo.AddHeaders(requestConfig.Headers);
     }
     return requestInfo;
 }
コード例 #12
0
 private async void UpdatePageUsingGraphClientApi(OnenotePage page, List <ReplacementData> updateRequestData)
 {
     try
     {
         using (var stream = new OneNoteMemoryStream(preparePatchStringRequestBody(updateRequestData)
                                                     .Select(c => (byte)c).ToArray()))
         {
             var pages = new OnenotePage()
             {
                 Content = stream
             };
             await client.Me.Onenote.Pages[page.Id].Request().UpdateAsync(pages);
         }
     }
     catch (Exception e)
     {
         logger.Error("Unable to fix the broken link in the page {0}. Exception: {1}", page.Title, e.Message);
     }
     logger.Info("page {0} is fixed up!", page.Title);
 }
コード例 #13
0
        public async Task OneNoteCreatePageWithHtmlStream()
        {
            string testString = ". Choose positive.";

            // Create the request body.
            string htmlBody = $"<!DOCTYPE html><html><head><title>OneNoteAddPageHtmlWithStream test created this{testString}</title></head>" +
                              "<body>Generated from the test with the partial</body></html> ";

            byte[] byteArray = Encoding.ASCII.GetBytes(htmlBody);

            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                // Create a OneNote page.
                testPage = await graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().AddAsync(stream, "text/html");
            }

            Assert.NotNull(testPage);
            Assert.Contains(testString, testPage.Title);

            TestPageCleanUp();
        }
コード例 #14
0
        /// <summary>
        /// Updates the content of the given OneNote page with the given HTML. Requires an authenticated GraphServiceClient.
        /// </summary>
        /// <param name="client">An authenticated GraphServiceClient containing the user's access token.</param>
        /// <param name="page">The page whose contents to update.</param>
        /// <param name="targetId">The ID of an element on the OneNote page that will be a container for the new content.</param>
        /// <param name="htmlContent">The new HTML content.</param>
        /// <returns></returns>
        public static async Task UpdatePage(GraphServiceClient client, OnenotePage page, string targetId, string htmlContent)
        {
            // The auto-generated OData client does not currently support updating a OnenotePage. Graph API expects a PATCH request
            // with a particular JSON body that does not correspond directly to the OnenotePage object. Here we need to get our hands
            // a little dirtier.
            string requestUri = client.Me.Onenote.Pages[page.Id].Content.Request().RequestUrl;

            // The expected body of the request is a JSON array of objects. This list will serialize to an array of one.
            List <OnenotePatchContentCommand> patchCommands = new List <OnenotePatchContentCommand>();

            patchCommands.Add(new OnenotePatchContentCommand()
            {
                Action  = OnenotePatchActionType.Replace,
                Target  = targetId,
                Content = htmlContent
            });

            // Create PATCH request
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri);

            // Serialize our list of one OnenotePatchContentCommand to JSON and set content type.
            request.Content = new StringContent(client.HttpProvider.Serializer.SerializeObject(patchCommands));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            // Adds the user's access token from the GraphServiceClient to the request.
            await client.AuthenticationProvider.AuthenticateRequestAsync(request);

            HttpResponseMessage response = await client.HttpProvider.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                throw new Microsoft.Graph.ServiceException(
                          new Error
                {
                    Code    = response.StatusCode.ToString(),
                    Message = await response.Content.ReadAsStringAsync()
                });
            }
        }
コード例 #15
0
        private async Task FixBrokenLinksInPage(OnenotePage page)
        {
            List <QueryOption> options = new List <QueryOption>
            {
                new QueryOption("includeIDs", "true")
            };

            Stream       content = await client.Me.Onenote.Pages[page.Id].Content.Request(options).GetAsync();
            StreamReader sr      = new StreamReader(content);

            pageCrawler = new PageContentCrawler();

            List <ReplacementData> updateRequestData = pageCrawler.GetBrokenLinkIds(sr.ReadToEnd(), "msft.spoppe.com", "microsoft.sharepoint-df.com");

            try
            {
                if (updateRequestData.Count > 0)
                {
                    Console.WriteLine("Broken Link found in page {0}. Number of Broken Links {1}", page.Title,
                                      updateRequestData.Count);

                    logger.Info("Broken Link found in page {0}. Number of Broken Links {1}", page.Title,
                                updateRequestData.Count);
                    //UpdatePageUsingGraphClientApi(page, updateRequestData)
                    UpdatePageUsingPlainHttp(page, updateRequestData);
                }
                else
                {
                    logger.Info("page {0} has no Broken Links! Proceeding to the Next Page", page.Title);
                }
            }
            catch (Exception e)
            {
                logger.Error("Exception Occured while sending explicit HttpRequest to update the page. Exception: " +
                             e.Message);
            }
        }
コード例 #16
0
        public async Async.Task OneNoteAddPageMultipartWorkaround()
        {
            try
            {
                // Get the request URL for adding a page.
                string requestUrl = graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().RequestUrl;
                string title      = "OneNoteAddPageMultipart test created this";
                string htmlBody   = $@"<!DOCTYPE html><html><head><title>{title}</title></head>
                                    <body>Generated from the test
                                        <p>
                                            <img src=""name:imageBlock1"" alt=""an image on the page"" width=""300"" />
                                        </p>
                                    </body></html>";

                string boundary    = "MultiPartBoundary32541";
                string contentType = "multipart/form-data; boundary=" + boundary;

                HttpResponseMessage response;

                // Create the presentation part.
                StringContent presentation = new StringContent(htmlBody);
                presentation.Headers.ContentDisposition      = new ContentDispositionHeaderValue("form-data");
                presentation.Headers.ContentDisposition.Name = "Presentation";
                presentation.Headers.ContentType             = new MediaTypeHeaderValue("text/html");

                StreamContent image;

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                var buff = (byte[])converter.ConvertTo(Microsoft.Graph.Test.Properties.Resources.hamilton, typeof(byte[]));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))
                {
                    // Create the image part.
                    image = new StreamContent(ms);
                    image.Headers.ContentDisposition      = new ContentDispositionHeaderValue(@"form-data");
                    image.Headers.ContentDisposition.Name = "imageBlock1";
                    image.Headers.ContentType             = new MediaTypeHeaderValue("image/png");

                    // Put the multiparts togeter
                    MultipartContent multiPartContent = new MultipartContent("form-data", boundary);
                    multiPartContent.Add(presentation);
                    multiPartContent.Add(image);

                    // Create the request message and add the content.
                    HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    hrm.Content = multiPartContent;

                    // Send the request and get the response.
                    response = await graphClient.HttpProvider.SendAsync(hrm);
                }

                // Get the OneNote page that we created.
                if (response.IsSuccessStatusCode)
                {
                    // Deserialize into OneNotePage object.
                    var content = await response.Content.ReadAsStringAsync();

                    testPage = graphClient.HttpProvider.Serializer.DeserializeObject <OnenotePage>(content);

                    Assert.IsNotNull(testPage, "We didn't deserialize the OnenotePage object.");
                    Assert.IsTrue(testPage.GetType() == typeof(OnenotePage), $"Expected a OnenotePage object. Actual type is {testPage.GetType().ToString()} ");
                    StringAssert.Contains(testPage.Title, title, "Expected: title matches, Actual: they don't match.");

                    TestPageCleanUp();
                }
                else
                {
                    throw new ServiceException(
                              new Error
                    {
                        Code    = response.StatusCode.ToString(),
                        Message = await response.Content.ReadAsStringAsync()
                    });
                }
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.Fail("Error code: {0}", e.Error.Code);
            }

            catch (Exception e)
            {
                Assert.Fail("Error code: {0}", e.Message);
            }
        }
コード例 #17
0
        public async Async.Task OneNoteAddPageHtmlWithStreamWorkaround()
        {
            try
            {
                // Get the request URL for adding a page. You don't have to use the request builder to
                // get the URL. We use it here for convenience.
                string requestUrl = graphClient.Me.Onenote.Sections[firstSectionID].Pages.Request().RequestUrl;

                // Create the request body.
                string title     = "OneNoteAddPageHtmlWithStream test created this";
                string htmlBody  = $"<!DOCTYPE html><html><head><title>{title}</title></head><body>Generated from the test</body></html> ";
                byte[] byteArray = Encoding.ASCII.GetBytes(htmlBody);

                StreamContent       body;
                HttpResponseMessage response;

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    // Create the stream body.
                    body = new StreamContent(stream);
                    body.Headers.ContentType = new MediaTypeHeaderValue("text/html");

                    // Create the request message and add the content.
                    HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    hrm.Content = body;

                    // Send the request and get the response.
                    response = await graphClient.HttpProvider.SendAsync(hrm);
                }

                // Get the OneNote page that we created.
                if (response.IsSuccessStatusCode)
                {
                    // Deserialize into OneNotePage object.
                    var content = await response.Content.ReadAsStringAsync();

                    testPage = graphClient.HttpProvider.Serializer.DeserializeObject <OnenotePage>(content);

                    Assert.IsNotNull(testPage, "We didn't deserialize the OnenotePage object.");
                    StringAssert.Contains(testPage.Title, title, "Expected: title matches, Actual: they don't match.");

                    TestPageCleanUp();
                }
                else
                {
                    throw new ServiceException(
                              new Error
                    {
                        Code    = response.StatusCode.ToString(),
                        Message = await response.Content.ReadAsStringAsync()
                    });
                }
            }
            catch (Microsoft.Graph.ServiceException e)
            {
                Assert.Fail("Error code: {0}", e.Error.Code);
            }

            catch (Exception e)
            {
                Assert.Fail("Error code: {0}", e.Message);
            }
        }
コード例 #18
0
        private async Task <DialogTurnResult> CheckTodaysEntry(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await PopulateStateObjects(stepContext);

            _graphHelper.Authenticate();

            var section      = stepContext.Values["Section"] as OnenoteSection;
            var contextId    = _discussionState.SignedInUserId;
            var currentPages = await _graphHelper.GetNotebookPagesInSection(section);

            DateTime entryDate = DateTime.Today;

            List <JournalPageMetadata> journalPages = new List <JournalPageMetadata>();
            int currentDay  = entryDate.Day;
            int daysInMonth = DateTime.DaysInMonth(entryDate.Year, entryDate.Month);
            int year        = entryDate.Year;
            int month       = entryDate.Month;
            List <JournalEntry> userEntries = DBHelper.GetJournalEntries(contextId,
                                                                         new DateTime(year, month, 1),
                                                                         new DateTime(year, month, daysInMonth));

            var invalidEntries = new KeyValuePair <string, List <string> >(
                contextId, new List <string>());

            // Remove pages that do not exist in the current pages collection
            for (int i = userEntries.Count - 1; i >= 0; i--)
            {
                var expectedPage = userEntries[i];
                if (!currentPages.Exists(ce => ce.Id == expectedPage.Id))
                {
                    invalidEntries.Value.Add(expectedPage.Id);
                    userEntries.Remove(expectedPage);
                }
            }
            if (invalidEntries.Value.Count > 0)
            {
                DBHelper.RemoveInvalidJournalEntries(invalidEntries);
            }

            var sentimentNeeded = userEntries.Where(j => {
                var cp = currentPages.First(p => p.Id == j.Id);
                return(
                    (j.Sentiment == null) ||
                    ((j.Sentiment != null) &&
                     (cp.LastModifiedDateTime > j.LastModified)));
            }).ToList();

            if (sentimentNeeded.Count > 0)
            {
                var sentimentDocuments = new Dictionary <String, TextDocumentInput[]>();
                foreach (var item in sentimentNeeded)
                {
                    var prompt = "Checking out your" +
                                 (item.Sentiment != null ? " updated" : "") +
                                 $" entry for {item.EntryDate.ToLongDateString()}";
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));

                    string content = await _graphHelper.GetNotebookPageContent(item.Id);

                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(content);
                    var body      = doc.DocumentNode.SelectSingleNode("//body");
                    var divHeader = doc.DocumentNode.SelectSingleNode("//div[@data-id='_default']");

                    var paragraphs     = new List <String>();
                    var paragraphNodes = divHeader.SelectNodes(".//p");
                    if (paragraphNodes?.Count > 0)
                    {
                        paragraphs.AddRange(paragraphNodes.Select(p => p.InnerText).ToArray());
                    }

                    var remainingHtml = body.InnerHtml.Replace(divHeader.OuterHtml, "");
                    var remainingDoc  = new HtmlDocument();
                    remainingDoc.LoadHtml(remainingHtml);

                    paragraphNodes = remainingDoc.DocumentNode.SelectNodes("//p");
                    if (paragraphNodes?.Count > 0)
                    {
                        paragraphs.AddRange(paragraphNodes.Select(p => p.InnerText).ToArray());
                    }

                    if (paragraphs.Count > 0)
                    {
                        var combinedText = System.Web.HttpUtility.HtmlDecode(String.Join("\n", paragraphs));
                        AddInputDocument(sentimentDocuments, item.Id, combinedText);
                        prompt = "That's new.. I'll have to consider what you wrote.";
                    }
                    else
                    {
                        prompt = "Nothing new for me to check out here!";
                    }
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));
                }

                if (sentimentDocuments.Count > 0)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Assessing what you wrote..."));
                }

                var sentimentResults = TextAnalyticsHelper.GetSentiment(sentimentDocuments);
                foreach (var entryKey in sentimentResults.Keys)
                {
                    var assessedPage = currentPages.First(e => e.Id == entryKey);
                    var lastModified = assessedPage.LastModifiedDateTime;
                    var ds           = sentimentResults[entryKey];
                    DBHelper.SaveJournalEntryAssessment(new JournalEntryAssessment
                    {
                        Id           = entryKey,
                        Sentiment    = ds,
                        LastModified = lastModified?.UtcDateTime
                    });

                    var prompt = $"Your entry on {assessedPage.Title} was {ds.Sentiment}";
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));
                }
            }

            var         monthMode   = false;
            var         createdPage = false;
            OnenotePage currentPage = null;
            var         pageId      = String.Empty;

            //Month mode
            if (monthMode)
            {
                for (int i = currentDay; i <= daysInMonth; i++)
                {
                    DateTime current = new DateTime(year, month, i);
                    if (!userEntries.Exists(e => e.EntryDate == current))
                    {
                        journalPages.Add(new JournalPageMetadata(current));
                    }
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                "Looking for today's journal entry"));

                var existingPage = userEntries.FirstOrDefault(e => e.EntryDate == entryDate);
                if (existingPage == null)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Hmmm... didn't find today's entry. Don't worry I'll create one for you."));

                    journalPages.Add(new JournalPageMetadata(entryDate));
                }
                else
                {
                    pageId = existingPage.Id;
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Found it!"));
                }
            }

            if (String.IsNullOrEmpty(pageId))
            {
                var weeks        = journalPages.GroupBy(p => p.Week).ToList();
                var pageTemplate = ResourceHelper
                                   .ReadManifestData <JournalingDialog>("JournalPageTemplate.htm");
                var headerPageTemplate = ResourceHelper
                                         .ReadManifestData <JournalingDialog>("JournalHeaderTemplate.htm");

                foreach (var grp in weeks)
                {
                    var headerPageTitle = $"Week {grp.Key}";
                    var headerEntryDate = entryDate.ToString("yyyy-MM-ddTHH:mm:ss.0000000");
                    Console.Write($" {headerPageTitle} ");
                    var headerPage = currentPages.FirstOrDefault(p => p.Title == headerPageTitle);

                    if (headerPage == null)
                    {
                        var headerHtml   = String.Format(headerPageTemplate, headerPageTitle, headerEntryDate);
                        var headerPageId = await _graphHelper.CreateNotebookPage(section.Id, headerHtml);

                        Console.WriteLine(headerPageId);
                    }
                    else
                    {
                        Console.WriteLine(headerPage.Id);
                    }

                    foreach (var item in grp)
                    {
                        var jp = DBHelper.GetJournalPrompt();

                        var pageTitle = $"{item.DayOfWeek} the {item.Day.AsOrdinal()}";
                        Console.Write($"\t{pageTitle} ");
                        var newEntryDate = item.EntryDate.ToString("yyyy-MM-ddTHH:mm:ss.0000000");

                        var prompt       = jp.Prompt;
                        var details      = jp.Details;
                        var promptSource = jp.Source;

                        var html = String.Format(pageTemplate, pageTitle, newEntryDate,
                                                 prompt, details, promptSource,
                                                 entryDate.Ticks, jp.SourceIndex, jp.PromptIndex);

                        currentPage = await _graphHelper.CreateNotebookPage(section.Id, html);

                        pageId      = currentPage.Id;
                        createdPage = true;
                        var je = new JournalEntry
                        {
                            UserContextId  = contextId,
                            Id             = pageId,
                            PromptSourceId = jp.SourceIndex,
                            PromptIndexId  = jp.PromptIndex,
                            EntryDate      = item.EntryDate
                        };
                        DBHelper.CreateJournalEntry(je);
                        await _graphHelper.UpdateNotebookPageLevel(pageId, 1);

                        await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                        "All done setting up today's entry for you!. Ping me when you want me to take a look."));

                        Console.WriteLine($"{pageId}");
                    }
                }
            }

            if ((currentPage == null) && !String.IsNullOrEmpty(pageId))
            {
                currentPage = await _graphHelper.GetNotebookPage(pageId);
            }
            AddUpdateStepContextValue(stepContext, "CurrentPage", currentPage);
            return(await stepContext.NextAsync(null, cancellationToken));
        }
コード例 #19
0
ファイル: OCRHelper.cs プロジェクト: john-guo/hodgepodge
 public OneNoteOCR()
 {
     try
     {
         _page = new OnenotePage(new OneNote.Application());
         _enableState = 1;
     }
     catch
     {
         _enableState = 2;
     }
 }
コード例 #20
0
        /// <summary>
        /// Returns a stream to the HTML content of the given OneNote page. Requires an authenticated GraphServiceClient.
        /// </summary>
        /// <param name="client">An authenticated GraphServiceClient containing the user's access token.</param>
        /// <param name="page">The page whose contents to return a stream to.</param>
        /// <param name="includeIds">If true, includes the OneNote element IDs in the content. False by default.</param>
        /// <returns>A stream to the HTML content of the page.</returns>
        public static async Task <System.IO.Stream> GetPageContent(GraphServiceClient client, OnenotePage page, bool includeIds = false)
        {
            List <QueryOption> queryOptions = new List <QueryOption>();

            if (includeIds)
            {
                queryOptions.Add(new QueryOption("includeIDs", "true"));
            }

            return(await client.Me.Onenote.Pages[page.Id].Content.Request(queryOptions).GetAsync());
        }