private Bitmap DownloadImage(string imageUrl, string basePath)
        {
            // non-url base path means embedded resource
            if (!UrlHelper.IsUrl(basePath))
            {
                string imagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", basePath, imageUrl);
                Bitmap image     = ResourceHelper.LoadAssemblyResourceBitmap(imagePath);
                if (image != null)
                {
                    return(image);
                }
                else
                {
                    throw new ArgumentException("Invalid Image Resource Path: " + imageUrl);
                }
            }
            else
            {
                // calculate the image url
                imageUrl = UrlHelper.UrlCombineIfRelative(basePath, imageUrl);

                // try to get the credentials context
                WinInetCredentialsContext credentialsContext = null;
                try
                {
                    credentialsContext = BlogClientHelper.GetCredentialsContext(_blogClient, _credentials, imageUrl);
                }
                catch (BlogClientOperationCancelledException)
                {
                }

                // download the image
                return(ImageHelper.DownloadBitmap(imageUrl, credentialsContext));
            }
        }
Ejemplo n.º 2
0
        public object[] FetchItems(IWin32Window owner)
        {
            object[] items = BlogClientHelper.PerformBlogOperationWithTimeout(_blogId, new BlogClientOperation(BlogFetchOperation), _timeoutMs) as object[];
            if (items != null)
            {
                return(items);
            }
            else
            {
                // see if we have default items available
                object[] defaultItems = new object[0];
                try
                {
                    using (Blog blog = new Blog(_blogId))
                        defaultItems = GetDefaultItems(blog);
                }
                catch { }

                // if we have default items then return them in preference to showing an error
                if (defaultItems.Length > 0)
                {
                    return(defaultItems);
                }
                else
                {
                    DisplayMessage.Show(MessageId.UnableToRetrieve, _fetchingText);
                    return(null);
                }
            }
        }
Ejemplo n.º 3
0
        public void DoPreloadWork()
        {
            ContentEditorProxy.ApplyInstalledCulture();
            SimpleHtmlParser.Create();
            BlogClientHelper.FormatUrl("", "", "", "");
            ContentEditor contentEditor = new ContentEditor(null, new Panel(), null, new BlogPostHtmlEditorControl.BlogPostHtmlEditorSecurityManager(), new ContentEditorProxy.ContentEditorTemplateStrategy(), MshtmlOptions.DEFAULT_DLCTL);

            contentEditor.Dispose();
        }
 private WinInetCredentialsContext CreateCredentialsContext(string url)
 {
     try
     {
         return(BlogClientHelper.GetCredentialsContext(_blogClient, _credentials, url));
     }
     catch (BlogClientOperationCancelledException)
     {
         return(null);
     }
 }
        private string DownloadManifestTemplate(IProgressHost progress, string manifestTemplateUrl)
        {
            try
            {
                // update progress
                progress.UpdateProgress(0, 100, Res.Get(StringId.ProgressDownloadingEditingTemplate));

                // process any parameters within the url
                string templateUrl = BlogClientHelper.FormatUrl(manifestTemplateUrl, _blogHomepageUrl, _blogAccount.PostApiUrl, _blogAccount.BlogId);

                // download the url
                using (StreamReader streamReader = new StreamReader(_blogClient.SendAuthenticatedHttpRequest(templateUrl, 20000, null).GetResponseStream()))
                    return(streamReader.ReadToEnd());
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception occurred while attempting to download template from " + manifestTemplateUrl + " :" + ex.ToString());
                return(null);
            }
            finally
            {
                progress.UpdateProgress(100, 100);
            }
        }
Ejemplo n.º 6
0
 public HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter)
 {
     return(BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, CreateAuthorizationFilter()));
 }
 public async Task <HttpResponseMessage> SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpAsyncRequestFilter filter)
 {
     return(await BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, await CreateAuthorizationFilter()));
 }
Ejemplo n.º 8
0
 public virtual HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter)
 {
     return(BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, CreateCredentialsFilter(requestUri)));
 }
Ejemplo n.º 9
0
 internal string FormatUrl(string url)
 {
     return(BlogClientHelper.FormatUrl(url, _homepageUrl, _postApiUrl, _hostBlogId));
 }
Ejemplo n.º 10
0
        private IBlogProviderButtonNotification GetButtonNotification()
        {
            string notificationUrl = String.Format(
                CultureInfo.InvariantCulture,
                "{0}?blog_id={1}&button_id={2}&image_url={3}",
                NotificationUrl,
                HttpUtility.UrlEncode(_hostBlogId),
                HttpUtility.UrlEncode(_buttonId),
                HttpUtility.UrlEncode(ImageUrl));

            // get the content
            HttpWebResponse response    = null;
            XmlDocument     xmlDocument = new XmlDocument();

            try
            {
                using (Blog blog = new Blog(_blogId))
                    response = blog.SendAuthenticatedHttpRequest(notificationUrl, 10000);

                // parse the results
                xmlDocument.Load(response.GetResponseStream());
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            // create namespace manager
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);

            nsmgr.AddNamespace("n", "http://schemas.microsoft.com/wlw/buttons/notification");

            // throw if the root element is not manifest
            if (xmlDocument.DocumentElement.LocalName.ToLower(CultureInfo.InvariantCulture) != "notification")
            {
                throw new ArgumentException("Not a valid writer button notification");
            }

            // polling interval
            int checkAgainMinutes = XmlHelper.NodeInt(xmlDocument.SelectSingleNode("//n:checkAgainMinutes", nsmgr), 0);

            if (checkAgainMinutes == 0)
            {
                throw new ArgumentException("You must specify a value for checkAgainMinutes");
            }
            TimeSpan pollingInterval = TimeSpan.FromMinutes(checkAgainMinutes);

            // notification text
            string notificationText = XmlHelper.NodeText(xmlDocument.SelectSingleNode("//n:text", nsmgr));

            // notification image
            Bitmap notificationImage    = null;
            string notificationImageUrl = XmlHelper.NodeText(xmlDocument.SelectSingleNode("//n:imageUrl", nsmgr));

            if (notificationImageUrl != String.Empty)
            {
                // compute the absolute url then allow parameter substitution
                notificationImageUrl = BlogClientHelper.GetAbsoluteUrl(notificationImageUrl, NotificationUrl);
                notificationImageUrl = BlogClientHelper.FormatUrl(notificationImageUrl, _homepageUrl, _postApiUrl, _hostBlogId);

                // try to download it (will use the cache if available)
                // note that failing to download it is a recoverable error, we simply won't show a notification image
                try
                {
                    // try to get a credentials context for the download
                    WinInetCredentialsContext credentialsContext = null;
                    try
                    {
                        credentialsContext = BlogClientHelper.GetCredentialsContext(_blogId, notificationImageUrl);
                    }
                    catch (BlogClientOperationCancelledException)
                    {
                    }

                    // execute the download
                    notificationImage = ImageHelper.DownloadBitmap(notificationImageUrl, credentialsContext);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Error downloading notification image: " + ex.ToString());
                }
            }

            // clear notification on click
            bool clearNotificationOnClick = XmlHelper.NodeBool(xmlDocument.SelectSingleNode("//n:resetOnClick", nsmgr), true);

            // return the notification
            return(new BlogProviderButtonNotification(pollingInterval, notificationText, notificationImage, clearNotificationOnClick));
        }
        public void ViewContent(Control parent, Point menuLocation, int alternativeLocation, IDisposable disposeWhenDone)
        {
            try
            {
                if (!WinInet.InternetConnectionAvailable)
                {
                    disposeWhenDone.Dispose();
                    DisplayMessage.Show(MessageId.InternetConnectionWarning);
                    return;
                }

                // track resource that need to be disposed
                _disposeWhenDone = disposeWhenDone;

                using (new WaitCursor())
                {
                    // if the user is holding the CTRL button down then invalidate the cache
                    bool forceResynchronize = (KeyboardHelper.GetModifierKeys() == Keys.Control);

                    // setup download options
                    int downloadOptions =
                        DLCTL.DLIMAGES |
                        DLCTL.NO_CLIENTPULL |
                        DLCTL.NO_BEHAVIORS |
                        DLCTL.NO_DLACTIVEXCTLS |
                        DLCTL.SILENT;
                    if (forceResynchronize)
                    {
                        downloadOptions |= DLCTL.RESYNCHRONIZE;
                    }

                    // determine cookies and/or network credentials
                    WinInetCredentialsContext credentialsContext = null;
                    try
                    {
                        credentialsContext = BlogClientHelper.GetCredentialsContext(_button.BlogId, _button.ContentUrl);
                    }
                    catch (BlogClientOperationCancelledException)
                    {
                        _disposeWhenDone.Dispose();
                        return;
                    }

                    // note that we have viewed the content
                    _button.RecordButtonClicked();

                    // create the form and position it
                    BrowserMiniForm form = new BrowserMiniForm(_button.ContentQueryUrl, downloadOptions, credentialsContext);
                    form.StartPosition = FormStartPosition.Manual;
                    form.Size          = _button.ContentDisplaySize;
                    if (!Screen.FromPoint(menuLocation).Bounds.Contains(menuLocation.X + form.Width, menuLocation.Y))
                    {
                        menuLocation.X = alternativeLocation - form.Width;
                    }
                    form.Location = new Point(menuLocation.X + 1, menuLocation.Y);

                    // subscribe to close event for disposal
                    form.Closed += new EventHandler(form_Closed);

                    // float above parent if we have one
                    IMiniFormOwner miniFormOwner = parent.FindForm() as IMiniFormOwner;
                    if (miniFormOwner != null)
                    {
                        form.FloatAboveOwner(miniFormOwner);
                    }

                    // show the form
                    form.Show();
                }
            }
            catch
            {
                disposeWhenDone.Dispose();
                throw;
            }
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Currently sends an UNAUTHENTICATED HTTP request.
 /// If a static site requires authentication, this may be implemented here later.
 /// </summary>
 /// <param name="requestUri"></param>
 /// <param name="timeoutMs"></param>
 /// <param name="filter"></param>
 /// <returns></returns>
 public HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter)
 => BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, (HttpWebRequest request) => {});
        private WriterEditingManifest(WriterEditingManifestDownloadInfo downloadInfo, XmlDocument xmlDocument, IBlogClient blogClient, IBlogCredentialsAccessor credentials)
        {
            // record blog client and credentials
            _blogClient  = blogClient;
            _credentials = credentials;

            // record download info
            if (UrlHelper.IsUrl(downloadInfo.SourceUrl))
            {
                _downloadInfo = downloadInfo;
            }

            // only process an xml document if we got one
            if (xmlDocument == null)
            {
                return;
            }

            // create namespace manager
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);

            nsmgr.AddNamespace("m", "http://schemas.microsoft.com/wlw/manifest/weblog");

            // throw if the root element is not manifest
            if (xmlDocument.DocumentElement.LocalName.ToUpperInvariant() != "MANIFEST")
            {
                throw new ArgumentException("Not a valid writer editing manifest");
            }

            // get button descriptions
            _buttonDescriptions = new IBlogProviderButtonDescription[] { };
            XmlNode buttonsNode = xmlDocument.SelectSingleNode("//m:buttons", nsmgr);

            if (buttonsNode != null)
            {
                ArrayList buttons = new ArrayList();

                foreach (XmlNode buttonNode in buttonsNode.SelectNodes("m:button", nsmgr))
                {
                    try
                    {
                        // id
                        string id = XmlHelper.NodeText(buttonNode.SelectSingleNode("m:id", nsmgr));
                        if (id == String.Empty)
                        {
                            throw new ArgumentException("Missing id field");
                        }

                        // title
                        string description = XmlHelper.NodeText(buttonNode.SelectSingleNode("m:text", nsmgr));
                        if (description == String.Empty)
                        {
                            throw new ArgumentException("Missing text field");
                        }

                        // imageUrl
                        string imageUrl = XmlHelper.NodeText(buttonNode.SelectSingleNode("m:imageUrl", nsmgr));
                        if (imageUrl == String.Empty)
                        {
                            throw new ArgumentException("Missing imageUrl field");
                        }

                        // download the image
                        Bitmap image = DownloadImage(imageUrl, downloadInfo.SourceUrl);

                        // clickUrl
                        string clickUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode("m:clickUrl", nsmgr)), downloadInfo.SourceUrl);

                        // contentUrl
                        string contentUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode("m:contentUrl", nsmgr)), downloadInfo.SourceUrl);

                        // contentDisplaySize
                        Size contentDisplaySize = XmlHelper.NodeSize(buttonNode.SelectSingleNode("m:contentDisplaySize", nsmgr), Size.Empty);

                        // button must have either clickUrl or hasContent
                        if (clickUrl == String.Empty && contentUrl == String.Empty)
                        {
                            throw new ArgumentException("Must either specify a clickUrl or contentUrl");
                        }

                        // notificationUrl
                        string notificationUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode("m:notificationUrl", nsmgr)), downloadInfo.SourceUrl);

                        // add the button
                        buttons.Add(new BlogProviderButtonDescription(id, imageUrl, image, description, clickUrl, contentUrl, contentDisplaySize, notificationUrl));
                    }
                    catch (Exception ex)
                    {
                        // buttons fail silently and are not "all or nothing"
                        Trace.WriteLine("Error occurred reading custom button description: " + ex.Message);
                    }
                }

                _buttonDescriptions = buttons.ToArray(typeof(IBlogProviderButtonDescription)) as IBlogProviderButtonDescription[];
            }

            // get options
            _optionOverrides = new Hashtable();
            AddOptionsFromNode(xmlDocument.SelectSingleNode("//m:weblog", nsmgr), _optionOverrides);
            AddOptionsFromNode(xmlDocument.SelectSingleNode("//m:options", nsmgr), _optionOverrides);
            AddOptionsFromNode(xmlDocument.SelectSingleNode("//m:apiOptions[@name='" + _blogClient.ProtocolName + "']", nsmgr), _optionOverrides);
            XmlNode defaultViewNode = xmlDocument.SelectSingleNode("//m:views/m:default", nsmgr);

            if (defaultViewNode != null)
            {
                _optionOverrides["defaultView"] = XmlHelper.NodeText(defaultViewNode);
            }

            // separate out client type
            const string CLIENT_TYPE = "clientType";

            if (_optionOverrides.Contains(CLIENT_TYPE))
            {
                string type = _optionOverrides[CLIENT_TYPE].ToString();
                if (ValidateClientType(type))
                {
                    _clientType = type;
                }
                _optionOverrides.Remove(CLIENT_TYPE);
            }

            // separate out image
            const string IMAGE_URL = "imageUrl";

            _image = GetImageBytes(IMAGE_URL, _optionOverrides, downloadInfo.SourceUrl, new Size(16, 16));
            _optionOverrides.Remove(IMAGE_URL);

            // separate out watermark image
            const string WATERMARK_IMAGE_URL = "watermarkImageUrl";

            _watermark = GetImageBytes(WATERMARK_IMAGE_URL, _optionOverrides, downloadInfo.SourceUrl, new Size(84, 84));
            _optionOverrides.Remove(WATERMARK_IMAGE_URL);

            // get templates
            XmlNode webLayoutUrlNode = xmlDocument.SelectSingleNode("//m:views/m:view[@type='WebLayout']/@src", nsmgr);

            if (webLayoutUrlNode != null)
            {
                string webLayoutUrl = XmlHelper.NodeText(webLayoutUrlNode);
                if (webLayoutUrl != String.Empty)
                {
                    _webLayoutUrl = BlogClientHelper.GetAbsoluteUrl(webLayoutUrl, downloadInfo.SourceUrl);
                }
            }
            XmlNode webPreviewUrlNode = xmlDocument.SelectSingleNode("//m:views/m:view[@type='WebPreview']/@src", nsmgr);

            if (webPreviewUrlNode != null)
            {
                string webPreviewUrl = XmlHelper.NodeText(webPreviewUrlNode);
                if (webPreviewUrl != String.Empty)
                {
                    _webPreviewUrl = BlogClientHelper.GetAbsoluteUrl(webPreviewUrl, downloadInfo.SourceUrl);
                }
            }
        }
Ejemplo n.º 14
0
 public virtual async Task <HttpResponseMessage> SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpAsyncRequestFilter filter)
 {
     return(await BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, await CreateCredentialsFilter(requestUri)));
 }