Search Results

Search found 51 results on 3 pages for 'resolveurl'.

Page 1/3 | 1 2 3  | Next Page >

  • ResolveUrl() from WCF service

    - by Michael Freidgeim
    I wanted to ResolveUrl() from WCF service and foundhttp://www.west-wind.com/weblog/posts/2007/Sep/18/ResolveUrl-without-Page .However the function assumes that the call is synchronous, in asynchronous call (e.g called from TPL task) HttpContext.Current==null.I had to split my asynchronous method into two-a long asynchronous one, invoked as task and generating relative URL and a post-task, that is calling wwWebUtils.ResolveServerUrl(relativeUrL)The http://www.codeproject.com/Articles/205425/ASP-NET-ResolveUrl-Without-Page  article suggests to useSystem.Web.VirtualPathUtility.ToAbsolute("~/default.aspx");but i expect, it wouldn’t work from asynchronous thread as well.

    Read the article

  • ResolveUrl Problem in Master Page

    - by Tarik
    Okay, I know it is weird but when I put this code between <head runat="server"></head> in master.page, this is how it renders into: <link id="ctl00_Link1" rel="shortcut icon" href="../%3C%25%20ResolveUrl(%22~/Resources/Pictures/Shared/Misc/favicon.ico%22);%20%25%3E" type="image/x-icon" /> It doesn't see something asp.net needs to take care of. This is the original code : <link id="Link1" rel="shortcut icon" href='<%=ResolveUrl("~/Resources/Pictures/Shared/Misc/favicon.ico") %>' type="image/x-icon" runat="server" /> Basically Asp.Net doesn't take care of the code below and renders as a normal html. How can I get over this problem? Thanks in advance... Edit and Resolved Okay people, there is no way for doing this. I've finally figured out because ResolveUrl or ResolveClientUrl is only working for these below : @import '<%= ResolveUrl("~/Resources/Styles/MainMaster/MainDesign.css") %>'; <script src='Resources/Scripts/Libraries/jquery-1.4.2.js' type="text/javascript"</script> it is too literal for link so you need to put link elements in body tag like : <body> <link id="iconOne" rel="shortcut icon" type="image/x-icon" href="Resources/Pictures/Shared/Misc/favicon.ico"/> <link id="iconTwo" rel="icon" href='Resources/Pictures/Shared/Misc/favicon.ico' type="image/ico" /> </body>

    Read the article

  • ResolveURL not resolving in a user control

    - by WebJunk
    I'm trying to use ResolveUrl() to set some paths in the code behind of a custom ASP.NET user control. The user control contains a navigation menu. I'm loading it on a page that's loading a master page. When I call ResolveUrl("~") in my user control it returns "~" instead of the root of the site. When I call it in a page I get the root path as expected. I've stepped through with the debugger and confirmed, ResolveUrl("~") returns "~" in my user control code behind. Is there some other way I should be calling the function in my user control code behind to get the root path of the site?

    Read the article

  • attaching js files to one js file but with JQuery error !

    - by uzay95
    Hi, I wanted to create one js file which includes every js files to attach them to the head tag where it is. But i am getting this error Microsoft JScript runtime error: Object expected this is my code: var baseUrl = document.location.protocol + "//" + document.location.host + '/yabant/'; // To find root path with virtual directory function ResolveUrl(url) { if (url.indexOf("~/") == 0) { url = baseUrl + url.substring(2); } return url; } // JS dosyalarinin tek noktadan yönetilmesi function addJavascript(jsname, pos) { var th = document.getElementsByTagName(pos)[0]; var s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('src', jsname); th.appendChild(s); } addJavascript(ResolveUrl('~/js/1_jquery-1.4.2.min.js'), 'head'); $(document).ready(function() { addJavascript(ResolveUrl('~/js/5_json_parse.js'), 'head'); addJavascript(ResolveUrl('~/js/3_jquery.colorbox-min.js'), 'head'); addJavascript(ResolveUrl('~/js/4_AjaxErrorHandling.js'), 'head'); addJavascript(ResolveUrl('~/js/6_jsSiniflar.js'), 'head'); addJavascript(ResolveUrl('~/js/yabanYeni.js'), 'head'); addJavascript(ResolveUrl('~/js/7_ResimBul.js'), 'head'); addJavascript(ResolveUrl('~/js/8_HaberEkle.js'), 'head'); addJavascript(ResolveUrl('~/js/9_etiketIslemleri.js'), 'head'); addJavascript(ResolveUrl('~/js/bugun.js'), 'head'); addJavascript(ResolveUrl('~/js/yaban.js'), 'head'); addJavascript(ResolveUrl('~/embed/bitgravity/functions.js'), 'head'); }); Paths are right. I wanted to show you folder structure and watch panel: Any help would be greatly appreciated.

    Read the article

  • Best Way to automatically compress and minimize JavaScript files in an ASP.NET MVC app

    - by wgpubs
    So I have an ASP.NET MVC app that references a number of javascript files in various places (in the site master and additional references in several views as well). I'd like to know if there is an automated way, and if so what is the recommended approach, for compressing and minimizing such references into a single .js file where possible. Such that this ... <script src="<%= ResolveUrl("~") %>Content/ExtJS/Ext.ux.grid.GridSummary/Ext.ux.grid.GridSummary.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.rating/ext.ux.ratingplugin.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext-starslider/ext-starslider.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.dollarfield.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.combobox.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.datepickerplus/ext.ux.datepickerplus-min.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/SessionProvider.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/TabCloseMenu.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/ActivityForm.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/UserForm.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/SwappedGrid.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/Tree.js" type="text/javascript"></script> ... could be reduced to something like this ... <script src="<%= ResolveUrl("~") %>Content/MyViewPage-min.js" type="text/javascript"></script> Thanks

    Read the article

  • Jquery loaded? Colorbox is available? Calling some js file via $.getScript are always downloading fr

    - by uzay95
    I am dynamically load js files with _tumIsler.js (_allStuff.js) <script src="../js/_tumJsler.js" type="text/javascript"></script> It contains: // url=> http: + // + localhost:4399 + /yabant/ // ---- ---- -------------- -------- // protocol + "//" + host + '/virtualDirectory/' var baseUrl = document.location.protocol + "//" + document.location.host + '/yabant/'; // If there is "~/" at the begining of url, replace it with baseUrl function ResolveUrl(url) { if (url.indexOf("~/") == 0) { url = baseUrl + url.substring(2); } return url; } // Attaching scripts to any tag function addJavascript(jsname, pos) { var th = document.getElementsByTagName(pos)[0]; var s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('src', jsname); th.appendChild(s); } // I want to make sure jQuery is loaded? addJavascript(ResolveUrl('~/js/1_jquery-1.4.2.min.js'), 'head'); var loaded = false; // assume it didn't first and if it is change it to true function fControl() { // alert("JQUERY is loaded?"); if (typeof jQuery == 'undefined') { loaded = false; fTry2LoadJquery(); } else { loaded = true; fGetOtherScripts(); } } // Check is jQuery loaded fControl(); function fTry2LoadJquery() { // alert("JQUERY didn't load! Trying to reload..."); if (loaded == false) { setTimeout("fControl()", 1000); } else { return; } } function getJavascript(jsname, pos) { // I want to retrieve every script one by one $.ajaxSetup({ async: false, beforeSend: function() { $.ajaxSetup({ async: false, cache: true }); }, complete: function() { $.ajaxSetup({ async: false, cache: true }); }, success: function() { // } }); $.getScript(ResolveUrl(jsname), function() { /* ok! */ }); } function fGetOtherScripts() { // alert("Other js files will be load in this function"); getJavascript(ResolveUrl('~/js/5_json_parse.js'), 'head'); getJavascript(ResolveUrl('~/js/3_jquery.colorbox-min.js'), 'head'); getJavascript(ResolveUrl('~/js/4_AjaxErrorHandling.js'), 'head'); getJavascript(ResolveUrl('~/js/6_jsSiniflar.js'), 'head'); getJavascript(ResolveUrl('~/js/yabanYeni.js'), 'head'); getJavascript(ResolveUrl('~/js/7_ResimBul.js'), 'head'); getJavascript(ResolveUrl('~/js/8_HaberEkle.js'), 'head'); getJavascript(ResolveUrl('~/js/9_etiketIslemleri.js'), 'head'); getJavascript(ResolveUrl('~/js/bugun.js'), 'head'); getJavascript(ResolveUrl('~/js/yaban.js'), 'head'); getJavascript(ResolveUrl('~/embed/bitgravity/functions.js'), 'head'); } After all these js files are loaded, this line is executing to show UploadFile page inside the page when clicked to the button which id is "btnResimYukle" . <script type="text/javascript"> if (jQuery().colorbox) { alert("colorbox exists"); } else { alert("colorbox doesn't exist"); $.ajaxSetup({ cache: true, async: false }); $.getScript(ResolveUrl('~/js/3_jquery.colorbox-min.js'), function() { alert("Loaded ! "); $('#btnResimYukle').live('click', function() { $.fn.colorbox({ iframe: true, width: 700, height: 600, href: ResolveUrl('~/Yonetim/DosyaYukle.aspx') }); return false; }); }); } </script> First i want to ask you very good people, i am always calling js files with $.getScript function. Are they always downloading in every $.getScript requests? And if it is so, how can i prevent that? is this work: $.ajaxSetup({ cache: true, async: false }); Second, i am always getting this error when i press F5 or Ctrl+F5 : But when i press enter key on url, there is no error :s

    Read the article

  • Apache local configuration to resolve files correctly

    - by Alex E.
    Hello, I am new at this so bare with me. I have just configured Apache and PHP to work on my local Mac OS X computer. Now PHP works fine, except when I try to load the files for my live sites. The live sites have separate directories and are sorted by client name etc. I've created symlinks in the default root for the local web server documents. My issue is that Apache doesn't seem to want to load any of the relative paths that are found in the HTML pages. For example, I have src="/css/main.css" but Apache doesn't load the file, similarly for images, it just resolves as a file not found 404 error. I then thought it might be the symlinks so I copied the full directory into the Apache document root, and still had the same result. I would really love to setup my local development environment to run Apache, PHP, MySQL to develop locally then publish when ready. I also tried the MAMP installation, and had the same issues. Any help at all in this would be greatly appreciated. If my explanation wasn't clear please let me know. Thanks! Alex.

    Read the article

  • Can I resolve ASP.NET "~" app paths to the website root without a Control being present?

    - by jdk
    I want to Resolve "~/whatever" from inside non-Page contexts such as Global.asax (HttpApplication), HttpModule, HttpHandler, etc. but can only find the Resolution methods specific to Controls (and Page). I think the app should have enough knowledge to be able to map this outside the Page context. No? Or at least it makes sense to me it should be resolvable in other circumstances, wherever the app root is known. Update: The reason being I'm sticking ~ paths in the web.configuration files. Update 2: I'm trying to resolve them to the website root such as Control.Resolve(..) URL does, not to a file system path.

    Read the article

  • Can I resolve ASP.NET "~" paths without a Control being present?

    - by jdk
    I want to Resolve "~/whatever" from inside non-Page contexts such as Global.asax (HttpApplication), HttpModule, HttpHandler, etc. but can only find the Resolution methods specific to Controls (and Page). I think the app should have enough knowledge to be able to map this outside the Page context. No? Or at least it makes sense to me it should be resolvable in other circumstances, wherever the app root is known. Update: The reason being I'm sticking ~ paths in the web.configuration files.

    Read the article

  • How can I resolve ASP.NET "~" app paths to the website root without a Control being present?

    - by jdk
    I want to Resolve "~/whatever" from inside non-Page contexts such as Global.asax (HttpApplication), HttpModule, HttpHandler, etc. but can only find such Resolution methods specific to Controls (and Page). I think the app should have enough knowledge to be able to map this outside the Page context. No? Or at least it makes sense to me it should be resolvable in other circumstances, wherever the app root is known. Update: The reason being I'm sticking "~" paths in the web.configuration files, and want to resolve them from the aforementioned non-Control scenarios. Update 2: I'm trying to resolve them to the website root such as Control.Resolve(..) URL behaviour, not to a file system path.

    Read the article

  • Making Sense of ASP.NET Paths

    - by Rick Strahl
    ASP.Net includes quite a plethora of properties to retrieve path information about the current request, control and application. There's a ton of information available about paths on the Request object, some of it appearing to overlap and some of it buried several levels down, and it can be confusing to find just the right path that you are looking for. To keep things straight I thought it a good idea to summarize the path options along with descriptions and example paths. I wrote a post about this a long time ago in 2004 and I find myself frequently going back to that page to quickly figure out which path I’m looking for in processing the current URL. Apparently a lot of people must be doing the same, because the original post is the second most visited even to this date on this blog to the tune of nearly 500 hits per day. So, I decided to update and expand a bit on the original post with a little more information and clarification based on the original comments. Request Object Paths Available Here's a list of the Path related properties on the Request object (and the Page object). Assume a path like http://www.west-wind.com/webstore/admin/paths.aspx for the paths below where webstore is the name of the virtual. .blackborder td { border-bottom: solid 1px silver; border-left: solid 1px silver; } Request Property Description and Value ApplicationPath Returns the web root-relative logical path to the virtual root of this app. /webstore/ PhysicalApplicationPath Returns local file system path of the virtual root for this app. c:\inetpub\wwwroot\webstore PhysicalPath Returns the local file system path to the current script or path. c:\inetpub\wwwroot\webstore\admin\paths.aspx Path FilePath CurrentExecutionFilePath All of these return the full root relative logical path to the script page including path and scriptname. CurrentExcecutionFilePath will return the ‘current’ request path after a Transfer/Execute call while FilePath will always return the original request’s path. /webstore/admin/paths.aspx AppRelativeCurrentExecutionFilePath Returns an ASP.NET root relative virtual path to the script or path for the current request. If in  a Transfer/Execute call the transferred Path is returned. ~/admin/paths.aspx PathInfo Returns any extra path following the script name. If no extra path is provided returns the root-relative path (returns text in red below). string.Empty if no PathInfo is available. /webstore/admin/paths.aspx/ExtraPathInfo RawUrl Returns the full root relative URL including querystring and extra path as a string. /webstore/admin/paths.aspx?sku=wwhelp40 Url Returns a fully qualified URL including querystring and extra path. Note this is a Uri instance rather than string. http://www.west-wind.com/webstore/admin/paths.aspx?sku=wwhelp40 UrlReferrer The fully qualified URL of the page that sent the request. This is also a Uri instance and this value is null if the page was directly accessed by typing into the address bar or using an HttpClient based Referrer client Http header. http://www.west-wind.com/webstore/default.aspx?Info Control.TemplateSourceDirectory Returns the logical path to the folder of the page, master or user control on which it is called. This is useful if you need to know the path only to a Page or control from within the control. For non-file controls this returns the Page path. /webstore/admin/ As you can see there’s a ton of information available there for each of the three common path formats: Physical Path is an OS type path that points to a path or file on disk. Logical Path is a Web path that is relative to the Web server’s root. It includes the virtual plus the application relative path. ~/ (Root-relative) Path is an ASP.NET specific path that includes ~/ to indicate the virtual root Web path. ASP.NET can convert virtual paths into either logical paths using Control.ResolveUrl(), or physical paths using Server.MapPath(). Root relative paths are useful for specifying portable URLs that don’t rely on relative directory structures and very useful from within control or component code. You should be able to get any necessary format from ASP.NET from just about any path or script using these mechanisms. ~/ Root Relative Paths and ResolveUrl() and ResolveClientUrl() ASP.NET supports root-relative virtual path syntax in most of its URL properties in Web Forms. So you can easily specify a root relative path in a control rather than a location relative path: <asp:Image runat="server" ID="imgHelp" ImageUrl="~/images/help.gif" /> ASP.NET internally resolves this URL by using ResolveUrl("~/images/help.gif") to arrive at the root-relative URL of /webstore/images/help.gif which uses the Request.ApplicationPath as the basepath to replace the ~. By convention any custom Web controls also should use ResolveUrl() on URL properties to provide the same functionality. In your own code you can use Page.ResolveUrl() or Control.ResolveUrl() to accomplish the same thing: string imgPath = this.ResolveUrl("~/images/help.gif"); imgHelp.ImageUrl = imgPath; Unfortunately ResolveUrl() is limited to WebForm pages, so if you’re in an HttpHandler or Module it’s not available. ASP.NET Mvc also has it’s own more generic version of ResolveUrl in Url.Decode: <script src="<%= Url.Content("~/scripts/new.js") %>" type="text/javascript"></script> which is part of the UrlHelper class. In ASP.NET MVC the above sort of syntax is actually even more crucial than in WebForms due to the fact that views are not referencing specific pages but rather are often path based which can lead to various variations on how a particular view is referenced. In a Module or Handler code Control.ResolveUrl() unfortunately is not available which in retrospect seems like an odd design choice – URL resolution really should happen on a Request basis not as part of the Page framework. Luckily you can also rely on the static VirtualPathUtility class: string path = VirtualPathUtility.ToAbsolute("~/admin/paths.aspx"); VirtualPathUtility also many other quite useful methods for dealing with paths and converting between the various kinds of paths supported. One thing to watch out for is that ToAbsolute() will throw an exception if a query string is provided and doesn’t work on fully qualified URLs. I wrote about this topic with a custom solution that works fully qualified URLs and query strings here (check comments for some interesting discussions too). Similar to ResolveUrl() is ResolveClientUrl() which creates a fully qualified HTTP path that includes the protocol and domain name. It’s rare that this full resolution is needed but can be useful in some scenarios. Mapping Virtual Paths to Physical Paths with Server.MapPath() If you need to map root relative or current folder relative URLs to physical URLs or you can use HttpContext.Current.Server.MapPath(). Inside of a Page you can do the following: string physicalPath = Server.MapPath("~/scripts/ww.jquery.js")); MapPath is pretty flexible and it understands both ASP.NET style virtual paths as well as plain relative paths, so the following also works. string physicalPath = Server.MapPath("scripts/silverlight.js"); as well as dot relative syntax: string physicalPath = Server.MapPath("../scripts/jquery.js"); Once you have the physical path you can perform standard System.IO Path and File operations on the file. Remember with physical paths and IO or copy operations you need to make sure you have permissions to access files and folders based on the Web server user account that is active (NETWORK SERVICE, ASPNET typically). Note the Server.MapPath will not map up beyond the virtual root of the application for security reasons. Server and Host Information Between these settings you can get all the information you may need to figure out where you are at and to build new Url if necessary. If you need to build a URL completely from scratch you can get access to information about the server you are accessing: Server Variable Function and Example SERVER_NAME The of the domain or IP Address wwww.west-wind.com or 127.0.0.1 SERVER_PORT The port that the request runs under. 80 SERVER_PORT_SECURE Determines whether https: was used. 0 or 1 APPL_MD_PATH ADSI DirectoryServices path to the virtual root directory. Note that LM typically doesn’t work for ADSI access so you should replace that with LOCALHOST or the machine’s NetBios name. /LM/W3SVC/1/ROOT/webstore Request.Url and Uri Parsing If you still need more control over the current request URL or  you need to create new URLs from an existing one, the current Request.Url Uri property offers a lot of control. Using the Uri class and UriBuilder makes it easy to retrieve parts of a URL and create new URLs based on existing URL. The UriBuilder class is the preferred way to create URLs – much preferable over creating URIs via string concatenation. Uri Property Function Scheme The URL scheme or protocol prefix. http or https Port The port if specifically specified. DnsSafeHost The domain name or local host NetBios machine name www.west-wind.com or rasnote LocalPath The full path of the URL including script name and extra PathInfo. /webstore/admin/paths.aspx Query The query string if any ?id=1 The Uri class itself is great for retrieving Uri parts, but most of the properties are read only if you need to modify a URL in order to change it you can use the UriBuilder class to load up an existing URL and modify it to create a new one. Here are a few common operations I’ve needed to do to get specific URLs: Convert the Request URL to an SSL/HTTPS link For example to take the current request URL and converted  it to a secure URL can be done like this: UriBuilder build = new UriBuilder(Request.Url); build.Scheme = "https"; build.Port = -1; // don't inject port Uri newUri = build.Uri; string newUrl = build.ToString(); Retrieve the fully qualified URL without a QueryString AFAIK, there’s no native routine to retrieve the current request URL without the query string. It’s easy to do with UriBuilder however: UriBuilder builder = newUriBuilder(Request.Url); builder.Query = ""; stringlogicalPathWithoutQuery = builder.ToString(); What else? I took a look through the old post’s comments and addressed as many of the questions and comments that came up in there. With a few small and silly exceptions this update post handles most of these. But I’m sure there are a more things that go in here. What else would be useful to put onto this post so it serves as a nice all in one place to go for path references? If you think of something leave a comment and I’ll try to update the post with it in the future.© Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  

    Read the article

  • Making Sense of ASP.NET Paths

    - by Renso
    Making Sense of ASP.NET Paths ASP.Net includes quite a plethora of properties to retrieve path information about the current request, control and application. There's a ton of information available about paths on the Request object, some of it appearing to overlap and some of it buried several levels down, and it can be confusing to find just the right path that you are looking for. To keep things straight I thought it a good idea to summarize the path options along with descriptions and example paths. I wrote a post about this a long time ago in 2004 and I find myself frequently going back to that page to quickly figure out which path I’m looking for in processing the current URL. Apparently a lot of people must be doing the same, because the original post is the second most visited even to this date on this blog to the tune of nearly 500 hits per day. So, I decided to update and expand a bit on the original post with a little more information and clarification based on the original comments. Request Object Paths Available Here's a list of the Path related properties on the Request object (and the Page object). Assume a path like http://www.west-wind.com/webstore/admin/paths.aspx for the paths below where webstore is the name of the virtual. Request Property Description and Value ApplicationPath Returns the web root-relative logical path to the virtual root of this app. /webstore/ PhysicalApplicationPath Returns local file system path of the virtual root for this app. c:\inetpub\wwwroot\webstore PhysicalPath Returns the local file system path to the current script or path. c:\inetpub\wwwroot\webstore\admin\paths.aspx Path FilePath CurrentExecutionFilePath All of these return the full root relative logical path to the script page including path and scriptname. CurrentExcecutionFilePath will return the ‘current’ request path after a Transfer/Execute call while FilePath will always return the original request’s path. /webstore/admin/paths.aspx AppRelativeCurrentExecutionFilePath Returns an ASP.NET root relative virtual path to the script or path for the current request. If in  a Transfer/Execute call the transferred Path is returned. ~/admin/paths.aspx PathInfo Returns any extra path following the script name. If no extra path is provided returns the root-relative path (returns text in red below). string.Empty if no PathInfo is available. /webstore/admin/paths.aspx/ExtraPathInfo RawUrl Returns the full root relative URL including querystring and extra path as a string. /webstore/admin/paths.aspx?sku=wwhelp40 Url Returns a fully qualified URL including querystring and extra path. Note this is a Uri instance rather than string. http://www.west-wind.com/webstore/admin/paths.aspx?sku=wwhelp40 UrlReferrer The fully qualified URL of the page that sent the request. This is also a Uri instance and this value is null if the page was directly accessed by typing into the address bar or using an HttpClient based Referrer client Http header. http://www.west-wind.com/webstore/default.aspx?Info Control.TemplateSourceDirectory Returns the logical path to the folder of the page, master or user control on which it is called. This is useful if you need to know the path only to a Page or control from within the control. For non-file controls this returns the Page path. /webstore/admin/ As you can see there’s a ton of information available there for each of the three common path formats: Physical Path is an OS type path that points to a path or file on disk. Logical Path is a Web path that is relative to the Web server’s root. It includes the virtual plus the application relative path. ~/ (Root-relative) Path is an ASP.NET specific path that includes ~/ to indicate the virtual root Web path. ASP.NET can convert virtual paths into either logical paths using Control.ResolveUrl(), or physical paths using Server.MapPath(). Root relative paths are useful for specifying portable URLs that don’t rely on relative directory structures and very useful from within control or component code. You should be able to get any necessary format from ASP.NET from just about any path or script using these mechanisms. ~/ Root Relative Paths and ResolveUrl() and ResolveClientUrl() ASP.NET supports root-relative virtual path syntax in most of its URL properties in Web Forms. So you can easily specify a root relative path in a control rather than a location relative path: <asp:Image runat="server" ID="imgHelp" ImageUrl="~/images/help.gif" /> ASP.NET internally resolves this URL by using ResolveUrl("~/images/help.gif") to arrive at the root-relative URL of /webstore/images/help.gif which uses the Request.ApplicationPath as the basepath to replace the ~. By convention any custom Web controls also should use ResolveUrl() on URL properties to provide the same functionality. In your own code you can use Page.ResolveUrl() or Control.ResolveUrl() to accomplish the same thing: string imgPath = this.ResolveUrl("~/images/help.gif"); imgHelp.ImageUrl = imgPath; Unfortunately ResolveUrl() is limited to WebForm pages, so if you’re in an HttpHandler or Module it’s not available. ASP.NET Mvc also has it’s own more generic version of ResolveUrl in Url.Decode: <script src="<%= Url.Content("~/scripts/new.js") %>" type="text/javascript"></script> which is part of the UrlHelper class. In ASP.NET MVC the above sort of syntax is actually even more crucial than in WebForms due to the fact that views are not referencing specific pages but rather are often path based which can lead to various variations on how a particular view is referenced. In a Module or Handler code Control.ResolveUrl() unfortunately is not available which in retrospect seems like an odd design choice – URL resolution really should happen on a Request basis not as part of the Page framework. Luckily you can also rely on the static VirtualPathUtility class: string path = VirtualPathUtility.ToAbsolute("~/admin/paths.aspx"); VirtualPathUtility also many other quite useful methods for dealing with paths and converting between the various kinds of paths supported. One thing to watch out for is that ToAbsolute() will throw an exception if a query string is provided and doesn’t work on fully qualified URLs. I wrote about this topic with a custom solution that works fully qualified URLs and query strings here (check comments for some interesting discussions too). Similar to ResolveUrl() is ResolveClientUrl() which creates a fully qualified HTTP path that includes the protocol and domain name. It’s rare that this full resolution is needed but can be useful in some scenarios. Mapping Virtual Paths to Physical Paths with Server.MapPath() If you need to map root relative or current folder relative URLs to physical URLs or you can use HttpContext.Current.Server.MapPath(). Inside of a Page you can do the following: string physicalPath = Server.MapPath("~/scripts/ww.jquery.js")); MapPath is pretty flexible and it understands both ASP.NET style virtual paths as well as plain relative paths, so the following also works. string physicalPath = Server.MapPath("scripts/silverlight.js"); as well as dot relative syntax: string physicalPath = Server.MapPath("../scripts/jquery.js"); Once you have the physical path you can perform standard System.IO Path and File operations on the file. Remember with physical paths and IO or copy operations you need to make sure you have permissions to access files and folders based on the Web server user account that is active (NETWORK SERVICE, ASPNET typically). Note the Server.MapPath will not map up beyond the virtual root of the application for security reasons. Server and Host Information Between these settings you can get all the information you may need to figure out where you are at and to build new Url if necessary. If you need to build a URL completely from scratch you can get access to information about the server you are accessing: Server Variable Function and Example SERVER_NAME The of the domain or IP Address wwww.west-wind.com or 127.0.0.1 SERVER_PORT The port that the request runs under. 80 SERVER_PORT_SECURE Determines whether https: was used. 0 or 1 APPL_MD_PATH ADSI DirectoryServices path to the virtual root directory. Note that LM typically doesn’t work for ADSI access so you should replace that with LOCALHOST or the machine’s NetBios name. /LM/W3SVC/1/ROOT/webstore Request.Url and Uri Parsing If you still need more control over the current request URL or  you need to create new URLs from an existing one, the current Request.Url Uri property offers a lot of control. Using the Uri class and UriBuilder makes it easy to retrieve parts of a URL and create new URLs based on existing URL. The UriBuilder class is the preferred way to create URLs – much preferable over creating URIs via string concatenation. Uri Property Function Scheme The URL scheme or protocol prefix. http or https Port The port if specifically specified. DnsSafeHost The domain name or local host NetBios machine name www.west-wind.com or rasnote LocalPath The full path of the URL including script name and extra PathInfo. /webstore/admin/paths.aspx Query The query string if any ?id=1 The Uri class itself is great for retrieving Uri parts, but most of the properties are read only if you need to modify a URL in order to change it you can use the UriBuilder class to load up an existing URL and modify it to create a new one. Here are a few common operations I’ve needed to do to get specific URLs: Convert the Request URL to an SSL/HTTPS link For example to take the current request URL and converted  it to a secure URL can be done like this: UriBuilder build = new UriBuilder(Request.Url); build.Scheme = "https"; build.Port = -1; // don't inject portUri newUri = build.Uri; string newUrl = build.ToString(); Retrieve the fully qualified URL without a QueryString AFAIK, there’s no native routine to retrieve the current request URL without the query string. It’s easy to do with UriBuilder however: UriBuilder builder = newUriBuilder(Request.Url); builder.Query = ""; stringlogicalPathWithoutQuery = builder.ToString();

    Read the article

  • Resolve a URL from a Partial View (ASP.NET MVC)

    Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png. Astandard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:' /The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image.I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl.public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); return MvcHtmlString.Create(urlHelper.Content(url)); }With this method in place you can resolve a URL in a partial view like so:' /Or you could use Stephen's Html.Image extension method (althoughmy more generic Html.ResolveUrl method could be used in non-image related scenarios where you needed to get a relative URL from a virtual one in a partial view). Thanks for the helpful tip, Stephen!Happy Programming!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Resolve a URL from a Partial View (ASP.NET MVC)

    Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png. Astandard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:' /The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image.I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl.public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); return MvcHtmlString.Create(urlHelper.Content(url)); }With this method in place you can resolve a URL in a partial view like so:' /Or you could use Stephen's Html.Image extension method (althoughmy more generic Html.ResolveUrl method could be used in non-image related scenarios where you needed to get a relative URL from a virtual one in a partial view). Thanks for the helpful tip, Stephen!Happy Programming!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Resolving an App-Relative URL without a Page Object Reference

    - by Damon
    If you've worked with ASP.NET before then you've almost certainly seen an application-relative URL like ~/SomeFolder/SomePage.aspx.  The tilde at the beginning is a stand in for the application path, and it can easily be resolved using the Page object's ResolveUrl method: string url = Page.ResolveUrl("~/SomeFolder/SomePage.aspx"); There are times, however, when you don't have a page object available and you need to resolve an application relative URL.  Assuming you have an HttpContext object available, the following method will accomplish just that: public static string ResolveAppRelativeUrl(string url) {      return url.Replace("~", System.Web.HttpContext.Current.Request.ApplicationPath); } It just replaces the tilde with the application path, which is essentially all the ResolveUrl method does.

    Read the article

  • mootools slideshow not working with JQuery. Need help !

    - by Shantanu Gupta
    I am working on a site http://tapasya.co.in where i just impemented mootools slideshow. But I noticed that menubar that i was using stopped working, it was supposed to drop horizontaly but it is not being displayed now. I have used jquery for it. Please see the source of the web page. What can be the problem ? Mootools conflicting with javascript or some other problem. If I tries to use $.noConflict() it throws me an error in script Uncaught TypeError: Object function (B,C){if(B&&B.$family&&B.uid){return B}var A=$type(B);return($[A])?$[A](B,C,this.document):null} has no method 'noConflict' I tried the given solution below. But it is not working. <script type="text/javascript" src="<%= ResolveUrl("~/Js/jquery-1.3.2.min.js") %>" ></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/mootools.js") %>"></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/slideshow.js") %>"></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/lightbox.js") %>"></script> <script type="text/javascript"> // <![CDATA[ $.noConflict(); var timeout = 500; var closetimer = 0; var ddmenuitem = 0; function ddmenu_open(){ ddmenu_canceltimer(); ddmenu_close(); ddmenuitem = $(this).find('ul').css('visibility', 'visible'); } function ddmenu_close(){ if(ddmenuitem) ddmenuitem.css('visibility', 'hidden'); } function ddmenu_timer(){ closetimer = window.setTimeout(ddmenu_close, timeout); } function ddmenu_canceltimer(){ if(closetimer){ window.clearTimeout(closetimer); closetimer = null; }} $(document).ready(function(){ $('#ddmenu > li').bind('mouseover', ddmenu_open) $('#ddmenu > li').bind('mouseout', ddmenu_timer) }); document.onclick = ddmenu_close; // ]]> </script> <script type="text/javascript"> //<![CDATA[ window.addEvent('domready', function(){ var data = { '1.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '2.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '3.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '4.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' } }; // Note the use of "linked: true" which tells Slideshow to auto-link all slides to the full-size image. //http://code.google.com/p/slideshow/wiki/Slideshow#Options: var mootoolsSlideshow = new Slideshow('divbanner', data, {loader:true,captions: true, delay: 5000,controller: false, height: 370,linked: false, hu: '<%= ResolveUrl("~/Scripts/SlideShow/Images/") %>', thumbnails: true, width: 1002}); // Here we create the Lightbox instance. // In this case we will use the "close" and "open" callbacks to pause our show while the modal window is visible. var box = new Lightbox({ 'onClose': function(){ this.pause(false); }.bind(mootoolsSlideshow), 'onOpen': function(){ this.pause(true); }.bind(mootoolsSlideshow) }); }); //]]> </script>

    Read the article

  • $.noConflict() not working with mootools slide show. Need help !

    - by Shantanu Gupta
    I am working on a site http://tapasya.co.in where i just impemented mootools slideshow. But I noticed that menubar that i was using stopped working, it was supposed to drop horizontaly but it is not being displayed now. I have used jquery for it. Please see the source of the web page. What can be the problem ? Mootools conflicting with javascript or some other problem. If I tries to use $.noConflict() it throws me an error in script Uncaught TypeError: Object function (B,C){if(B&&B.$family&&B.uid){return B}var A=$type(B);return($[A])?$[A](B,C,this.document):null} has no method 'noConflict' I tried the given solution below. But it is not working. <script type="text/javascript" src="<%= ResolveUrl("~/Js/jquery-1.3.2.min.js") %>" ></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/mootools.js") %>"></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/slideshow.js") %>"></script> <script type="text/javascript" src="<%= ResolveUrl("~/Scripts/SlideShow/js/lightbox.js") %>"></script> <script type="text/javascript"> // <![CDATA[ $.noConflict(); var timeout = 500; var closetimer = 0; var ddmenuitem = 0; function ddmenu_open(){ ddmenu_canceltimer(); ddmenu_close(); ddmenuitem = $(this).find('ul').css('visibility', 'visible'); } function ddmenu_close(){ if(ddmenuitem) ddmenuitem.css('visibility', 'hidden'); } function ddmenu_timer(){ closetimer = window.setTimeout(ddmenu_close, timeout); } function ddmenu_canceltimer(){ if(closetimer){ window.clearTimeout(closetimer); closetimer = null; }} $(document).ready(function(){ $('#ddmenu > li').bind('mouseover', ddmenu_open) $('#ddmenu > li').bind('mouseout', ddmenu_timer) }); document.onclick = ddmenu_close; // ]]> </script> <script type="text/javascript"> //<![CDATA[ window.addEvent('domready', function(){ var data = { '1.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '2.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '3.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' }, '4.jpg': { caption: 'Acoustic Guitar,electric,bass,keyboard, indian vocal traning and Music theory.' } }; // Note the use of "linked: true" which tells Slideshow to auto-link all slides to the full-size image. //http://code.google.com/p/slideshow/wiki/Slideshow#Options: var mootoolsSlideshow = new Slideshow('divbanner', data, {loader:true,captions: true, delay: 5000,controller: false, height: 370,linked: false, hu: '<%= ResolveUrl("~/Scripts/SlideShow/Images/") %>', thumbnails: true, width: 1002}); // Here we create the Lightbox instance. // In this case we will use the "close" and "open" callbacks to pause our show while the modal window is visible. var box = new Lightbox({ 'onClose': function(){ this.pause(false); }.bind(mootoolsSlideshow), 'onOpen': function(){ this.pause(true); }.bind(mootoolsSlideshow) }); }); //]]> </script>

    Read the article

  • Getting Started with jqChart for ASP.NET Web Forms

    - by jqChart
    Official Site | Samples | Download | Documentation | Forum | Twitter Introduction jqChart takes advantages of HTML5 Canvas to deliver high performance client-side charts and graphs across browsers (IE 6+, Firefox, Chrome, Opera, Safari) and devices, including iOS and Android mobile devices. Some of the key features are: High performance rendering. Animaitons. Scrolling/Zoooming. Support for unlimited number of data series and data points. Support for unlimited number of chart axes. True DateTime Axis. Logarithmic and Reversed axis scale. Large set of chart types - Bar, Column, Pie, Line, Spline, Area, Scatter, Bubble, Radar, Polar. Financial Charts - Stock Chart and Candlestick Chart. The different chart types can be easily combined.  System Requirements Browser Support jqChart supports all major browsers: Internet Explorer - 6+ Firefox Google Chrome Opera Safari jQuery version support jQuery JavaScript framework is required. We recommend using the latest official stable version of the jQuery library. Visual Studio Support jqChart for ASP.NET does not require using Visual Studio. You can use your favourite code editor. Still, the product has been tested with several versions of Visual Studio .NET and you can find the list of supported versions below: Visual Studio 2008 Visual Studio 2010 Visual Studio 2012 ASP.NET Web Forms support Supported version - ASP.NET Web Forms 3.5, 4.0 and 4.5 Installation Download and unzip the contents of the archive to any convenient location. The package contains the following folders: [bin] - Contains the assembly DLLs of the product (JQChart.Web.dll) for WebForms 3.5, 4.0 and 4.5. This is the assembly that you can reference directly in your web project (or better yet, add it to your ToolBox and then drag & drop it from there). [js] - The javascript files of jqChart and jqRangeSlider (and the needed libraries). You need to include them in your ASPX page, in order to gain the client side functionality of the chart. The first file is "jquery-1.5.1.min.js" - this is the official jQuery library. jqChart is built upon jQuery library version 1.4.3. The second file you need is the "excanvas.js" javascript file. It is used from the versions of IE, which dosn't support canvas graphics. The third is the jqChart javascript code itself, located in "jquery.jqChart.min.js". The last one is the jqRangeSlider javascript, located in "jquery.jqRangeSlider.min.js". It is used when the chart zooming is enabled. [css] - Contains the Css files that the jqChart and the jqRangeSlider need. [samples] - Contains some examples that use the jqChart. For full list of samples plese visit - jqChart for ASP.NET Samples. [themes] - Contains the themes shipped with the products. It is used from the jqRangeSlider. Since jqRangeSlider supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqRangeSlider as well. You can download any additional themes directly from jQuery UI's ThemeRoller site available here: http://jqueryui.com/themeroller/ or reference them from Microsoft's / Google's CDN. <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.21/themes/smoothness/jquery-ui.css" /> The final result you will have in an ASPX page containing jqChart would be something similar to that (assuming you have copied the [js] to the Script folder and [css] to Content folder of your ASP.NET site respectively). <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="samples_cs.Default" %> <%@ Register Assembly="JQChart.Web" Namespace="JQChart.Web.UI.WebControls" TagPrefix="jqChart" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head runat="server"> <title>jqChart ASP.NET Sample</title> <link rel="stylesheet" type="text/css" href="~/Content/jquery.jqChart.css" /> <link rel="stylesheet" type="text/css" href="~/Content/jquery.jqRangeSlider.css" /> <link rel="stylesheet" type="text/css" href="~/Content/themes/smoothness/jquery-ui-1.8.21.css" /> <script src="<% = ResolveUrl("~/Scripts/jquery-1.5.1.min.js") %>" type="text/javascript"></script> <script src="<% = ResolveUrl("~/Scripts/jquery.jqRangeSlider.min.js") %>" type="text/javascript"></script> <script src="<% = ResolveUrl("~/Scripts/jquery.jqChart.min.js") %>" type="text/javascript"></script> <!--[if IE]><script lang="javascript" type="text/javascript" src="<% = ResolveUrl("~/Scripts/excanvas.js") %>"></script><![endif]--> </head> <body> <form id="form1" runat="server"> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetData" TypeName="SamplesBrowser.Models.ChartData"></asp:ObjectDataSource> <jqChart:Chart ID="Chart1" Width="500px" Height="300px" runat="server" DataSourceID="ObjectDataSource1"> <Title Text="Chart Title"></Title> <Animation Enabled="True" Duration="00:00:01" /> <Axes> <jqChart:CategoryAxis Location="Bottom" ZoomEnabled="true"> </jqChart:CategoryAxis> </Axes> <Series> <jqChart:ColumnSeries XValuesField="Label" YValuesField="Value1" Title="Column"> </jqChart:ColumnSeries> <jqChart:LineSeries XValuesField="Label" YValuesField="Value2" Title="Line"> </jqChart:LineSeries> </Series> </jqChart:Chart> </form> </body> </html>   Official Site | Samples | Download | Documentation | Forum | Twitter

    Read the article

  • changing img src with JQuery but leave pathing info intact?

    - by Kevin Won
    I'm using JQuery to switch out an image src thusly: $("#myImg").attr("src", "../../new.gif"); notice the relative pathing on the new src. Unfortunately, this isn't portable when I deploy my app. In my MVC app I'm using a ResolveUrl() method that will fix the pathing problem for me so it's portable, but now my JQuery image src swapper doesn't work right since it now switches the correctly resolved path to a broken relative one. <img id="myImg" src="<%=ResolveUrl("~/Images/transparent.gif")%>" /> What I want is for JQuery to just flip the actual filename and leave the path untouched. My first thought would be to // pseudocode javascript jquery on my thought on how to approach this prob var oldFullPath = $('#myImg").GetTheImgSrc; var newFileNameWithPathIntact = someRegexAddNewFileNameWithOldPath $("#myImg").attr("src", newFileNameWithPathIntact); but that seems rather gross and un-JQuery to me. Anyone got a better way?

    Read the article

  • Using external javascript files with asp.net MVC

    - by twal
    I have some javascript inwhich I am using such helpers as var url = <%=ResolveUrl("~/controller/action") %> When the javascript is embeded in the .aspx page using the <script> tag everything works fine When I move it out to an external file those scripts that have the helper methods do not work. Other scripts do just the ones with the var url = <%=ResolveUrl("~/controller/action") %> do not. Are these not possible to use in external javascript files?? I would like to get all of my javascript out of the aspx files if I can. thanks!

    Read the article

  • Adding StyleSheets Programmatically in Asp.Net

    - by Braveyard
    I want to add StyleSheets programmatically in the head section but one of the examples I saw seemed to need to many lines of code to add just one style sheet even though I may need a lot: Example Code: HtmlLink css = new HtmlLink(); css.Href = "css/fancyforms.css"; css.Attributes["rel"] = "stylesheet"; css.Attributes["type"] = "text/css"; css.Attributes["media"] = "all"; Page.Header.Controls.Add(css); I also use Page.Header.RenderControl() method but it didn't work either. Object null something error was thrown. I also used Page.Header.InnerHtml and InnerText += "<link .... "/> things but they threw the Literal error which is I think common error. I used this code : List<Literal> cssFiles = new List<Literal>(); cssFiles.Add(new Literal() { Text = @"<link href=""" + ResolveUrl("~/Resources/Styles/MainMaster/MainDesign.css") + @""" type=""text/css"" rel=""stylesheet"" />" }); cssFiles.Add(new Literal() { Text = @"<link href=""" + ResolveUrl("~/Resources/Styles/MainMaster/MainLayout.css") + @""" type=""text/css"" rel=""stylesheet"" />" }); AddStyleRange(cssFiles); private void AddStyleRange(List<Literal> cssFiles) { foreach (Literal item in cssFiles) { this.Header.Controls.Add(item); } } It worked at first but when I change the pages it stopped working. I am using Master Page and I am writing these codes on Master.cs file and also some people recommended to use this.Header instead of Page.Header but when I built it throws an error which says I cannot declare that like this. It shouldn't be that hard to add many styles. It is getting complicated.

    Read the article

  • Loading jQuery Consistently in a .NET Web App

    - by Rick Strahl
    One thing that frequently comes up in discussions when using jQuery is how to best load the jQuery library (as well as other commonly used and updated libraries) in a Web application. Specifically the issue is the one of versioning and making sure that you can easily update and switch versions of script files with application wide settings in one place and having your script usage reflect those settings in the entire application on all pages that use the script. Although I use jQuery as an example here, the same concepts can be applied to any script library - for example in my Web libraries I use the same approach for jQuery.ui and my own internal jQuery support library. The concepts used here can be applied both in WebForms and MVC. Loading jQuery Properly From CDN Before we look at a generic way to load jQuery via some server logic, let me first point out my preferred way to embed jQuery into the page. I use the Google CDN to load jQuery and then use a fallback URL to handle the offline or no Internet connection scenario. Why use a CDN? CDN links tend to be loaded more quickly since they are very likely to be cached in user's browsers already as jQuery CDN is used by many, many sites on the Web. Using a CDN also removes load from your Web server and puts the load bearing on the CDN provider - in this case Google - rather than on your Web site. On the downside, CDN links gives the provider (Google, Microsoft) yet another way to track users through their Web usage. Here's how I use jQuery CDN plus a fallback link on my WebLog for example: <!DOCTYPE HTML> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script> if (typeof (jQuery) == 'undefined') document.write(unescape("%3Cscript " + "src='/Weblog/wwSC.axd?r=Westwind.Web.Controls.Resources.jquery.js' %3E%3C/script%3E")); </script> <title>Rick Strahl's Web Log</title> ... </head>   You can see that the CDN is referenced first, followed by a small script block that checks to see whether jQuery was loaded (jQuery object exists). If it didn't load another script reference is added to the document dynamically pointing to a backup URL. In this case my backup URL points at a WebResource in my Westwind.Web  assembly, but the URL can also be local script like src="/scripts/jquery.min.js". Important: Use the proper Protocol/Scheme for  for CDN Urls [updated based on comments] If you're using a CDN to load an external script resource you should always make sure that the script is loaded with the same protocol as the parent page to avoid mixed content warnings by the browser. You don't want to load a script link to an http:// resource when you're on an https:// page. The easiest way to use this is by using a protocol relative URL: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> which is an easy way to load resources from other domains. This URL syntax will automatically use the parent page's protocol (or more correctly scheme). As long as the remote domains support both http:// and https:// access this should work. BTW this also works in CSS (with some limitations) and links. BTW, I didn't know about this until it was pointed out in the comments. This is a very useful feature for many things - ah the benefits of my blog to myself :-) Version Numbers When you use a CDN you notice that you have to reference a specific version of jQuery. When using local files you may not have to do this as you can rename your private copy of jQuery.js, but for CDN the references are always versioned. The version number is of course very important to ensure you getting the version you have tested with, but it's also important to the provider because it ensures that cached content is always correct. If an existing file was updated the updates might take a very long time to get past the locally cached content and won't refresh properly. The version number ensures you get the right version and not some cached content that has been changed but not updated in your cache. On the other hand version numbers also mean that once you decide to use a new version of the script you now have to change all your script references in your pages. Depending on whether you use some sort of master/layout page or not this may or may not be easy in your application. Even if you do use master/layout pages, chances are that you probably have a few of them and at the very least all of those have to be updated for the scripts. If you use individual pages for all content this issue then spreads to all of your pages. Search and Replace in Files will do the trick, but it's still something that's easy to forget and worry about. Personaly I think it makes sense to have a single place where you can specify common script libraries that you want to load and more importantly which versions thereof and where they are loaded from. Loading Scripts via Server Code Script loading has always been important to me and as long as I can remember I've always built some custom script loading routines into my Web frameworks. WebForms makes this fairly easy because it has a reasonably useful script manager (ClientScriptManager and the ScriptManager) which allow injecting script into the page easily from anywhere in the Page cycle. What's nice about these components is that they allow scripts to be injected by controls so components can wrap up complex script/resource dependencies more easily without having to require long lists of CSS/Scripts/Image includes. In MVC or pure script driven applications like Razor WebPages  the process is more raw, requiring you to embed script references in the right place. But its also more immediate - it lets you know exactly which versions of scripts to use because you have to manually embed them. In WebForms with different controls loading resources this often can get confusing because it's quite possible to load multiple versions of the same script library into a page, the results of which are less than optimal… In this post I look a simple routine that embeds jQuery into the page based on a few application wide configuration settings. It returns only a string of the script tags that can be manually embedded into a Page template. It's a small function that merely a string of the script tags shown at the begging of this post along with some options on how that string is comprised. You'll be able to specify in one place which version loads and then all places where the help function is used will automatically reflect this selection. Options allow specification of the jQuery CDN Url, the fallback Url and where jQuery should be loaded from (script folder, Resource or CDN in my case). While this is specific to jQuery you can apply this to other resources as well. For example I use a similar approach with jQuery.ui as well using practically the same semantics. Providing Resources in ControlResources In my Westwind.Web Web utility library I have a class called ControlResources which is responsible for holding resource Urls, resource IDs and string contants that reference those resource IDs. The library also provides a few helper methods for loading common scriptscripts into a Web page. There are specific versions for WebForms which use the ClientScriptManager/ScriptManager and script link methods that can be used in any .NET technology that can embed an expression into the output template (or code for that matter). The ControlResources class contains mostly static content - references to resources mostly. But it also contains a few static properties that configure script loading: A Script LoadMode (CDN, Resource, or script url) A default CDN Url A fallback url They are  static properties in the ControlResources class: public class ControlResources { /// <summary> /// Determines what location jQuery is loaded from /// </summary> public static JQueryLoadModes jQueryLoadMode = JQueryLoadModes.ContentDeliveryNetwork; /// <summary> /// jQuery CDN Url on Google /// </summary> public static string jQueryCdnUrl = "//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"; /// <summary> /// jQuery CDN Url on Google /// </summary> public static string jQueryUiCdnUrl = "//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"; /// <summary> /// jQuery UI fallback Url if CDN is unavailable or WebResource is used /// Note: The file needs to exist and hold the minimized version of jQuery ui /// </summary> public static string jQueryUiLocalFallbackUrl = "~/scripts/jquery-ui.min.js"; } These static properties are fixed values that can be changed at application startup to reflect your preferences. Since they're static they are application wide settings and respected across the entire Web application running. It's best to set these default in Application_Init or similar startup code if you need to change them for your application: protected void Application_Start(object sender, EventArgs e) { // Force jQuery to be loaded off Google Content Network ControlResources.jQueryLoadMode = JQueryLoadModes.ContentDeliveryNetwork; // Allow overriding of the Cdn url ControlResources.jQueryCdnUrl = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"; // Route to our own internal handler App.OnApplicationStart(); } With these basic settings in place you can then embed expressions into a page easily. In WebForms use: <!DOCTYPE html> <html> <head runat="server"> <%= ControlResources.jQueryLink() %> <script src="scripts/ww.jquery.min.js"></script> </head> In Razor use: <!DOCTYPE html> <html> <head> @Html.Raw(ControlResources.jQueryLink()) <script src="scripts/ww.jquery.min.js"></script> </head> Note that in Razor you need to use @Html.Raw() to force the string NOT to escape. Razor by default escapes string results and this ensures that the HTML content is properly expanded as raw HTML text. Both the WebForms and Razor output produce: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> if (typeof (jQuery) == 'undefined') document.write(unescape("%3Cscript src='/WestWindWebToolkitWeb/WebResource.axd?d=-b6oWzgbpGb8uTaHDrCMv59VSmGhilZP5_T_B8anpGx7X-PmW_1eu1KoHDvox-XHqA1EEb-Tl2YAP3bBeebGN65tv-7-yAimtG4ZnoWH633pExpJor8Qp1aKbk-KQWSoNfRC7rQJHXVP4tC0reYzVw2&t=634535391996872492' type='text/javascript'%3E%3C/script%3E"));</script> <script src="scripts/ww.jquery.min.js"></script> </head> which produces the desired effect for both CDN load and fallback URL. The implementation of jQueryLink is pretty basic of course: /// <summary> /// Inserts a script link to load jQuery into the page based on the jQueryLoadModes settings /// of this class. Default load is by CDN plus WebResource fallback /// </summary> /// <param name="url"> /// An optional explicit URL to load jQuery from. Url is resolved. /// When specified no fallback is applied /// </param> /// <returns>full script tag and fallback script for jQuery to load</returns> public static string jQueryLink(JQueryLoadModes jQueryLoadMode = JQueryLoadModes.Default, string url = null) { string jQueryUrl = string.Empty; string fallbackScript = string.Empty; if (jQueryLoadMode == JQueryLoadModes.Default) jQueryLoadMode = ControlResources.jQueryLoadMode; if (!string.IsNullOrEmpty(url)) jQueryUrl = WebUtils.ResolveUrl(url); else if (jQueryLoadMode == JQueryLoadModes.WebResource) { Page page = new Page(); jQueryUrl = page.ClientScript.GetWebResourceUrl(typeof(ControlResources), ControlResources.JQUERY_SCRIPT_RESOURCE); } else if (jQueryLoadMode == JQueryLoadModes.ContentDeliveryNetwork) { jQueryUrl = ControlResources.jQueryCdnUrl; if (!string.IsNullOrEmpty(jQueryCdnUrl)) { // check if jquery loaded - if it didn't we're not online and use WebResource fallbackScript = @"<script type=""text/javascript"">if (typeof(jQuery) == 'undefined') document.write(unescape(""%3Cscript src='{0}' type='text/javascript'%3E%3C/script%3E""));</script>"; fallbackScript = string.Format(fallbackScript, WebUtils.ResolveUrl(ControlResources.jQueryCdnFallbackUrl)); } } string output = "<script src=\"" + jQueryUrl + "\" type=\"text/javascript\"></script>"; // add in the CDN fallback script code if (!string.IsNullOrEmpty(fallbackScript)) output += "\r\n" + fallbackScript + "\r\n"; return output; } There's one dependency here on WebUtils.ResolveUrl() which resolves Urls without access to a Page/Control (another one of those features that should be in the runtime, not in the WebForms or MVC engine). You can see there's only a little bit of logic in this code that deals with potentially different load modes. I can load scripts from a Url, WebResources or - my preferred way - from CDN. Based on the static settings the scripts to embed are composed to be returned as simple string <script> tag(s). I find this extremely useful especially when I'm not connected to the internet so that I can quickly swap in a local jQuery resource instead of loading from CDN. While CDN loading with the fallback works it can be a bit slow as the CDN is probed first before the fallback kicks in. Switching quickly in one place makes this trivial. It also makes it very easy once a new version of jQuery rolls around to move up to the new version and ensure that all pages are using the new version immediately. I'm not trying to make this out as 'the' definite way to load your resources, but rather provide it here as a pointer so you can maybe apply your own logic to determine where scripts come from and how they load. You could even automate this some more by using configuration settings or reading the locations/preferences out of some sort of data/metadata store that can be dynamically updated instead via recompilation. FWIW, I use a very similar approach for loading jQuery UI and my own ww.jquery library - the same concept can be applied to any kind of script you might be loading from different locations. Hopefully some of you find this a useful addition to your toolset. Resources Google CDN for jQuery Full ControlResources Source Code ControlResource Documentation Westwind.Web NuGet This method is part of the Westwind.Web library of the West Wind Web Toolkit or you can grab the Web library from NuGet and add to your Visual Studio project. This package includes a host of Web related utilities and script support features. © Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  jQuery   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

1 2 3  | Next Page >