Source file: Canabalt.swf
Source file: barbarian-onslaught--3991.swf
Source file: Canabalt wide mega.swf
Source file: Canabalt wide normal.swf
Source file: Canabalt.swf
Source file: barbarian-onslaught--3991.swf
Source file: Canabalt wide mega.swf
Source file: Canabalt wide normal.swf
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.
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 |
| CurrentExecutionFilePath FilePath Path | All of these return the full root relative logical path to the script page including path and scriptname. /webstore/admin/paths.aspx |
| AppRelativeCurrentExecutionFilePath | Returns an ASP.NET root relative virtual path to the script or path ~/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 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:
You should be able to get any necessary format from ASP.NET from just about any path or script using these mechanisms.
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 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).
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).
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 |
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();
Trovato qui.
SET NOCOUNT ON;
DECLARE @tblTmpViews TABLE (view_name varchar(100));
DECLARE @view_name nvarchar(100);
INSERT @tblTmpViews SELECT [name] FROM sysobjects WHERE xtype='V';
DELETE @tblTmpViews WHERE view_name IN ('tax_OrfaniSanguinettiVP_vl', 'tax_OrfaniSanguinettiFS_vl', 'tax_OrfaniSanguinettiVU_vl');
DELETE @tblTmpViews WHERE view_name LIKE '%ven_RicercaContratti_vl%';
DECLARE crsrViews CURSOR FOR SELECT view_name FROM @tblTmpViews ORDER BY view_name;
OPEN crsrViews;
FETCH NEXT FROM crsrViews INTO @view_name;
WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Refreshing view ' + @view_name + '...' EXEC sp_refreshview @view_name FETCH NEXT FROM crsrViews INTO @view_name END CLOSE crsrViews;
DEALLOCATE crsrViews;
PRINT '';
PRINT 'Refresh done successfully.';
SET NOCOUNT OFF;SET NOCOUNT ON; DECLARE @tblTmpViews TABLE (view_name varchar(100)); DECLARE @view_name nvarchar(100); INSERT @tblTmpViews SELECT [name] FROM sysobjects WHERE xtype='V'; DELETE @tblTmpViews WHERE view_name IN ('tax_OrfaniSanguinettiVP_vl', 'tax_OrfaniSanguinettiFS_vl', 'tax_OrfaniSanguinettiVU_vl'); DELETE @tblTmpViews WHERE view_name LIKE '%ven_RicercaContratti_vl%'; DECLARE crsrViews CURSOR FOR SELECT view_name FROM @tblTmpViews ORDER BY view_name; OPEN crsrViews; FETCH NEXT FROM crsrViews INTO @view_name; WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Refreshing view ' + @view_name + '...' EXEC sp_refreshview @view_name FETCH NEXT FROM crsrViews INTO @view_name END CLOSE crsrViews; DEALLOCATE crsrViews; PRINT ''; PRINT 'Refresh done successfully.'; SET NOCOUNT OFF;
' Invoke a method via reflection and return its result - return null if method
' doesn't exist or throws
' Note: requires Imports System.Reflection
'
' Example:
' Function GetCompleteName(ByVal firstName As String,
' ByVal lastName As String)
' Return lastName & ", " & firstName
' End Function
' ...
' MessageBox.Show(InvokeMethod(Me, "GetCompleteName", False, "Marco",
' "Bellinaso"))
Function InvokeMethod(ByVal obj As Object, ByVal methodName As String, _
ByVal throwIfError As Boolean, ByVal ParamArray args() As Object) As Object
Try
Return obj.GetType().InvokeMember(methodName, BindingFlags.Instance Or _
BindingFlags.InvokeMethod Or BindingFlags.Public, Nothing, obj, _
args)
Catch ex As Exception
If throwIfError Then Throw ex
End Try
' if method doesn't exists or throws
Return Nothing
End Function
Trovato qui.
Here's an easy way to check if a temp table exists, before trying to create it (ie. for reusable scripts):
IF object_id('tempdb..#MyTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyTempTable
END
CREATE TABLE #MyTempTable
(
ID int IDENTITY(1,1),
SomeValue varchar(100)
)
GO
That way, if you have to change databases in the query window, you don't have to drop the tables before you run it again.
Trovato qui.
This article was previously published under Q327084
Microsoft Visual Basic version 6.0 cannot use the .NET method with the ParamArray parameter in Microsoft Visual Studio .NET. A compile-time error is generated by Visual Basic version 6.0 when it tries to consume the .NET method that has the ByRef ParamArray parameter or theByRef Structure parameter.
When the .NET method has the ByRef ParamArray parameter, you receive the following error message:
Compile error:
Function or interface marked as restricted, or the function uses an Automation type not supported in Visual Basic
When the .NET method has the ByRef Structure parameter, you receive the following error message:
Compile error:
User-defined type may not be passed ByVal
This problem occurs because Visual Basic version 6.0 does not let the ParamArray parameter and the Structure parameter be passed to the BYVAL value. This problem occurs with a .NET property because a .NET property does not let property parameters be defined by the BYREF value.
To work around this problem, you can define the ParamArray parameter and the Structureparameter as BYREF. For a property, you can add a method with the ByRef parameter that assigns the property to the private member.
Microsoft has confirmed that this is a bug in the Microsoft products that are listed in the "Applies to" section.
<ComClass()> Public Class Class1
Dim _res(4) As Byte
Public Property res() As Byte()
Get
Return _res
End Get
Set(ByVal Value As Byte())
_res = Value
End Set
End Property
Public Structure s1
Public i As Integer
dim j as integer
End Structure
Dim _mes As s1
Public Property mes() As s1
Get
Return _mes
End Get
Set(ByVal Value As s1)
_mes = Value
End Set
End Property
Public Sub setArrayProp(ByRef Value As Byte())
_res = Value
End Sub
Public Sub setStructProp(ByRef Value As s1)
_mes = Value
End Sub
End Class
Private Sub Command1_Click()
Dim cls As New Class1
Dim arr() As Byte
Dim s As s1
arr = cls.res
'cls.res = arr
s = cls.mes
'cls.mes = s
Call cls.setArrayProp(arr)
Call cls.setStructProp(s)
End Sub
Trovato qui.
Gli HTTP Handler sono dei meccanismi di ASP.NET che si occupano di elaborare le risposte a specifiche richieste HTTP e fornirle, secondo la forma più consona, al richiedente.
Questo Generic Handler restituisce un'immagine a caso tra quelle presenti in una directory di un sito web.
Si tratta di un file con estensione .ashx che non ha bisogno di essere compilato, né di essere registrato nel file web.config. Basterà solamente far riferimento ad esso come URL di un'immagine, indipendentemente da dove questo sia utilizzato.
Ad esempio, supponendo di chiamare il nostro file ImmagineCasuale.ashx e di metterlo nella root del sito web www.miosito.it, potremmo utilizzarlo per visualizzare un'immagine casuale In diversi modi.
<img src="/ImmagineCasuale.ashx" alt="immagine casuale"/>
div.intestazione {
background-image: url (/ImmagineOraria.ashx);
}
<asp:Image ID="ImmagineCasuale" runat="server" ImageUrl="~/ImmagineCasuale.ashx"
AlternateText="Immagine Casuale" />
E' possibile, inoltre, chiedere l'immagine casuale da un altro sito, sarà sufficiente indicare l'URL completo: http://www.miosito.it/ImmagineCasuale.ashx
Ecco il codice:
<%@ WebHandler Language="VB" Class="ImmagineCasuale" %>
Imports System
Imports System.Web
Public Class ImmagineCasuale : Implements IHttpHandler
' qui indico la directory in cui ci sono le immagini
Const DIRIMMAGINI = "immagini/fotocasuali"
' implementazione del metodo
Public Sub ProcessRequest(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
' metto i nomi dei file .jpg in un array
' (potrei farlo anche per altre estensioni)
Dim nomiFileImmagine() As String = _
System.IO.Directory.GetFiles(context.Server.MapPath(DIRIMMAGINI), "*.jpg")
' se ci sono immagini ne estraggo una a caso e la invio come HttpResponse
If nomiFileImmagine.Length > 0 Then
Dim n As Integer
Dim vMax As Integer
vMax = nomiFileImmagine.GetUpperBound(0)
Randomize()
n = CInt(Int((vMax + 1) * Rnd()))
Dim response As Web.HttpResponse = context.Response
response.ContentType = "image/jpeg"
response.Cache.SetCacheability(HttpCacheability.Public)
response.BufferOutput = False
response.WriteFile(nomiFileImmagine(n))
response.End()
End If
End Sub
' poiché si tratta di sola lettura imposto IsReusable a True
Public ReadOnly Property IsReusable() As Boolean _
Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
Un esempio di possibile utilizzo potrebbe essere un banner pubblicitario di una pagina web, in cui ad ogni richiesta lo sponsor varia casualmente.
Possibili varianti: cambiare la directory o scegliere l'immagine a seconda dei parametri passati attraverso una QueryString, oppure scegliere l'immagine a seconda dell'ora.
In quest'ultimo caso il codice potrebbe essere:
<%@ WebHandler Language="VB" Class="ImmagineOraria" %>
Imports System
Imports System.Web
Public Class ImmagineOraria : Implements IHttpHandler
Const DIRIMMAGINI = "immagini/orarie"
Public Sub ProcessRequest(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
Dim nomiFileImmagine() As String = _
{"mattino", "giorno", "pomeriggio", "sera", "notte"}
Dim n, ora As Integer
ora = DateTime.Now.Hour
Select Case ora
Case 22 To 24, 0 To 6
n = 4
Case 7 To 9
n = 0
Case 17 To 19
n = 2
Case 20 To 21
n = 3
Case Else
n = 1
End Select
Dim response As Web.HttpResponse = context.Response
response.ContentType = "image/jpeg"
response.Cache.SetCacheability(HttpCacheability.Public)
response.BufferOutput = False
response.WriteFile(context.Server.MapPath(DIRIMMAGINI & _
nomiFileImmagine(n) & ".jpg"))
response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean _
Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
Trovato qui.