private static MediaUrlData ParseRenderUrl(string relativeUrl, out UrlKind urlKind) { try { var queryParameters = new UrlBuilder(relativeUrl).GetQueryParameters(); IMediaFile mediaFile = MediaUrlHelper.GetFileFromQueryString(queryParameters); Verify.IsNotNull(mediaFile, "failed to get file from a query string"); urlKind = UrlKind.Renderer; queryParameters.Remove("id"); queryParameters.Remove("i"); queryParameters.Remove("src"); queryParameters.Remove("store"); return(new MediaUrlData { MediaId = mediaFile.Id, MediaStore = mediaFile.StoreId, QueryParameters = queryParameters }); } catch (Exception) { urlKind = UrlKind.Undefined; return(null); } }
private IWatermarkConfiguration GetWatermarkConfigOrDefault(NameValueCollection queryString) { try { IMediaFile mediaFile = MediaUrlHelper.GetFileFromQueryString(queryString); using (var connection = new DataConnection()) { IQueryable <IWatermarkConfiguration> configs = connection.Get <IWatermarkConfiguration>(); foreach (IWatermarkConfiguration config in configs) { IMediaFileFolder mediaFolder = connection.Get <IMediaFileFolder>().SingleOrDefault(mf => mf.KeyPath == config.TargetMediaFolderPath); if (mediaFolder != null && mediaFile.CompositePath.StartsWith(mediaFolder.CompositePath)) { return(config); } } } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } return(null); }
public string NewMediaObject(FileData mediaObject) { var mediaFile = new WorkflowMediaFile { FileName = mediaObject.name, Title = mediaObject.name, Culture = DataLocalizationFacade.DefaultLocalizationCulture.Name, Length = mediaObject.bits.Count(), MimeType = MimeTypeInfo.GetCanonical(mediaObject.type) }; if (mediaFile.MimeType == MimeTypeInfo.Default) { mediaFile.MimeType = MimeTypeInfo.GetCanonicalFromExtension(Path.GetExtension(mediaFile.FileName)); } using (Stream readStream = new MemoryStream(mediaObject.bits)) { using (Stream writeStream = mediaFile.GetNewWriteStream()) { readStream.CopyTo(writeStream); } } string folderPath = string.Format("/Blog/{0}/{1:yyyy-MM-dd}", Author.Name, DateTime.Now); mediaFile.FolderPath = ForceGetMediaFolderPath(folderPath); var addedFile = DataFacade.AddNew <IMediaFile>(mediaFile); return(MediaUrlHelper.GetUrl(addedFile)); }
public void ProcessRequest(HttpContext context) { var functionName = (string)context.Request.RequestContext.RouteData.Values["function"]; var dataCulture = GetCurrentDataCulture(context); using (var data = new DataConnection()) { if (!data.Get <IFunctionRoute>().Any()) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } } IFunction function; if (!FunctionFacade.TryGetFunction(out function, functionName)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } using (var dataScope = new DataScope(DataScopeIdentifier.Public, dataCulture)) { var functionResult = FunctionFacade.Execute <object>(function, context.Request.QueryString); if (functionResult == null) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } var xhtmlDocument = functionResult as XhtmlDocument; if (xhtmlDocument != null) { PageRenderer.ExecuteEmbeddedFunctions(xhtmlDocument.Root, new FunctionContextContainer()); PageRenderer.NormalizeXhtmlDocument(xhtmlDocument); var xhtml = xhtmlDocument.ToString(); xhtml = PageUrlHelper.ChangeRenderingPageUrlsToPublic(functionResult.ToString()); xhtml = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(xhtml); context.Response.Write(xhtml); } else { context.Response.Write(functionResult.ToString()); if (functionResult is XNode && function.ReturnType != typeof(XhtmlDocument)) { context.Response.ContentType = "text/xml"; } } } }
/// <exclude /> public string GetResizedImageUrl(string storeId, Guid mediaId, ResizingOptions resizingOptions) { IMediaFile file = MediaUrlHelper.GetFileById(storeId, mediaId); if (file == null) { return(null); } string pathToFile = UrlUtils.Combine(file.FolderPath, file.FileName); pathToFile = RemoveForbiddenCharactersAndNormalize(pathToFile); // IIS6 doesn't have wildcard mapping by default, so removing image extension if running in "classic" app pool if (!HttpRuntime.UsingIntegratedPipeline) { int dotOffset = pathToFile.IndexOf(".", StringComparison.Ordinal); if (dotOffset >= 0) { pathToFile = pathToFile.Substring(0, dotOffset); } } string mediaStore = string.Empty; if (!storeId.Equals(DefaultMediaStore, StringComparison.InvariantCultureIgnoreCase)) { mediaStore = storeId + "/"; } var url = new UrlBuilder(UrlUtils.PublicRootPath + "/media/" + mediaStore + /* UrlUtils.CompressGuid(*/ mediaId /*)*/) { PathInfo = file.LastWriteTime != null ? "/" + GetDateTimeHash(file.LastWriteTime.Value.ToUniversalTime()) : string.Empty }; if (pathToFile.Length > 0) { url.PathInfo += pathToFile; } if (resizingOptions != null && !resizingOptions.IsEmpty) { return(url + "?" + resizingOptions); } return(url.ToString()); }
public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer) { var id = String.Empty; var title = String.Empty; var internalUrl = String.Empty; var publicUrl = String.Empty; var currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId; var mediaToken = actionToken as GetMediaLinkActionToken; if (mediaToken != null) { var file = mediaToken.File; id = file.Id.ToString(); title = file.FileName; internalUrl = MediaUrlHelper.GetUrl(file); publicUrl = MediaUrlHelper.GetUrl(file, false); } var pageToken = actionToken as GetPageLinkActionToken; if (pageToken != null) { var page = pageToken.Page; using (var data = new DataConnection(PublicationScope.Published)) { var publishedPage = data.Get <IPage>().SingleOrDefault(p => p.Id == page.Id); if (publishedPage != null) { page = publishedPage; } id = page.Id.ToString(); title = page.Title; internalUrl = PageUrls.BuildUrl(page, UrlKind.Internal); publicUrl = PageUrls.BuildUrl(page); } } ConsoleMessageQueueFacade.Enqueue(new MessageBoxMessageQueueItem { Title = title, Message = "Id: " + id + "\n\rInternal: " + internalUrl + "\n\rPublic url: " + publicUrl }, currentConsoleId); return(null); }
protected override void Render(HtmlTextWriter writer) { var markupBuilder = new StringBuilder(); using (var sw = new StringWriter(markupBuilder)) { base.Render(new HtmlTextWriter(sw)); } string xhtml = markupBuilder.ToString(); using (Profiler.Measure("Changing 'internal' page urls to 'public'")) { xhtml = PageUrlHelper.ChangeRenderingPageUrlsToPublic(xhtml); } using (Profiler.Measure("Changing 'internal' media urls to 'public'")) { xhtml = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(xhtml); } writer.Write(xhtml); }
private void WriteWatermarkImageToImage(IWatermarkConfiguration config, Graphics graphic) { IMediaFile originalMediaFile = MediaUrlHelper.GetFileFromQueryString(HttpContext.Current.Request.QueryString); IMediaFile imageFile; using (var conn = new DataConnection()) { imageFile = conn.Get <IMediaFile>().SingleOrDefault(i => i.KeyPath == config.WatermarkImageFilePath); } Image watermarkImage = Image.FromStream(imageFile.GetReadStream()); IEnumerable <PointF> positions = GetAllTextPositionByConfigFontAndImage(config, watermarkImage.Size, graphic); Size originalImageSize = GetImageSizeFromCacheOrFile(originalMediaFile); float widthRatio = graphic.VisibleClipBounds.Width / originalImageSize.Width; float heightRatio = graphic.VisibleClipBounds.Height / originalImageSize.Height; var watermarkSize = new SizeF(watermarkImage.Width * widthRatio, watermarkImage.Height * heightRatio); foreach (PointF position in positions) { graphic.DrawImage(watermarkImage, position.X, position.Y, watermarkSize.Width, watermarkSize.Height); } }
public override string Process(string str) { var document = XDocument.Parse(Regex.Replace(str, @"xmlns:(\w*)=""http://www.w3.org/1999/xhtml""", "")); //fix Media Urls foreach (var a in document.Descendants(Namespaces.Xhtml + "a")) { if (a.Attribute("href") != null) { var href = a.Attribute("href").Value; var re = new Regex(@"ShowMedia.ashx\?(.*)"); var match = re.Match(href); if (match.Success) { try { var querystring = HttpUtility.ParseQueryString(match.Groups[1].Value); a.SetAttributeValue("href", href.Replace("ShowMedia.ashx?", string.Format("ShowMedia.ashx/{0}?", Regex.Replace(MediaUrlHelper.GetFileFromQueryString(querystring).FileName, @"[^\w\d.]", "")))); } catch { } } } } ; //remove "noindex" elements foreach (var el in document.Descendants().Where(d => d.Attribute("class") != null && d.Attribute("class").Value.ToLower().Contains("noindex")).Reverse()) { el.Remove(); } return(document.ToString()); }
public void Import(string rssPath, Guid pageId) { using (var conn = new DataConnection(PublicationScope.Unpublished)) { var mapLinks = new Dictionary <string, string>(); var client = new WebClient(); XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(rssPath)); var feed = SyndicationFeed.Load(reader); reader.Close(); var links = feed.Links.Select(d => d.Uri.ToString()).ToList(); var defaultAuthor = DataFacade.GetData <Authors>().Select(d => d.Name).TheOneOrDefault() ?? "Anonymous"; var blogAuthor = feed.Authors.Select(d => d.Name).FirstOrDefault() ?? feed.ElementExtensions.ReadElementExtensions <string>("creator", "http://purl.org/dc/elements/1.1/").FirstOrDefault();; foreach (var item in feed.Items) { using (new DataScope(PublicationScope.Published)) { var itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime; foreach (var itemLink in item.Links) { mapLinks[itemLink.Uri.OriginalString] = BlogFacade.BuildBlogInternalPageUrl(itemDate, item.Title.Text, pageId); } } } foreach (var item in feed.Items) { try { var content = new XDocument(); string text = null; var itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime; if (text == null && item.Content != null) { var syndicationContent = item.Content as TextSyndicationContent; if (syndicationContent != null) { text = syndicationContent.Text; } } if (text == null) { text = item.ElementExtensions.ReadElementExtensions <string>("encoded", "http://purl.org/rss/1.0/modules/content/") .FirstOrDefault(); } if (text == null && item.Summary != null) { text = item.Summary.Text; } content = MarkupTransformationServices.TidyHtml(text).Output; //somewhere empty <title></title> created foreach (var title in content.Descendants(Namespaces.Xhtml + "title").ToList()) { if (string.IsNullOrWhiteSpace(title.Value)) { title.Remove(); } } foreach (var img in content.Descendants(Namespaces.Xhtml + "img")) { var src = img.GetAttributeValue("src"); if (!string.IsNullOrEmpty(src)) { foreach (var link in links) { if (src.StartsWith(link)) { var newImage = ImportMedia(src, string.Format(FolderFormat, itemDate, item.Title.Text)); if (newImage != null) { img.SetAttributeValue("src", MediaUrlHelper.GetUrl(newImage, true)); } break; } } } } foreach (var a in content.Descendants(Namespaces.Xhtml + "a")) { var href = a.GetAttributeValue("href"); if (!string.IsNullOrEmpty(href)) { foreach (var link in links) { if (href.StartsWith(link)) { if (mapLinks.ContainsKey(href)) { a.SetAttributeValue("href", mapLinks[href]); } else { var extension = Path.GetExtension(href).ToLower(); switch (extension) { case ".jpg": case ".png": case ".gif": case ".pdf": case ".doc": case ".docx": var newMedia = ImportMedia(href, string.Format(FolderFormat, itemDate, item.Title.Text)); a.SetAttributeValue("href", MediaUrlHelper.GetUrl(newMedia, true)); break; default: a.SetAttributeValue("href", new Uri(href).PathAndQuery); break; } } break; } } } } var blogItem = DataFacade.BuildNew <Entries>(); var match = Regex.Match(item.Id, @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b", RegexOptions.IgnoreCase); if (match.Success) { var id = Guid.Empty; Guid.TryParse(match.Groups[0].Value, out id); if (id != Guid.Empty && !DataFacade.GetData <Entries>(d => d.Id == id).Any()) { blogItem.Id = id; } } blogItem.Title = item.Title.Text; blogItem.PageId = pageId; blogItem.Teaser = string.Empty; var blogItemAuthor = item.Authors.Select(d => d.Name ?? d.Email).FirstOrDefault() ?? item.ElementExtensions.ReadElementExtensions <string>("creator", "http://purl.org/dc/elements/1.1/").FirstOrDefault(); blogItem.Author = ImportAuthor(blogItemAuthor ?? blogAuthor ?? defaultAuthor); var tagType = DataFacade.GetData <TagType>().FirstOrDefault(); if (tagType == null) { tagType = DataFacade.BuildNew <TagType>(); tagType.Name = "Categories"; DataFacade.AddNew(tagType); } foreach (var tag in item.Categories) { ImportTag(tag.Name, tagType.Id); } blogItem.Tags = string.Join(",", item.Categories.Select(d => d.Name)); blogItem.Content = content.ToString(); blogItem.Date = itemDate; blogItem.PublicationStatus = GenericPublishProcessController.Draft; blogItem = DataFacade.AddNew(blogItem); blogItem.PublicationStatus = GenericPublishProcessController.Published; DataFacade.Update(blogItem); //break; } catch (Exception ex) { Log.LogError("Import Blog", ex); } } //1st redirect var mapLinks2 = new Dictionary <string, string>(); foreach (var maplink in mapLinks.ToList()) { var request = (HttpWebRequest)WebRequest.Create(maplink.Key); request.AllowAutoRedirect = false; var response = (HttpWebResponse)request.GetResponse(); var location = response.Headers["Location"]; if (!string.IsNullOrWhiteSpace(location)) { location = new Uri(new Uri(maplink.Key), location).OriginalString; foreach (var link in links) { if (location.StartsWith(link)) { if (!mapLinks.ContainsKey(location)) { mapLinks[location] = maplink.Value; mapLinks2[location] = maplink.Value; } } } } } //2nd redirect foreach (var maplink in mapLinks2.ToList()) { var request = (HttpWebRequest)WebRequest.Create(maplink.Key); request.AllowAutoRedirect = false; var response = (HttpWebResponse)request.GetResponse(); var location = response.Headers["Location"]; if (!string.IsNullOrWhiteSpace(location)) { location = new Uri(new Uri(maplink.Key), location).OriginalString; foreach (var link in links) { if (location.StartsWith(link)) { if (!mapLinks.ContainsKey(location)) { mapLinks[location] = maplink.Value; } } } } } var mapFile = PathUtil.Resolve(@"~\App_Data\RequestUrlRemappings.xml"); var map = new XElement("RequestUrlRemappings"); if (File.Exists(mapFile)) { map = XElement.Load(mapFile); } map.Add(new XComment(" Imported Blog " + DateTime.Now)); map.Add( mapLinks.Select(d => new XElement("Remapping", new XAttribute("requestPath", new Uri(d.Key).PathAndQuery), new XAttribute("rewritePath", d.Value) )) ); map.Add(new XComment(" ")); map.Save(mapFile); } }
public override void ExecuteResult(ControllerContext context) { string markup; using (TimerProfilerFacade.CreateTimerProfiler()) { var page = PageRenderer.CurrentPage; var markupBuilder = new StringBuilder(); var sw = new StringWriter(markupBuilder); var output = new HtmlTextWriter(sw); IView view; using (Profiler.Measure("Resolving view for template")) { view = FindView(context).View; } var viewContext = new ViewContext(context, view, ViewData, TempData, output); view.Render(viewContext, output); markup = markupBuilder.ToString(); var xml = XDocument.Parse(markup); var functionContext = PageRenderer.GetPageRenderFunctionContextContainer(); functionContext = new FunctionContextContainer(functionContext, new Dictionary <string, object> { { "viewContext", viewContext } }); using (Profiler.Measure("Executing embedded functions")) { PageRenderer.ExecuteEmbeddedFunctions(xml.Root, functionContext); } using (Profiler.Measure("Resolving pagefields")) { PageRenderer.ResolvePageFields(xml, page); } var document = new XhtmlDocument(xml); using (Profiler.Measure("Normalizing html")) { PageRenderer.NormalizeXhtmlDocument(document); } PageRenderer.ResolveRelativePaths(document); PageRenderer.AppendC1MetaTags(page, document); using (Profiler.Measure("Resolving localized strings")) { LocalizationParser.Parse(document); } markup = document.ToString(); using (Profiler.Measure("Changing 'internal' page urls to 'public'")) { markup = PageUrlHelper.ChangeRenderingPageUrlsToPublic(markup); } using (Profiler.Measure("Changing 'internal' media urls to 'public'")) { markup = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(markup); } markup = _mvcContext.FormatXhtml(markup); } if (_mvcContext.ProfilingEnabled) { markup = _mvcContext.BuildProfilerReport(); context.HttpContext.Response.ContentType = "text/xml"; } context.HttpContext.Response.Write(markup); }