RickStrahl / MarkdownMonster

An extensible Markdown Editor, Viewer and Weblog Publisher for Windows
https://markdownmonster.west-wind.com
Other
1.58k stars 236 forks source link

MetaWeblog Addin Error Message Display #723

Closed shawnwildermuth closed 3 years ago

shawnwildermuth commented 3 years ago

When posting, the error messagebox isn't correctly parented so it goes away. I would have done a PR but I can't get my fork to build and test. But this is how I tried to test it:

        public async Task<bool> SendPost(WeblogInfo weblogInfo, bool sendAsDraft = false, WeblogForm parent)
        {
            var editor = Model.ActiveEditor;
            if (editor == null)
                return false;

            var doc = editor.MarkdownDocument;

            WeblogModel.ActivePost = new Post()
            {
                DateCreated = DateTime.Now
            };

            // start by retrieving the current Markdown from the editor
            string markdown = editor.MarkdownDocument.CurrentText;

            // Retrieve Meta data from post and clean up the raw markdown
            // so we render without the config data
            var meta = WeblogPostMetadata.GetPostConfigFromMarkdown(markdown, WeblogModel.ActivePost, weblogInfo);

            string html = doc.RenderHtml(meta.MarkdownBody, usePragmaLines: false);
            WeblogModel.ActivePost.Body = html;
            WeblogModel.ActivePost.PostId = meta.PostId;
            WeblogModel.ActivePost.PostStatus = meta.PostStatus;
            WeblogModel.ActivePost.Permalink = meta.Permalink;

            // Custom Field Processing:
            // Add custom fields from existing post
            // then add or update our custom fields
            var customFields = new Dictionary<string, CustomField>();

            // load existing custom fields from post online if possible
            if (!string.IsNullOrEmpty(meta.PostId))
            {
                var existingPost = GetPost(meta.PostId, weblogInfo);
                if (existingPost != null && meta.CustomFields != null && existingPost.CustomFields != null)
                {
                    foreach (var kvp in existingPost.CustomFields)
                    {
                        if (!customFields.ContainsKey(kvp.Key))
                            AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value);
                    }
                }
            }
            // add custom fields from Weblog configuration
            if (weblogInfo.CustomFields != null)
            {
                foreach (var kvp in weblogInfo.CustomFields)
                {
                    AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value);
                }
            }
            // add custom fields from Meta data
            if (meta.CustomFields != null)
            {
                foreach (var kvp in meta.CustomFields)
                {
                    AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value.Value);
                }
            }

            if (!string.IsNullOrEmpty(markdown))
            {
                AddOrUpdateCustomField(customFields, "mt_markdown", markdown);
            }

            WeblogModel.ActivePost.CustomFields = customFields.Values.ToArray();

            var config = WeblogAddinConfiguration.Current;

            var kv = config.Weblogs.FirstOrDefault(kvl => kvl.Value.Name == meta.WeblogName);
            if (kv.Equals(default(KeyValuePair<string, WeblogInfo>)))
            {
                MessageBox.Show(parent,
                    "Invalid Weblog configuration selected.",
                    "Weblog Posting Failed",
                    MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return false;
            }
            weblogInfo = kv.Value;

            var type = weblogInfo.Type;
            if (type == WeblogTypes.Unknown)
                type = weblogInfo.Type;

            string previewUrl = weblogInfo.PreviewUrl;
            string basePath = Path.GetDirectoryName(doc.Filename);
            string postUrl = null;

            if (type == WeblogTypes.MetaWeblogApi || type == WeblogTypes.Wordpress)
            {
                MetaWebLogWordpressApiClient client;
                client = new MetaWebLogWordpressApiClient(weblogInfo);

                // if values are already configured don't overwrite them again
                client.DontInferFeaturedImage = meta.DontInferFeaturedImage;
                client.FeaturedImageUrl = meta.FeaturedImageUrl;
                client.FeatureImageId = meta.FeaturedImageId;

                var result = await Task.Run<bool>(() => client.PublishCompletePost(WeblogModel.ActivePost, basePath,
                    sendAsDraft, markdown));

                meta.FeaturedImageUrl = client.FeaturedImageUrl;
                meta.FeaturedImageId = client.FeatureImageId;

                //if (!client.PublishCompletePost(WeblogModel.ActivePost, basePath,
                //    sendAsDraft, markdown))
                if (!result)
                {
                    mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage);
                    MessageBox.Show(parent,
                        "Error sending post to Weblog: " + client.ErrorMessage,
                        mmApp.ApplicationName,
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                    return false;
                }

                var post = client.GetPost(WeblogModel.ActivePost.PostId);
                if (post != null)
                {
                    postUrl = post.Url;
                    meta.Permalink = post.Permalink;
                }
            }
            if (type == WeblogTypes.Medium)
            {
                var client = new MediumApiClient(weblogInfo);
                var post = client.PublishCompletePost(WeblogModel.ActivePost, basePath, sendAsDraft);
                if (post == null)
                {
                    mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage);
                    MessageBox.Show(parent,
                        client.ErrorMessage,
                        "Error Sending Post to Medium",
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                    return false;
                }

                // this is null
                postUrl = client.PostUrl;
            }

            if (type == WeblogTypes.LocalJekyll)
            {
                var pub = new LocalJekyllPublisher(meta, weblogInfo, Model.ActiveDocument.Filename);
                pub.PublishPost(false);

                if (!string.IsNullOrEmpty(weblogInfo.LaunchCommand))
                {
                    if (!pub.BuildAndLaunchSite())
                    {
                        ShowStatusError(pub.ErrorMessage);
                        return false;
                    }
                    previewUrl = null;
                    postUrl = pub.GetPostUrl(weblogInfo.PreviewUrl ?? "http://localhost:4000/{0}");
                }
            }

            meta.PostId = WeblogModel.ActivePost.PostId?.ToString();

            // retrieve the raw editor markdown
            markdown = editor.MarkdownDocument.CurrentText;
            meta.RawMarkdownBody = markdown;

            // add the meta configuration to it
            markdown = meta.SetPostYamlFromMetaData();

            // write it back out to editor
            editor.SetMarkdown(markdown, updateDirtyFlag: true, keepUndoBuffer: true);

            try
            {
                if (!string.IsNullOrEmpty(postUrl))
                    ShellUtils.GoUrl(postUrl);
                else if (!string.IsNullOrEmpty(previewUrl))
                {
                    var url = string.Format(previewUrl, WeblogModel.ActivePost.PostId);
                    ShellUtils.GoUrl(url);
                }
                else
                {
                    ShellUtils.GoUrl(new Uri(weblogInfo.ApiUrl).GetLeftPart(UriPartial.Authority));
                }
            }
            catch
            {
                mmApp.Log("Failed to display Weblog Url after posting: " +
                          weblogInfo.PreviewUrl ?? postUrl ?? weblogInfo.ApiUrl);
            }

            return true;
        }
RickStrahl commented 3 years ago

Sorry not sure what you're referring to in this huge block of code.

shawnwildermuth commented 3 years ago

My bad. Chanaged the signature to include the parent:

public async Task<bool> SendPost(WeblogInfo weblogInfo, bool sendAsDraft = false, WeblogForm parent)

Then I added the parent parameter to each of the MessageBox's to deal with the error window being parented by the OS instead of the App. For example:

MessageBox.Show(parent,
  "Invalid Weblog configuration selected.",
  "Weblog Posting Failed",
   MessageBoxButton.OK, MessageBoxImage.Exclamation);

I couldn't test it (or I would have done a PR) as I couldn't build and run the source code. (Any hints there would be great).

RickStrahl commented 3 years ago

Can you file a separate bug for the non-building?

Tests are integration tests so they won't run and not fail (paths and dependencies), but the project should build. Error info would be useful.

To be honest I haven't checked in some time to build clean, but not sure why that would fail now.

Thanks...

shawnwildermuth commented 3 years ago

Yup.

RickStrahl commented 3 years ago

I think we don't need the parameter. You can get the form from:

WeblogForm

// or
WebLogAddinModel.Addin.WeblogForm

I'll fix this here. Thanks.

Oddly I've never run into this particular problem and I tend to publish a lot (but maybe I don't get a lot of errors). When do you see this undercut happening?

shawnwildermuth commented 3 years ago

I always get errors when I setup a new machine and have to hunt for hte message box (as it's usually parented by the Desktop)