public virtual void DoTest(Blog blog, IBlogClient blogClient, XmlElement providerEl) { TestResultImpl results = new TestResultImpl(); DoTest(blog, blogClient, results); results.ForEach(delegate (string key, string value) { XmlElement optionsEl = (XmlElement)providerEl.SelectSingleNode("options"); if (optionsEl == null) { optionsEl = providerEl.OwnerDocument.CreateElement("options"); providerEl.AppendChild(optionsEl); } XmlElement el = (XmlElement)optionsEl.SelectSingleNode(key); if (el == null) { el = providerEl.OwnerDocument.CreateElement(key); optionsEl.AppendChild(el); } if (!el.HasAttribute("readonly", NAMESPACE_BLOGRUNNER)) { el.InnerText = value; } }); }
public BlogPostRegionLocatorStrategy(IBlogClient blogClient, BlogAccount blogAccount, IBlogCredentialsAccessor credentials, string blogHomepageUrl, PageDownloader pageDownloader) { _blogClient = blogClient; _blogAccount = blogAccount; _credentials = credentials; _blogHomepageUrl = blogHomepageUrl; _pageDownloader = pageDownloader; }
protected internal override void PreparePost(Blog blog, IBlogClient blogClient, OpenLiveWriter.Extensibility.BlogClient.BlogPost blogPost, ref bool? publish) { BlogPostCategory[] categories = blogClient.GetCategories(blog.BlogId); if (categories.Length < 2) throw new InvalidOperationException("Blog " + blog.HomepageUrl + " does not have enough categories for the SupportsMultipleCategories test to be performed"); BlogPostCategory[] newCategories = new BlogPostCategory[2]; newCategories[0] = categories[0]; newCategories[1] = categories[1]; blogPost.Categories = newCategories; }
public static WriterEditingManifest FromHomepage(LazyHomepageDownloader homepageDownloader, Uri homepageUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials) { if (homepageUri == null) return null; WriterEditingManifest editingManifest = null; try { // compute the "by-convention" url for the manifest string homepageUrl = UrlHelper.InsureTrailingSlash(UrlHelper.SafeToAbsoluteUri(homepageUri)); string manifestUrl = UrlHelper.UrlCombine(homepageUrl, "wlwmanifest.xml"); // test to see whether this url exists and has a valid manifest editingManifest = FromUrl(new Uri(manifestUrl), blogClient, credentials, false); // if we still don't have one then scan homepage contents for a link tag if (editingManifest == null) { string manifestLinkTagUrl = ScanHomepageContentsForManifestLink(homepageUri, homepageDownloader); if (manifestLinkTagUrl != null) { // test to see whether this url exists and has a valid manifest try { editingManifest = FromUrl(new Uri(manifestLinkTagUrl), blogClient, credentials, true); } catch (Exception ex) { Trace.WriteLine("Error attempting to download manifest from " + manifestLinkTagUrl + ": " + ex.ToString()); } } } } catch (Exception ex) { Trace.WriteLine("Unexpected exception attempting to discover manifest from " + UrlHelper.SafeToAbsoluteUri(homepageUri) + ": " + ex.ToString()); } // return whatever editing manifest we found return editingManifest; }
private WriterEditingManifest SafeDownloadEditingManifest() { WriterEditingManifest editingManifest = null; try { // create a blog client IBlogClient blogClient = CreateBlogClient(); // can we get one based on cached download info IBlogCredentialsAccessor credentialsToUse = (IncludeInsecureOperations || blogClient.IsSecure) ? _context.Credentials : null; if (_context.ManifestDownloadInfo != null) { string manifestUrl = _context.ManifestDownloadInfo.SourceUrl; if (UseManifestCache) { editingManifest = WriterEditingManifest.FromDownloadInfo(_context.ManifestDownloadInfo, blogClient, credentialsToUse, true); } else { editingManifest = WriterEditingManifest.FromUrl(new Uri(manifestUrl), blogClient, credentialsToUse, true); } } // if we don't have one yet then probe for one if (editingManifest == null) { editingManifest = WriterEditingManifest.FromHomepage(_homepageAccessor, new Uri(_context.HomepageUrl), blogClient, credentialsToUse); } } catch (Exception ex) { ReportException("attempting to download editing manifest", ex); } // return whatever we found return(editingManifest); }
public void RunTests(Provider provider, Blog blog, XmlElement providerEl) { using (new BlogClientUIContextSilentMode()) //supress prompting for credentials { TemporaryBlogCredentials credentials = new TemporaryBlogCredentials(); credentials.Username = blog.Username; credentials.Password = blog.Password; BlogCredentialsAccessor credentialsAccessor = new BlogCredentialsAccessor(Guid.NewGuid().ToString(), credentials); IBlogClient client = BlogClientManager.CreateClient(provider.ClientType, blog.ApiUrl, credentialsAccessor); if (blog.BlogId == null) { BlogInfo[] blogs = client.GetUsersBlogs(); if (blogs.Length == 1) { blog.BlogId = blogs[0].Id; credentialsAccessor = new BlogCredentialsAccessor(blog.BlogId, credentials); client = BlogClientManager.CreateClient(provider.ClientType, blog.ApiUrl, credentialsAccessor); } } foreach (Test test in tests) { try { Console.WriteLine("Running test " + test.ToString()); test.DoTest(blog, client, providerEl); } catch (Exception e) { Console.Error.WriteLine("Error: Test " + test.GetType().Name + " failed for provider " + provider.Name + ":"); Console.Error.WriteLine(e.ToString()); } } } }
public sealed override void DoTest(Blog blog, IBlogClient blogClient, ITestResults results) { BlogPost blogPost = new BlogPost(); bool? publish = null; PreparePost(blog, blogClient, blogPost, ref publish); string token = BlogUtil.ShortGuid; blogPost.Title = token + ":" + blogPost.Title; string etag; XmlDocument remotePost; string postId = blogClient.NewPost(blog.BlogId, blogPost, null, publish ?? true, out etag, out remotePost); BlogPost newPost = blogClient.GetPost(blog.BlogId, postId); HandleResult(newPost, results); if (postId != null && CleanUpPosts) blogClient.DeletePost(blog.BlogId, postId, false); }
protected internal abstract void PreparePost(Blog blog, IBlogClient blogClient, BlogPost blogPost, ref bool? publish);
private bool AttemptGenericAtomLinkDetection(string url, string html, bool preferredOnly) { const string GENERIC_ATOM_PROVIDER_ID = "D48F1B5A-06E6-4f0f-BD76-74F34F520792"; if (html == null) { return(false); } HtmlExtractor ex = new HtmlExtractor(html); if (ex .SeekWithin("<head>", "<body>") .SeekWithin("<link href rel='service' type='application/atomsvc+xml'>", "</head>") .Success) { IBlogProvider atomProvider = BlogProviderManager.FindProvider(GENERIC_ATOM_PROVIDER_ID); BeginTag bt = ex.Element as BeginTag; if (preferredOnly) { string classes = bt.GetAttributeValue("class"); if (classes == null) { return(false); } if (!Regex.IsMatch(classes, @"\bpreferred\b")) { return(false); } } string linkUrl = bt.GetAttributeValue("href"); Debug.WriteLine("Atom service link detected in the blog homepage"); _providerId = atomProvider.Id; _serviceName = atomProvider.Name; _clientType = atomProvider.ClientType; _blogName = string.Empty; _postApiUrl = GetAbsoluteUrl(url, linkUrl); IBlogClient client = BlogClientManager.CreateClient(atomProvider.ClientType, _postApiUrl, _credentials); client.VerifyCredentials(); _usersBlogs = client.GetUsersBlogs(); if (_usersBlogs.Length == 1) { _hostBlogId = _usersBlogs[0].Id; _blogName = _usersBlogs[0].Name; /* * if (_usersBlogs[0].HomepageUrl != null && _usersBlogs[0].HomepageUrl.Length > 0) * _homepageUrl = _usersBlogs[0].HomepageUrl; */ } // attempt to read the blog name from the homepage title if (_blogName == null || _blogName.Length == 0) { HtmlExtractor ex2 = new HtmlExtractor(html); if (ex2.Seek("<title>").Success) { _blogName = ex2.CollectTextUntil("title"); } } return(true); } return(false); }
public static WriterEditingManifest FromDownloadInfo(WriterEditingManifestDownloadInfo downloadInfo, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable) { if (downloadInfo == null) { return(null); } try { // if the manifest is not yet expired then don't try a download at all if (downloadInfo.Expires > DateTimeHelper.UtcNow) { return(new WriterEditingManifest(downloadInfo)); } // execute the download HttpWebResponse response = null; try { if (credentials != null) { response = blogClient.SendAuthenticatedHttpRequest(downloadInfo.SourceUrl, REQUEST_TIMEOUT, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); } else { response = HttpRequestHelper.SendRequest(downloadInfo.SourceUrl, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); } } catch (WebException ex) { // Not modified -- return ONLY an updated downloadInfo (not a document) HttpWebResponse errorResponse = ex.Response as HttpWebResponse; if (errorResponse != null && errorResponse.StatusCode == HttpStatusCode.NotModified) { return(new WriterEditingManifest( new WriterEditingManifestDownloadInfo( downloadInfo.SourceUrl, HttpRequestHelper.GetExpiresHeader(errorResponse), downloadInfo.LastModified, HttpRequestHelper.GetETagHeader(errorResponse)))); } else { throw; } } // read headers DateTime expires = HttpRequestHelper.GetExpiresHeader(response); DateTime lastModified = response.LastModified; string eTag = HttpRequestHelper.GetETagHeader(response); // read document using (Stream stream = response.GetResponseStream()) { XmlDocument manifestXmlDocument = new XmlDocument(); manifestXmlDocument.Load(stream); // return the manifest return(new WriterEditingManifest( new WriterEditingManifestDownloadInfo(downloadInfo.SourceUrl, expires, lastModified, eTag), manifestXmlDocument, blogClient, credentials)); } } catch (Exception ex) { if (expectedAvailable) { Trace.WriteLine("Error attempting to download manifest from " + downloadInfo.SourceUrl + ": " + ex.ToString()); } return(null); } }
public static WriterEditingManifest FromUrl(Uri manifestUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable) { return(FromDownloadInfo(new WriterEditingManifestDownloadInfo(UrlHelper.SafeToAbsoluteUri(manifestUri)), blogClient, credentials, expectedAvailable)); }
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); } }
public static WriterEditingManifest FromDownloadInfo(WriterEditingManifestDownloadInfo downloadInfo, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable) { if (downloadInfo == null) return null; try { // if the manifest is not yet expired then don't try a download at all if (downloadInfo.Expires > DateTimeHelper.UtcNow) return new WriterEditingManifest(downloadInfo); // execute the download HttpWebResponse response = null; try { if (credentials != null) response = blogClient.SendAuthenticatedHttpRequest(downloadInfo.SourceUrl, REQUEST_TIMEOUT, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); else response = HttpRequestHelper.SendRequest(downloadInfo.SourceUrl, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); } catch (WebException ex) { // Not modified -- return ONLY an updated downloadInfo (not a document) HttpWebResponse errorResponse = ex.Response as HttpWebResponse; if (errorResponse != null && errorResponse.StatusCode == HttpStatusCode.NotModified) { return new WriterEditingManifest( new WriterEditingManifestDownloadInfo( downloadInfo.SourceUrl, HttpRequestHelper.GetExpiresHeader(errorResponse), downloadInfo.LastModified, HttpRequestHelper.GetETagHeader(errorResponse))); } else throw; } // read headers DateTime expires = HttpRequestHelper.GetExpiresHeader(response); DateTime lastModified = response.LastModified; string eTag = HttpRequestHelper.GetETagHeader(response); // read document using (Stream stream = response.GetResponseStream()) { XmlDocument manifestXmlDocument = new XmlDocument(); manifestXmlDocument.Load(stream); // return the manifest return new WriterEditingManifest( new WriterEditingManifestDownloadInfo(downloadInfo.SourceUrl, expires, lastModified, eTag), manifestXmlDocument, blogClient, credentials); } } catch (Exception ex) { if (expectedAvailable) { Trace.WriteLine("Error attempting to download manifest from " + downloadInfo.SourceUrl + ": " + ex.ToString()); } return null; } }
public BlogServiceContentDestination(ILogger <BlogServiceContentDestination> logger, IBlogClient blogClient) { _logger = logger; _blogClient = blogClient; }
public TemporaryPostRegionLocatorStrategy(IBlogClient blogClient, BlogAccount blogAccount, IBlogCredentialsAccessor credentials, string blogHomepageUrl, PageDownloader pageDownloader, BlogPostRegionLocatorBooleanCallback promptForTempPost) : base(blogClient, blogAccount, credentials, blogHomepageUrl, pageDownloader) { this.containsBlogPosts = promptForTempPost; }
public sealed override void DoTest(Blog blog, IBlogClient blogClient, ITestResults results) { BlogPost blogPost = new BlogPost(); bool? publish = null; PreparePost(blogPost, ref publish); string token = BlogUtil.ShortGuid; blogPost.Title = token + ":" + blogPost.Title; string etag; XmlDocument remotePost; string postId = blogClient.NewPost(blog.BlogId, blogPost, null, publish ?? true, out etag, out remotePost); try { RetryUntilTimeout(TimeoutDuration, delegate { using (HttpWebResponse response = HttpRequestHelper.SendRequest(blog.HomepageUrl)) { using (Stream stream = response.GetResponseStream()) { string html = Encoding.ASCII.GetString(StreamHelper.AsBytes(stream)); if (html.Contains(token)) { HandleResult(html, results); return true; } Thread.Sleep(1000); return false; } } }); } catch (TimeoutException te) { if (!HandleTimeout(te, results)) throw; } if (postId != null && CleanUpPosts) blogClient.DeletePost(blog.BlogId, postId, false); }
public abstract void DoTest(Blog blog, IBlogClient blogClient, ITestResults results);
protected internal abstract void PreparePost(Blog blog, IBlogClient blogClient, BlogPost blogPost, ref bool?publish);
public static WriterEditingManifest FromUrl(Uri manifestUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable) { return FromDownloadInfo(new WriterEditingManifestDownloadInfo(UrlHelper.SafeToAbsoluteUri(manifestUri)), blogClient, credentials, expectedAvailable); }
public BlogClientController(string serviceUrl) { client = new BlogClient(serviceUrl); }
public RecentPostRegionLocatorStrategy(IBlogClient blogClient, BlogAccount blogAccount, IBlogCredentialsAccessor credentials, string blogHomepageUrl, PageDownloader pageDownloader) : base(blogClient, blogAccount, credentials, blogHomepageUrl, pageDownloader) { }
public BlogUtil(Blog blog, IBlogClient client) { this.blog = blog; this.client = client; }
/// <summary> /// Конструктор /// </summary> /// <param name="client" >Клиент получения данных</param> /// <param name="notificator">Сервис, позволяющий информировать пользователя</param> public BlogViewModel(IBlogClient client, IClientNotificator notificator) { blogClient = client; clientNotificator = notificator; }
public static WinInetCredentialsContext GetCredentialsContext(IBlogClient blogClient, IBlogCredentialsAccessor credentials, string url) { // determine cookies and/or network credentials CookieString cookieString = null; NetworkCredential credential = null; if (credentials != null && credentials.Username != String.Empty) { credential = new NetworkCredential(credentials.Username, credentials.Password); } if (cookieString != null || credential != null) return new WinInetCredentialsContext(credential, cookieString); else return null; }
public static WriterEditingManifest FromHomepage(LazyHomepageDownloader homepageDownloader, Uri homepageUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials) { if (homepageUri == null) { return(null); } WriterEditingManifest editingManifest = null; try { // compute the "by-convention" url for the manifest string homepageUrl = UrlHelper.InsureTrailingSlash(UrlHelper.SafeToAbsoluteUri(homepageUri)); string manifestUrl = UrlHelper.UrlCombine(homepageUrl, "wlwmanifest.xml"); // test to see whether this url exists and has a valid manifest editingManifest = FromUrl(new Uri(manifestUrl), blogClient, credentials, false); // if we still don't have one then scan homepage contents for a link tag if (editingManifest == null) { string manifestLinkTagUrl = ScanHomepageContentsForManifestLink(homepageUri, homepageDownloader); if (manifestLinkTagUrl != null) { // test to see whether this url exists and has a valid manifest try { editingManifest = FromUrl(new Uri(manifestLinkTagUrl), blogClient, credentials, true); } catch (Exception ex) { Trace.WriteLine("Error attempting to download manifest from " + manifestLinkTagUrl + ": " + ex.ToString()); } } } } catch (Exception ex) { Trace.WriteLine("Unexpected exception attempting to discover manifest from " + UrlHelper.SafeToAbsoluteUri(homepageUri) + ": " + ex.ToString()); } // return whatever editing manifest we found return(editingManifest); }
public object DetectSettings(IProgressHost progressHost) { using (_silentMode ? new BlogClientUIContextSilentMode() : null) { if (IncludeButtons || IncludeOptionOverrides || IncludeImages) { using (new ProgressContext(progressHost, 40, Res.Get(StringId.ProgressDetectingWeblogSettings))) { // attempt to download editing manifest WriterEditingManifest editingManifest = SafeDownloadEditingManifest(); if (editingManifest != null) { // always update the download info if (editingManifest.DownloadInfo != null) { _context.ManifestDownloadInfo = editingManifest.DownloadInfo; } // images if (IncludeImages) { // image if provided if (editingManifest.Image != null) { _context.Image = editingManifest.Image; } // watermark if provided if (editingManifest.Watermark != null) { _context.WatermarkImage = editingManifest.Watermark; } } // buttons if provided if (IncludeButtons && (editingManifest.ButtonDescriptions != null)) { _context.ButtonDescriptions = editingManifest.ButtonDescriptions; } // option overrides if provided if (IncludeOptionOverrides) { if (editingManifest.ClientType != null) { _context.ClientType = editingManifest.ClientType; } if (editingManifest.OptionOverrides != null) { _context.OptionOverrides = editingManifest.OptionOverrides; } } } } } using (new ProgressContext(progressHost, 40, Res.Get(StringId.ProgressDetectingWeblogCharSet))) { if (IncludeOptionOverrides && IncludeHomePageSettings) { DetectHomePageSettings(); } } IBlogClient blogClient = CreateBlogClient(); if (IncludeInsecureOperations || blogClient.IsSecure) { if (blogClient is ISelfConfiguringClient) { // This must happen before categories detection but after manifest!! ((ISelfConfiguringClient)blogClient).DetectSettings(_context, this); } // detect categories if (IncludeCategories) { using ( new ProgressContext(progressHost, 20, Res.Get(StringId.ProgressDetectingWeblogCategories))) { BlogPostCategory[] categories = SafeDownloadCategories(); if (categories != null) { _context.Categories = categories; } BlogPostKeyword[] keywords = SafeDownloadKeywords(); if (keywords != null) { _context.Keywords = keywords; } } } // detect favicon (only if requested AND we don't have a PNG already // for the small image size) if (IncludeFavIcon) { using (new ProgressContext(progressHost, 10, Res.Get(StringId.ProgressDetectingWeblogIcon))) { byte[] favIcon = SafeDownloadFavIcon(); if (favIcon != null) { _context.FavIcon = favIcon; } } } if (IncludeImageEndpoints) { Debug.WriteLine("Detecting image endpoints"); ITemporaryBlogSettingsDetectionContext tempContext = _context as ITemporaryBlogSettingsDetectionContext; Debug.Assert(tempContext != null, "IncludeImageEndpoints=true but non-temporary context (type " + _context.GetType().Name + ") was used"); if (tempContext != null) { tempContext.AvailableImageEndpoints = null; try { BlogInfo[] imageEndpoints = blogClient.GetImageEndpoints(); tempContext.AvailableImageEndpoints = imageEndpoints; Debug.WriteLine(imageEndpoints.Length + " image endpoints detected"); } catch (NotImplementedException) { Debug.WriteLine("Image endpoints not implemented"); } catch (Exception e) { Trace.Fail("Exception detecting image endpoints: " + e.ToString()); } } } } // completed progressHost.UpdateProgress(100, 100, Res.Get(StringId.ProgressCompletedSettingsDetection)); } return(this); }
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); } } }