Example #1
0
        public void CreateJS(ADZoneInfo adZoneInfo, IList <AdvertisementInfo> advertisementInfoList)
        {
            this.zoneInfo = adZoneInfo;
            StringBuilder builder = new StringBuilder(this.GetZoneJSTemplate());

            builder.Append("var ZoneAD_" + adZoneInfo.ZoneId + "=new ");
            builder.Append(string.Concat(new object[] { this.zoneConfig[adZoneInfo.ZoneType], "ZoneAD(\"ZoneAD_", adZoneInfo.ZoneId, "\");" }));
            for (int i = 0; i < advertisementInfoList.Count; i++)
            {
                this.advertisementInfo        = advertisementInfoList[i];
                this.advertisementInfo.ZoneId = adZoneInfo.ZoneId.ToString(CultureInfo.CurrentCulture);
                if (this.advertisementInfo.Passed && (this.advertisementInfo.Days >= 0))
                {
                    builder.Append(this.CreatAdvertisementJS());
                }
            }
            builder.Append(this.CreateADZoneJS());
            FileSystemObject.WriteFile(VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Server.MapPath("~/" + SiteConfig.SiteOption.AdvertisementDir)) + adZoneInfo.ZoneJSName, builder.ToString());
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PageRelativePathContextRegion"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        public PageRelativePathContextRegion(HttpContextBase context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.context      = context;
            this.originalPath = context.Request.AppRelativeCurrentExecutionFilePath;
            var originalWithSlash = VirtualPathUtility.AppendTrailingSlash(this.originalPath);

            bool?isFrontendPageEdit = context.Items["IsFrontendPageEdit"] as bool?;
            var  currentNode        = SiteMapBase.GetCurrentNode();

            if (currentNode != null && !(isFrontendPageEdit.HasValue && isFrontendPageEdit.Value))
            {
                var nodeUrl           = currentNode.Url.StartsWith("~/", StringComparison.Ordinal) ? RouteHelper.ResolveUrl(currentNode.Url, UrlResolveOptions.ApplicationRelative | UrlResolveOptions.AppendTrailingSlash) : currentNode.Url;
                var comparisonNodeUrl = nodeUrl.Replace("~", string.Empty);
                if (originalWithSlash.StartsWith(nodeUrl, StringComparison.OrdinalIgnoreCase))
                {
                    var newPath = originalWithSlash.Right(originalWithSlash.Length - nodeUrl.Length);

                    this.context.RewritePath("~/" + newPath);
                }
                else if (SystemManager.CurrentContext.CurrentSite.Cultures.Length > 1 && originalWithSlash.StartsWith($"~/{SystemManager.CurrentContext.Culture}/", StringComparison.OrdinalIgnoreCase) && originalWithSlash.Contains(comparisonNodeUrl))
                {
                    var newPath = originalWithSlash.Right(originalWithSlash.Length - nodeUrl.Length - SystemManager.CurrentContext.Culture.Name.Length - 1);

                    this.context.RewritePath("~/" + newPath);
                }
                else if (currentNode.IsHomePage() &&
                         RouteHelper.ResolveUrl(SystemManager.CurrentContext.CurrentSite.GetUri().AbsolutePath, UrlResolveOptions.ApplicationRelative | UrlResolveOptions.AppendTrailingSlash) == originalWithSlash)
                {
                    // The request is to the root of the site
                    this.context.RewritePath("~/");
                }
            }
            else
            {
                this.context.RewritePath("~/");
            }
        }
        /// <summary>
        /// Gets the list of books for the current session
        /// </summary>
        public static List <Book> GetBooks(string instanceId)
        {
            if (!tempState.ContainsKey(instanceId + "_" + "Books"))
            {
                //Get the filename containing the XML data
                string fullyQualifiedPath = VirtualPathUtility.Combine
                                                (VirtualPathUtility.AppendTrailingSlash
                                                    (HttpRuntime.AppDomainAppVirtualPath), "~/App_Data/Books.xml");
                string xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);

                //Create a new list of authors from the XML data
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFileName);
                XmlSerializer serializer = new XmlSerializer(typeof(List <Book>), new XmlRootAttribute()
                {
                    ElementName = "Books"
                });
                XmlNodeReader nodeReader = new XmlNodeReader(xmlDoc);
                List <Book>   books      = (List <Book>)serializer.Deserialize(nodeReader);
                tempState[instanceId + "_" + "Books"] = books;
            }

            //Make sure all navigation properties are populated
            foreach (Book book in (List <Book>)tempState[instanceId + "_" + "Books"])
            {
                if (book.Author == null)
                {
                    //Find the author
                    List <Author> authors = GetAuthors(instanceId);
                    book.Author = authors.FirstOrDefault(a => a.Id == book.AuthorId);
                }

                if (book.Genre == null)
                {
                    //Find the genre
                    List <Genre> genres = GetGenres(instanceId);
                    book.Genre = genres.FirstOrDefault(g => g.Id == book.GenreId);
                }
            }

            return((List <Book>)tempState[instanceId + "_" + "Books"]);
        }
Example #4
0
        /// <summary>Combines two <see cref="Uri" />s altogether, without checking if the base one is an absolute uri.</summary>
        /// <param name="uri">Relative uri to be appended.</param>
        /// <param name="baseUri">Base uri.</param>
        /// <returns><see cref="Uri" /> being a combination of the <paramref name="baseUri" /> and <paramref name="uri" />.</returns>
        public static Uri Combine(this Uri uri, Uri baseUri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }

            if (baseUri.IsAbsoluteUri)
            {
                Uri relativeUri = uri;
                if (relativeUri.ToString().StartsWith("/"))
                {
                    if (!baseUri.ToString().EndsWith("/"))
                    {
                        baseUri = new Uri(baseUri.ToString() + "/");
                    }

                    relativeUri = new Uri(relativeUri.ToString().Substring(1), UriKind.Relative);
                }

                return(new Uri(baseUri, relativeUri));
            }

            string uriString = uri.ToString();

            if (uriString == "/")
            {
                return(baseUri);
            }

            string baseUriString = VirtualPathUtility.AppendTrailingSlash(baseUri.ToString());
            string result        = VirtualPathUtility.Combine(
                (baseUriString[0] == '/' ? String.Empty : "/") + baseUriString,
                (uriString[0] == '/' ? uriString.Substring(1) : uriString));

            return(new Uri(result, UriKind.Relative));
        }
        private bool CreateAndCheckFolderPermission(NodeInfo nodeInfo)
        {
            string file = VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.CreateHtmlPath) + nodeInfo.ParentDir + nodeInfo.NodeDir;

            file = VirtualPathUtility.AppendTrailingSlash(this.PhysicalApplicationPath) + file;
            if (!FileSystemObject.IsExist(file, FsoMethod.Folder))
            {
                try
                {
                    FileSystemObject.Create(file, FsoMethod.Folder);
                }
                catch
                {
                    string errMsg = "栏目ID:" + nodeInfo.NodeId.ToString() + "  " + nodeInfo.NodeName + " 生成失败! 失败原因:请检查服务器是否给网站" + SiteConfig.SiteOption.CreateHtmlPath + "文件夹写入权限!";
                    this.ErrorLog(errMsg);
                    return(false);
                }
            }
            return(true);
        }
Example #6
0
        /// <summary>
        /// Gets the resource name based on the virtual path.
        /// </summary>
        /// <param name="definition">The definition.</param>
        /// <param name="virtualPath">The virtual path.</param>
        protected virtual string GetResourceName(PathDefinition definition, string virtualPath)
        {
            string assemblyName = this.GetAssembly(definition).GetName().Name;
            string path;

            if (definition.IsWildcard)
            {
                var definitionVp = VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.ToAppRelative(definition.VirtualPath));
                var vp           = VirtualPathUtility.ToAppRelative(virtualPath);
                var dir          = VirtualPathUtility.GetDirectory(vp);
                vp   = Regex.Replace(dir, @"[ \-]", "_") + Path.GetFileName(vp);
                path = assemblyName + "." + vp.Substring(definitionVp.Length).Replace('/', '.');
            }
            else
            {
                path = assemblyName;
            }

            return(path);
        }
Example #7
0
        private string FileSavePath()
        {
            string str = "";

            if (string.Compare(this.m_ModuleName, "ADZone", StringComparison.OrdinalIgnoreCase) == 0)
            {
                str             = VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.AdvertisementDir);
                this.m_ShowPath = "";
                return(str);
            }
            if (string.Compare(this.m_ModuleName, "Author", StringComparison.OrdinalIgnoreCase) == 0)
            {
                str             = "AuthorPic/";
                this.m_ShowPath = str;
                return(str);
            }
            if (string.Compare(this.m_ModuleName, "Source", StringComparison.OrdinalIgnoreCase) == 0)
            {
                str             = "CopyFromPic/";
                this.m_ShowPath = str;
                return(str);
            }
            if (string.Compare(this.m_ModuleName, "Trademark", StringComparison.OrdinalIgnoreCase) == 0)
            {
                str             = "TrademarkPic/";
                this.m_ShowPath = str;
                return(str);
            }
            if (string.Compare(this.m_ModuleName, "Producer", StringComparison.OrdinalIgnoreCase) == 0)
            {
                str             = str + "ProducerPic/";
                this.m_ShowPath = str;
                return(str);
            }
            if ((this.m_NodeInfo != null) && SiteConfig.SiteOption.EnableUploadFiles)
            {
                str             = Nodes.UploadPathParse(this.m_NodeInfo, this.FupFile.FileName);
                this.m_ShowPath = str;
            }
            return(str);
        }
        private void CreateNodeDefalutPageHtml(NodeInfo nodeInfo, TemplateInfo templateInfo)
        {
            string path = string.Empty;
            string str2 = SiteConfig.SiteInfo.VirtualPath + VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.CreateHtmlPath);

            if (string.IsNullOrEmpty(nodeInfo.DefaultTemplateFile))
            {
                path = nodeInfo.ContainChildTemplateFile;
                templateInfo.PageName = str2 + nodeInfo.ListHtmlPageName("{$pageid/}");
            }
            else
            {
                templateInfo.PageName = str2 + nodeInfo.ListHtmlPageName("0");
                path = nodeInfo.DefaultTemplateFile;
            }
            try
            {
                templateInfo.CurrentPage     = 1;
                templateInfo.TemplateContent = Template.GetTemplateContent(path, this.PhysicalApplicationPath);
                TemplateTransform.GetHtml(templateInfo);
            }
            catch
            {
                this.CreateMessage = string.Concat(new object[] { "<li>第<font color='red'><b>", this.CreateCompleted + 1, "</b>条信息生成失败</font>&nbsp;&nbsp;栏目名:", nodeInfo.NodeName, "&nbsp;&nbsp;标签解析出现异常</li>", this.CreateMessage });
            }
            finally
            {
                string str3;
                if (nodeInfo.NodeId == -2)
                {
                    str3 = nodeInfo.ListHtmlPageName("0");
                }
                else
                {
                    str3 = VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.CreateHtmlPath) + nodeInfo.ListHtmlPageName("0");
                }
                FileSystemObject.WriteFile(VirtualPathUtility.AppendTrailingSlash(this.PhysicalApplicationPath) + str3, templateInfo.TemplateContent);
                string str4 = (VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteInfo.VirtualPath) + str3).Replace("//", "/");
                this.CreateMessage = string.Concat(new object[] { "<li>成功生成第", this.CreateCompleted + 1, "个栏目的栏目首页,栏目名:<a target=_blank href=", str4, ">", nodeInfo.NodeName, "</a></li>", this.CreateMessage });
            }
        }
Example #9
0
        public ActionResult OpenBucket()
        {
            //var request = new ListObjectsRequest { BucketName = "KloojedDump" };

            //var response = _client.ListObjects(request);

            //var assets = new List<AssetModel>(response.S3Objects.Count);

            var directory = HostingEnvironment.VirtualPathProvider.GetDirectory("~/s3/Images/");

            foreach (S3Object file in directory.Files)
            {
                //if (s3Object.Size == 0)
                //    continue;

                var path = string.Concat("http://s3.amazonaws.com/",
                                         VirtualPathUtility.AppendTrailingSlash(((AmazonS3VirtualPathProvider)HostingEnvironment.VirtualPathProvider).BucketName),
                                         file.Key);

                //assets.Add(new AssetModel
                //{
                //    Name = s3Object.Key,
                //    FileSize = s3Object.Size,
                //    Path = path,
                //    LastModified = s3Object.LastModified,
                //    //Class = selectedAsset.Equals(path) ? "selected" : "unselected"

                //});
            }
            //var viewModel = new FileBrowserModel
            //                    {
            //                        Assets = assets,
            //                        BackAction = "Index",
            //                    };

            return(new JsonResult()
            {
                Data = directory.Files, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
            //return PartialView("_FileBrowser", viewModel);
        }
Example #10
0
        private static void CreateCommonListPageTemplate(ModelInfo modelInfo, bool isEshop)
        {
            string str2;
            string virtualPath = HttpContext.Current.Server.MapPath("~/");
            string fileContent = FileSystemObject.ReadFile(VirtualPathUtility.AppendTrailingSlash(virtualPath) + "CommonTemplate/栏目列表页模板.htm").Replace("{$$$TableName$$$}", modelInfo.TableName).Replace("{$$$ModelName$$$}", modelInfo.ModelName).Replace("{$$$ItemName$$$}", modelInfo.ItemName);
            string str4        = VirtualPathUtility.AppendTrailingSlash(virtualPath) + VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.TemplateDir) + modelInfo.ModelName;

            FileSystemObject.WriteFile(str4 + "/栏目列表页模板.html", fileContent);
            if (isEshop)
            {
                str2 = VirtualPathUtility.AppendTrailingSlash(virtualPath) + "CommonTemplate/内容页模板_商品模型.htm";
            }
            else
            {
                str2 = VirtualPathUtility.AppendTrailingSlash(virtualPath) + "CommonTemplate/内容页模板.htm";
            }
            fileContent = FileSystemObject.ReadFile(str2).Replace("{$$$ContentLabelName$$$}", "内容页_" + modelInfo.ModelName).Replace("{$$$ModelName$$$}", modelInfo.ModelName).Replace("{$$$ItemName$$$}", modelInfo.ItemName);
            FileSystemObject.WriteFile(str4 + "/内容页模板.html", fileContent);
            CreateCommonLable(modelInfo);
            CreateContentLabel(virtualPath, modelInfo);
        }
        protected ProviderControlBase LoadControl(PortalModuleBase parentControl, string controlPath, string controlName)
        {
            string controlValue = "";

            controlPath = VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.Combine(controlPath, _info.VirtualPath));
            for (int i = 0; i < _info.Controls.Length; i++)
            {
                if (_info.Controls[i].Name == controlName)
                {
                    controlValue = _info.Controls[i].Value;
                    break;
                }
            }
            controlPath = VirtualPathUtility.Combine(controlPath, controlValue);

            ProviderControlBase childControl = (ProviderControlBase)parentControl.LoadControl(controlPath);

            childControl.ParentControl = parentControl;

            return(childControl);
        }
Example #12
0
        private void DeleteFolder(HttpContext context)
        {
            var result = OpResult.Denied;

            try
            {
                virtualPath = VirtualPathUtility.AppendTrailingSlash(virtualPath);

                if (OnFolderDeleting(virtualPath, ref result))
                {
                    result = fileSystem.DeleteFolder(virtualPath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result = OpResult.Error;
            }

            RenderJsonResult(context, result);
        }
        private void DeleteHtml(string generalId)
        {
            IList <CommonModelInfo> commonModelInfoList = ContentManage.GetCommonModelInfoList(BasePage.RequestString("NodeID"), generalId);
            string str = base.Server.MapPath("~/" + VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.CreateHtmlPath));

            foreach (CommonModelInfo info2 in commonModelInfoList)
            {
                string file = str;
                if (info2.CreateTime.HasValue && (info2.CreateTime.Value >= info2.UpdateTime))
                {
                    NodeInfo cacheNodeById = Nodes.GetCacheNodeById(info2.NodeId);
                    file = file + ContentManage.ContentHtmlName(info2, cacheNodeById, 0);
                    if (FileSystemObject.IsExist(file, FsoMethod.File))
                    {
                        FileSystemObject.Delete(file, FsoMethod.File);
                    }
                    DateTime?createTime = null;
                    ContentManage.UpdateCreateTime(info2.GeneralId, createTime);
                }
            }
        }
Example #14
0
        private void BindPlacement(ModelShapeContext context, string displayType, string stereotype, string contentType)
        {
            context.FindPlacement = (partShapeType, differentiator, defaultLocation) =>
            {
                var theme      = _themeService.Value.GetRequestTheme(_requestContext);
                var shapeTable = _shapeTableManager.GetShapeTable(theme.Id);
                var request    = _requestContext.HttpContext.Request;

                ShapeDescriptor descriptor;
                if (shapeTable.Descriptors.TryGetValue(partShapeType, out descriptor))
                {
                    var placementContext = new ModelShapePlacementContext
                    {
                        ModelContext   = context,
                        Stereotype     = stereotype,
                        DisplayType    = displayType,
                        Differentiator = differentiator,
                        ContentType    = String.IsNullOrWhiteSpace(contentType)?context.Model.GetType().Name:contentType,
                        // Get the current app-relative path, i.e. ~/my-blog/foo
                        // TODO: This is for Url placement to work. It'd be far better if we could just inject any old strings into a properties dictionary,
                        // or even a dictionary of LazyFields, so work like this doesn't have to happen. Not sure how long ToAppRelative takes but it's
                        // getting called for every single placement op and might never get used...
                        Path = VirtualPathUtility.AppendTrailingSlash(_virtualPathProvider.ToAppRelative(request.Path))
                    };

                    var placement = descriptor.Placement(placementContext);
                    if (placement != null)
                    {
                        placement.Source = placementContext.Source;
                        return(placement);
                    }
                }

                return(new PlacementInfo
                {
                    Location = defaultLocation,
                    Source = String.Empty
                });
            };
        }
Example #15
0
 public virtual void CommonCreateHtml()
 {
     this.m_CreateId = Guid.NewGuid().ToString();
     if (HttpContext.Current != null)
     {
         this.m_PhysicalApplicationPath = HttpContext.Current.Request.PhysicalApplicationPath;
         this.m_MapPath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Server.MapPath("~/"));
         this.m_SiteUrl = HttpContext.Current.Request.Url.Authority + VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);
     }
     this.m_MapPath = this.m_PhysicalApplicationPath;
     try
     {
         string      filename = this.m_MapPath + "Config/CreateHtmlWork.config";
         XmlDocument document = new XmlDocument();
         document.Load(filename);
         XmlAttribute attribute = document.CreateAttribute("id");
         attribute.Value = this.m_CreateId;
         XmlNode newChild = document.CreateElement("WorkId");
         newChild.Attributes.Append(attribute);
         XmlNode node2 = document.CreateElement("ErrorTime");
         newChild.AppendChild(node2);
         node2 = document.CreateElement("ErrorMessage");
         newChild.AppendChild(node2);
         document.SelectSingleNode("CreateWork").AppendChild(newChild);
         document.Save(filename);
     }
     catch (FileNotFoundException)
     {
         CustomException.ThrowBllException("CreateHtmlWork.config文件未找到。");
     }
     catch
     {
         CustomException.ThrowBllException("检查您的服务器是否给配置文件CreateHtmlWork.config或文件夹写入权限。");
     }
     this.StartCreate();
     if (HttpContext.Current != null)
     {
         HttpContext.Current.Application[this.m_CreateId] = this;
     }
 }
        /// <summary>
        /// Internal endpoint with testing capabilities.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        internal void ProcessRequestInternal(HttpContextBase context)
        {
            var resourceParam = context.Request.QueryString["resource"];

            var apprelativePath = VirtualPathUtility.AppendTrailingSlash(context.Request.ApplicationPath) + this._virtualDirectoryName;

            var filePath = !string.IsNullOrEmpty(resourceParam) ? resourceParam : context.Request.Path.Substring(context.Request.Path.IndexOf(apprelativePath, StringComparison.CurrentCultureIgnoreCase) + apprelativePath.Length);

            var assetLoader = _assetLoaderLocator();

            if (assetLoader == null)
            {
                throw new NotSupportedException("Unable to get a not null instance of IAssetLoader.");
            }

            var asset = assetLoader.Load(filePath);

            if (asset == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }
            var fileName = Path.GetFileName(filePath);

            context.Response.ContentType = MimeMapping.GetMimeMapping(fileName);

            var responseContent = asset.Data;
            var refresh         = new TimeSpan(0, 1, 0, 0);

            context.Response.Cache.SetExpires(DateTime.Now.Add(refresh));
            context.Response.Cache.SetMaxAge(refresh);
            context.Response.Cache.SetLastModified(asset.LastWriteTime);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.CacheControl = HttpCacheability.Public.ToString();
            context.Response.Cache.SetValidUntilExpires(true);
            context.Response.Cache.VaryByParams["random"]   = true;
            context.Response.Cache.VaryByParams["resource"] = true;
            context.Response.Cache.VaryByHeaders["Host"]    = true;
            context.Response.BinaryWrite(responseContent);
        }
Example #17
0
        /// <summary>
        /// 生成广告对象的JS代码
        /// </summary>
        /// <returns></returns>
        private string CreatAdvertisementJS()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("var objAD = new ObjectAD();\n");
            builder.Append("objAD.ADID= " + this.advertisementInfo.ADID + ";");
            builder.Append("objAD.ADType= " + this.advertisementInfo.ADType + ";");
            builder.Append("objAD.ADName= \"" + this.advertisementInfo.ADName + "\";");
            string imgUrl = this.advertisementInfo.ImgUrl;

            if (((imgUrl.StartsWith("/") || imgUrl.StartsWith("~/")) || imgUrl.StartsWith("http", StringComparison.CurrentCultureIgnoreCase)) || imgUrl.StartsWith("https", StringComparison.CurrentCultureIgnoreCase))
            {
                builder.Append("objAD.ImgUrl= \"" + imgUrl + "\";");
            }
            else
            {
                builder.Append("objAD.ImgUrl= \"" + VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath) + this.advertisementInfo.ImgUrl + "\";");
            }
            string adintro = this.advertisementInfo.ADIntro;

            adintro = adintro.Replace("\"", "'");
            adintro = adintro.Replace("\n", "");
            adintro = adintro.Replace("\r", "");

            builder.Append("objAD.ImgWidth       = " + this.advertisementInfo.ImgWidth + ";");
            builder.Append("objAD.ImgHeight      = " + this.advertisementInfo.ImgHeight + ";");
            builder.Append("objAD.FlashWmode     = " + this.advertisementInfo.FlashWmode + ";");
            builder.Append("objAD.ADIntro =\"" + adintro + "\";");
            builder.Append("objAD.LinkUrl        = \"" + this.advertisementInfo.LinkUrl + "\";");
            builder.Append("objAD.LinkTarget     = " + this.advertisementInfo.LinkTarget + ";");
            builder.Append("objAD.LinkAlt        = \"" + this.advertisementInfo.LinkAlt + "\";");
            builder.Append("objAD.Priority       = " + this.advertisementInfo.Priority + ";");
            builder.Append("objAD.CountView      = " + this.advertisementInfo.CountView.ToString().ToLower() + ";");
            builder.Append("objAD.CountClick     = " + this.advertisementInfo.CountClick.ToString().ToLower() + ";");
            builder.Append("objAD.OverdueDate    = \"" + this.advertisementInfo.OverdueDate.ToString("yyyy") + "/" + this.advertisementInfo.OverdueDate.ToString("MM") + "/" + this.advertisementInfo.OverdueDate.ToString("dd") + "\";");
            builder.Append("objAD.InstallDir     = \"" + VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath) + "\";");
            builder.Append("objAD.ADDIR= \"" + SiteConfig.SiteOption.AdvertisementDir + "\";");
            builder.Append("ZoneAD_" + this.advertisementInfo.ZoneID + ".AddAD(objAD);");
            return(builder.ToString());
        }
Example #18
0
        protected override void Render(HtmlTextWriter writer)
        {
            var headControl = Page.Header;

            if (headControl == null)
            {
                base.Render(writer);
                return;
            }
            try
            {
                var siteUrl = PortalContext.Current.SiteUrl;
                if (string.IsNullOrEmpty(siteUrl))
                {
                    siteUrl = PortalContext.Current.RequestedUri.GetComponents(UriComponents.HostAndPort, UriFormat.SafeUnescaped);
                }

                var hrefServerPart = VirtualPathUtility.AppendTrailingSlash(siteUrl);
                var hrefPathPart   = PortalContext.Current.RequestedUri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
                var hrefString     = string.Concat(hrefServerPart, hrefPathPart);

                // note that if the original URI already contains a trailing slash, we do not remove it
                if (AppendTrailingSlash)
                {
                    hrefString = VirtualPathUtility.AppendTrailingSlash(hrefString);
                }

                var baseTag = new LiteralControl
                {
                    ID   = "baseTag",
                    Text = string.Format("<base href=\"//{0}\" />", hrefString)
                };

                baseTag.RenderControl(writer);
            }
            catch (Exception exc) // logged
            {
                SnLog.WriteException(exc);
            }
        }
        /// <summary>
        /// Determine the namespace to use for the proxy generation
        /// </summary>
        /// <param name="webReferencesRootVirtualPath">The path to the App_WebReferences folder</param>
        /// <param name="virtualPath">The path to the current folder</param>
        /// <returns></returns>
        private static string CalculateGeneratedNamespace(string webReferencesRootVirtualPath, string virtualPath)
        {
            // ... Ensure both folders have trailing slashes
            webReferencesRootVirtualPath = VirtualPathUtility.AppendTrailingSlash(webReferencesRootVirtualPath);
            virtualPath = VirtualPathUtility.AppendTrailingSlash(virtualPath);

            Debug.Assert(virtualPath.StartsWith(webReferencesRootVirtualPath, StringComparison.OrdinalIgnoreCase),
                         "We expected to be inside the App_WebReferences folder");

            // ... Determine the namespace to use, based on the directory structure where the .svcmap file
            //     is found.
            if (webReferencesRootVirtualPath.Length == virtualPath.Length)
            {
                Debug.Assert(string.Equals(webReferencesRootVirtualPath, virtualPath, StringComparison.OrdinalIgnoreCase),
                             "We expected to be in the App_WebReferences directory");

                // If it's the root WebReferences dir, use the empty namespace
                return(String.Empty);
            }
            else
            {
                // We're in a subdirectory of App_WebReferences.
                // Get the directory's relative path from App_WebReferences, e.g. "Foo/Bar"

                virtualPath = VirtualPathUtility.RemoveTrailingSlash(virtualPath).Substring(webReferencesRootVirtualPath.Length);

                // Split it into chunks separated by '/'
                string[] chunks = virtualPath.Split('/');

                // Turn all the relevant chunks into valid namespace chunks
                for (int i = 0; i < chunks.Length; i++)
                {
                    chunks[i] = MakeValidTypeNameFromString(chunks[i]);
                }

                // Put the relevant chunks back together to form the namespace
                return(String.Join(".", chunks));
            }
        }
Example #20
0
        /// <summary>
        /// Only so we can add users to the adminstrators role.
        /// </summary>
        private void ReadMembershipDataStore()
        {
            string fullyQualifiedPath = VirtualPathUtility.Combine
                                            (VirtualPathUtility.AppendTrailingSlash
                                                (HttpRuntime.AppDomainAppVirtualPath), BlogSettings.Instance.StorageLocation + "users.xml");

            lock (this)
            {
                if (_UserNames == null)
                {
                    _UserNames = new List <string>();
                    XmlDocument doc = new XmlDocument();
                    doc.Load(HostingEnvironment.MapPath(fullyQualifiedPath));
                    XmlNodeList nodes = doc.GetElementsByTagName("User");

                    foreach (XmlNode node in nodes)
                    {
                        _UserNames.Add(node["UserName"].InnerText);
                    }
                }
            }
        }
Example #21
0
        /// <summary>
        ///     Updates the urls.
        /// </summary>
        /// <param name="node">The node.</param>
        private void UpdateUrls(TrieNode node)
        {
            foreach (var child in node.Children)
            {
                var slug = child.Url != null?child.Url.Split('/').Last() : "";

                if (!string.IsNullOrEmpty(child.ParentId))
                {
                    if (child.ParentId == this.RootNode.PageId)
                    {
                        child.Url = slug;
                    }
                    else
                    {
                        var parent = this.Get(child.ParentId);
                        child.Url = slug.Insert(0, VirtualPathUtility.AppendTrailingSlash(parent.Url));
                    }
                }

                this.UpdateUrls(child);
            }
        }
Example #22
0
        private void BindPlacement(BuildShapeContext context, string displayType, string stereotype)
        {
            context.FindPlacement = (partShapeType, differentiator, defaultLocation) =>
            {
                var theme      = _siteThemeService.GetSiteTheme();
                var shapeTable = _shapeTableLocator.Lookup(theme.Id);

                var request = _requestContext.HttpContext.Request;

                ShapeDescriptor descriptor;
                if (shapeTable.Descriptors.TryGetValue(partShapeType, out descriptor))
                {
                    var placementContext = new ShapePlacementContext
                    {
                        ContentType    = context.ContentItem.ContentType,
                        Stereotype     = stereotype,
                        DisplayType    = displayType,
                        Differentiator = differentiator,
                        Path           = VirtualPathUtility.AppendTrailingSlash(_virtualPathProvider.ToAppRelative(request.Path)) // get the current app-relative path, i.e. ~/my-blog/foo
                    };

                    // define which location should be used if none placement is hit
                    descriptor.DefaultPlacement = defaultLocation;

                    var placement = descriptor.Placement(placementContext);
                    if (placement != null)
                    {
                        placement.Source = placementContext.Source;
                        return(placement);
                    }
                }

                return(new PlacementInfo
                {
                    Location = defaultLocation,
                    Source = String.Empty
                });
            };
        }
Example #23
0
        public override string GetResourcePath(NameObjectCollection variables)
        {
            ArgumentUtility.CheckNotNull("variables", variables);

            object pageObject = variables[_pathReference.Name];

            if (pageObject == null)
            {
                throw new InvalidOperationException(string.Format("The variable '{0}' could not be found in the list of variables.", _pathReference.Name));
            }

            string page = pageObject as string;

            if (page == null)
            {
                throw new InvalidCastException(string.Format("The variable '{0}' was of type '{1}'. Expected type is '{2}'.", _pathReference.Name, pageObject.GetType().FullName, typeof(string).FullName));
            }

            return(VirtualPathUtility.Combine(
                       VirtualPathUtility.AppendTrailingSlash(ResourceRoot),
                       page));
        }
Example #24
0
        private String GetCurrentDirectory()
        {
            string currentDirectory = fileSystem.VirtualRoot;

            if (hdnCurDir.Value.Length > 0)
            {
                currentDirectory = hdnCurDir.Value;
            }

            lblCurrentDirectory.Text = currentDirectory.Replace("|", "/");

            if (currentDirectory == fileSystem.VirtualRoot)
            {
                btnGoUp.Visible = false;
            }
            else
            {
                btnGoUp.Visible = true;
            }

            return(currentDirectory = VirtualPathUtility.AppendTrailingSlash(currentDirectory));
        }
        // POST api/userenrolment
        //public HttpResponseMessage PostUserEnrolment(UserEnrolmentData userEnrolment)
        //{
        //    int ID = userEnrolment.Save();
        //    var response = Request.CreateResponse<UserEnrolmentData>(HttpStatusCode.Created, userEnrolment);

        //    string url = VirtualPathUtility.AppendTrailingSlash(Request.RequestUri.AbsoluteUri) + ID;
        //    response.Headers.Location = new Uri(url);
        //    return response;
        //}

        /// <summary>
        /// Enrol a user on a course using either an EventID or a course credit key
        /// </summary>
        /// <param name="userEnrolment">
        /// User enrolment details in JSON or XML format
        /// </param>
        /// <returns></returns>
        public HttpResponseMessage PostUserEnrolment(UserEnrolmentData userEnrolment)
        {
            var response = Request.CreateResponse <UserEnrolmentData>(HttpStatusCode.Created, userEnrolment);

            try
            {
                int    ID  = userEnrolment.Save();
                string url = VirtualPathUtility.AppendTrailingSlash(Request.RequestUri.AbsoluteUri) + ID;
                response.Headers.Location = new Uri(url);
            }
            catch (UserEnrolException ex)
            {
                response.StatusCode   = HttpStatusCode.BadRequest;
                response.ReasonPhrase = ex.Message;
            }
            catch (CourseCreditsException ex)
            {
                response.StatusCode   = HttpStatusCode.BadRequest;
                response.ReasonPhrase = ex.Message;
            }
            return(response);
        }
        private ResourcePathMapping GetResourcePathMapping(string appRelativePath)
        {
            var rootPath = VirtualPathUtility.AppendTrailingSlash(appRelativePath);

            if (_resourcePathMappings.ContainsKey(rootPath))
            {
                return(_resourcePathMappings[rootPath]);
            }

            var subDirectories = appRelativePath.Substring(_resourceRoot.Length).Split('/');

            for (var index = 0; index < subDirectories.Length; index++)
            {
                var partialPath = VirtualPathUtility.AppendTrailingSlash(_resourceRoot + string.Join("/", subDirectories, 0, index + 1));
                if (_resourcePathMappings.ContainsKey(partialPath))
                {
                    return(_resourcePathMappings[partialPath]);
                }
            }

            return(null);
        }
Example #27
0
        /// <summary>
        /// Gets the control presentation that contains the requested resource from the database.
        /// </summary>
        /// <param name="virtualPathDefinition">The virtual path definition.</param>
        /// <param name="virtualPath">The virtual path.</param>
        protected virtual ControlPresentation GetControlPresentation(PathDefinition virtualPathDefinition, string virtualPath)
        {
            if (virtualPathDefinition == null)
            {
                throw new ArgumentNullException("virtualPathDefinition");
            }

            if (virtualPath == null)
            {
                throw new ArgumentNullException("virtualPath");
            }

            var resourceName = VirtualPathUtility.ToAppRelative(virtualPath);
            var areaName     = VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.ToAppRelative(virtualPathDefinition.VirtualPath));
            var extension    = VirtualPathUtility.GetExtension(virtualPath).ToLowerInvariant();

            var controlPresentation = PageManager.GetManager().GetPresentationItems <ControlPresentation>()
                                      .FirstOrDefault(cp => cp.AreaName == areaName && cp.NameForDevelopers == resourceName &&
                                                      cp.DataType == extension);

            return(controlPresentation);
        }
 protected void RenderItemName(HtmlTextWriter output, FileViewItem item)
 {
     if (fileView.UseLinkToOpenItem)
     {
         string href = item.IsDirectory ?
                       "javascript:WFM_" + fileView.Controller.ClientID + ".OnExecuteCommand(WFM_" + fileView.ClientID + ",\'0:0\')" :
                       (VirtualPathUtility.AppendTrailingSlash(fileView.CurrentDirectory.VirtualPath) + item.FileSystemInfo.Name);
         if (!item.IsDirectory && !String.IsNullOrEmpty(fileView.LinkToOpenItemTarget))
         {
             output.AddAttribute(HtmlTextWriterAttribute.Target, fileView.LinkToOpenItemTarget);
         }
         output.AddAttribute(HtmlTextWriterAttribute.Href, href, true);
         output.AddAttribute(HtmlTextWriterAttribute.Class, fileView.LinkToOpenItemClass);
         output.RenderBeginTag(HtmlTextWriterTag.A);
         output.Write(HttpUtility.HtmlEncode(item.Name));
         output.RenderEndTag();
     }
     else
     {
         output.Write(HttpUtility.HtmlEncode(item.Name));
     }
 }
Example #29
0
        /// <summary>
        ///     Transforms all url rules in <paramref name="content" /> that are not Data URI to absolute.
        ///     We cannot use <see cref="CssRewriteUrlTransform" /> because it has a bug - it screwes up data uri and virtual
        ///     directory based urls.
        /// </summary>
        /// <param name="cssFilePath">File path of the file being bundled</param>
        /// <param name="content">The file content to replace URLs in</param>
        /// <exception cref="HttpException">Cannot make an absolute path from '<paramref name="cssFilePath"/>' file location to URL in <paramref name="content"/></exception>
        private static string ConvertUrlsToAbsolute(string cssFilePath, string content)
        {
            string basePath = VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.GetDirectory(VirtualPathUtility.ToAbsolute(cssFilePath)));

            return(_cssUrlRuleMatcher.Replace(content, match =>
            {
                string url = match.Groups["url"].Value;
                if (!string.IsNullOrWhiteSpace(url) && !url.StartsWith("data:") && !url.StartsWith("//") && !url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    try
                    {
                        url = VirtualPathUtility.Combine(basePath, url);
                    }
                    catch (Exception ex)
                    {
                        throw new HttpException(string.Format(
                                                    "Cannot make an absolute path from '{0}' file location to '{1}'", cssFilePath, url), ex);
                    }
                }
                return string.Concat("url(", url, ")");
            }));
        }
Example #30
0
        /// <summary>
        /// Gets the relative path of the template to use with the current file taking into account all the possible parameters/fields that control this setting
        /// </summary>
        /// <returns></returns>
        private static string GetCurrentTemplateFile(MarkdownFile md)
        {
            //Get the template name that is going to be used (Front Matter or configuration), if any.
            string templateName = Common.GetFieldValue("TemplateName", md);

            if (string.IsNullOrEmpty(templateName))
            {
                return(string.Empty);    //Use the default basic HTML5 template
            }
            //The name (or sub-path) for the layout file (.html normaly) to be used
            string layoutName = Common.GetFieldValue("Layout", md);

            if (string.IsNullOrEmpty(layoutName))
            {
                return(string.Empty);    //Use the default basic HTML5 template
            }
            //If both the template folder and the layout are established, then get the base folder for the templates
            //This base path for the templates parameter is only available through Web.config. NOT in the file Front Matter (we're skipping the file in the following call)
            string basePath = Common.GetFieldValue("TemplatesBasePath", defValue: "~/Templates/");

            return(VirtualPathUtility.AppendTrailingSlash(basePath) + VirtualPathUtility.AppendTrailingSlash(templateName) + layoutName);
        }