How to do it?
I don't want to use this:
HttpContext.Current.Server.MapPath
Is there a similar function that I can call without requiring a httpcontext?
For example if a start a thread doing some stuff i cant use the httpcontext, but i still need to get the path of the app. And no i can't pass the context as an argument or read it from a shared var.
Use the HttpRuntime.AppDomainAppPath property.
There are several options:
HttpRuntime.AppDomainAppPath
WebApplication -> Web root folder
UnitTest -> ArgumentNullException
ConsoleApplication -> ArgumentNullException
AppDomain.CurrentDomain.BaseDirectory
WebApplication -> Web root folder
UnitTest -> ...\AppDir\bin\Debug
ConsoleApplication -> ...\AppDir\bin\Debug
HostingEnvironment.ApplicationPhysicalPath
WebApplication -> Web root folder
UnitTest -> null
ConsoleApplication -> null
I would recommend to use AppDomain.CurrentDomain.BaseDirectory, because it can be used in any type of project and it can be set up.
You can for example set UnitTest BaseDirectory to point your web root folder the AppDomain.CurrentDomain.BaseDirectory by command:
AppDomain.CurrentDomain.SetData("APPBASE", "path to your web root");
I have run across this question when looking for way to compute an URL (permalinks in the Web application) to provide in some e-mail notifications.
These were generated on another thread, so HttpContext was not available and I wanted to avoid putting URL related information in the queue table used to generate the e-mails.
The code:
public static String GetCurrentAppDomainBasePath(String prefix = "http://")
{
return String.Format("{0}{1}{2}",
prefix,
System.Net.Dns.GetHostEntry("").HostName,
System.Web.HttpRuntime.AppDomainAppVirtualPath
);
}
The function returns the full virtual path like: http://full-host-name/AppName. Of course, there are some limitations: hardcoded protocol (http, https etc.) and using hostname instead of domain name (fails if multiple domains are defined on a single machine).
Related
I'm developing a WebApp using JavaEE and I use a servlet to test some stuff.
Currently, my WebApp is set as when I go to my local url localhost:8080/myApp/test , I can run my test Servlet.
My plan is to deploy my project to a Web and I want to disable the Servlet, but not delete it. I mean, if in the future I visit my remote server via URL www.myNewWeb.com/test , I would like it throws an error od do nothing.
How could I do that?
There are many possible options here:
Option 1
Remove the mapping (annotation #WebServlet or url mapping entry in web.xml). In this case, any attempt to call this servlet will end with an error generated by the JEE container of your choice. It will try to map the servlet to URL, will obviously fail and throw an exception
The obvious drawback of this method is that you need to change the deployment configuration and if you'll want to run the same artifact in another envrironment where this servlet should work you won't be able to do so.
Option 2
Create some kind of configuration, load this configuration along with your application.
In the doGet (just for the sake of example) method do something like this:
public void doGet(request, response) {
if(config.isTestServletEnabled()) { // this is where the data gets read from configuration that I've talked about before
// do your regular processing here
}
else {
// this will happen when the servlet should not be activated
// throw an exception, return HTTP error code of your choice, etc
}
}
This way doesn't have a drawback of the first method that I've explained above, however involves some code to be written.
I have created a WFC RIA Service based on ASP.Net Website and adding the nuget packages for RIA service. I have also created a Service named "FactoryService" by extending DomainService class.
I have tested the service by creating a GridView with DomainDataSource pointing to the service. The service is working.
Now I want to access the service from other clients as I have enabled SOAP endpoint. But I cannot find the service's url to the svc file. I need this url to add service reference to my other projects. How do I find the service url?
I have tried the following urls and all returns 404. (namespace "WebApplication3", DomainService class "FactoryService").
- http://localhost:15066/WebApplication3-FactoryService.svc
- http://localhost:15066/services/WebApplication3-FactoryService.svc
- http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc
- http://localhost:15066/FactoryService.svc
- http://localhost:15066/services/FactoryService.svc
- http://localhost:15066/ClientBin/FactoryService.svc
I have found the problem. In the DomainService class, I missed to annotate it with [EnableClientAccess()].
A domain service class must be marked with the
EnableClientAccessAttribute attribute to make the service available to
the client project. The EnableClientAccessAttribute attribute is
automatically applied to a domain service when you select the Enable
client access check box in the Add New Domain Service Class dialog
box.
As I'm using VS2013, the wizard is not available and missed to annotate it with the attribute.
Normally it has the following form
Base-Address + ClientBin + FullName of DomainService (Namespace+TypeName separated by -)
So in your case it should look like
http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc
When you access this link in a Browser you will be provided a page that looks similar to this
Service
You have created a service.
To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:
svcutil.exe http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc?wsdl
You can also access the service description as a single file:
http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc?singleWsdl
This will generate a configuration file and a code file that contains the client class. Add the two files to your client application and use the generated client class to call the Service. For example:
C#
class Test
{
static void Main()
{
HelloClient client = new HelloClient();
// Use the 'client' variable to call operations on the service.
// Always close the client.
client.Close();
}
}
Visual Basic
Class Test
Shared Sub Main()
Dim client As HelloClient = New HelloClient()
' Use the 'client' variable to call operations on the service.
' Always close the client.
client.Close()
End Sub
End Class
I have a windows service which is using a method from a class library with same asp.net solution. in class library, I have a method with following line:
reader = XmlReader.Create(HttpContext.Current.Server
.MapPath("~/TestDevice/Data.xml"), settings);
When control comes to this line. I get exception. I tried to debug the code and found that when service tries to access this method then HttpContext.Current.Server is null. What is alternative syntax.
I tried to access this class library method from web application and it works fine.
Please suggest solution.
HttpContext.Current is returning null because your Windows Service is not running under the umbrella of IIS or some other web server provder.
However, you can find the executing path of your service using reflection:
System.Reflection.Assembly.GetExecutingAssembly().Location
^ should return the path of the executing service..
This method works much better:
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
It could be that when you are using windows service, you are no longer running a web app, therefore HttpContext and web server is not available. Try using System.IO.File for mapping, see whether that takes you to the correct directory.
Edit
private String yourFullPath = System.IO.Path.GetFullPath("/YourDirectory") + #"\";
I am currently in a dev only phase of development, and am using the VS built-in web server, configured for a fixed port number. I am using the following code, in my MembershipService class, to build an email body with a confirmation link, but obviously this must change when I deploy to our prod host.
var url = string.Format("http://localhost:59927/Account/CompleteRegistration/{0}", newMember.PendingReplyId);
How can I build this URL to always reflect the host that the code is running on, e.g. when deployed to prod the URL should be http://our-live-domain.com/Account/..etc.
MORE INFO: This URL will is included in an email to a new user busy registering an account, so I cannot use a relative URL.
Have a setting for this in your web.config
Like this:
<appSettings>
<add key="BaseURL" value="http://localhost:59927/"/>
</appSettings>
Access the value from the code. If you store multiple values in the appSettings and use them all over your project, I'd avise to use a wrapper class.
public class AppSettingsWrapper
{
public static String BaseURL
{
get { return System.Configuration.ConfigurationManager.AppSettings["BaseURL"].ToString(); }
}
// you can also insert other values here, that need to be cast into a specific datatype
public static int DefaultPageID
{
get { return int.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultPageID"].ToString()); }
}
}
You can assemble your string like this:
String url = string.Format("{0}{1}", AppSettingsWrapper.BaseURL, ResolveUrl(String.Format("~/Account/CompleteRegistration/{0}", newMember.PendingReplyId)));
Upon deployment, you need to replace the settings from the appSettings section. You can do this by using web config transforms. Have a look at this article http://www.tomot.de/en-us/article/5/asp.net/how-to-use-web.config-transforms-to-replace-appsettings-and-connectionstrings, which shows you how to this. You would create solution configurations for your testserver and your production server
use appSettings section in web.conf it will allow you to configure setting for production server.
and use ConfigurationManager class for acces to appSetting section.
While you can always set the host name and port as a setting which can then be read at run time (Very useful if the machine you have has multiple host headers, which might be in the case of load balancing). You can work out the Url from the following components :
Request["SCRIPT_NAME"] eg "/default.aspx"
Request["SERVER_NAME"] eg "localhost"
Request["SERVER_PORT"] eg "80"
Hope that this helps.
Jonathan
new Uri(
Request.Url, // base URI from current context
"/Account/CompleteRegistration/1234" // address relative to the base URI, use / if needed
).ToString();
This results in http://your.server/Account/CompleteRegistration/1234 .
It works great for relative links, even if our current location is not root:
new Uri(
Request.Url, // we are at http://server/app/subfolder/page.aspx?q=1
"page2.aspx"
).ToString(); //produces http://server/app/subfolder/page2.aspx
BTW, since it's of System.Uri type (unlike Request.RawUrl which is a relative path string), it has tons of useful properties, but typically you will just use .ToString().
Although you can't use ~ (tilde) paths directly, it's very simple to resolve them, and you should do it when in doubt:
new Uri(
Request.Url,
Page.ResolveUrl("~/folder/test") // use this! tilde is your friend!!!
).ToString(); // this will always point to our app even if it's in a virtual folder instead of root
I have a classic ASP page - written in JScript - that's using Scripting.FileSystemObject to save files to a network share - and it's not working. ("Permission denied")
The ASP page is running under IIS using Windows authentication, with impersonation enabled.
If I run the following block of code locally via CScript.exe:
var objNet = new ActiveXObject("WScript.Network");
WScript.Echo(objNet.ComputerName);
WScript.Echo(objNet.UserName);
WScript.Echo(objNet.UserDomain);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "\\\\myserver\\my_share\\some_path";
if (fso.FolderExists(path)) {
WScript.Echo("Yes");
} else {
WScript.Echo("No");
}
I get the (expected) output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
Yes
If I run the same code as part of a .ASP page, substituting Response.Write for WScript.Echo I get this output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
No
Now - my understanding is that the WScript.Network object will retrieve the current security credentials of the thread that's actually running the code. If this is correct - then why is the same user, on the same domain, getting different results from CScript.exe vs ASP? If my ASP code is running as dylan.beattie, then why can't I see the network share? And if it's not running as dylan.beattie, why does WScript.Network think it is?
Your problem is clear. In the current implementation you have only impersonation of users and no delegation. I don't want to repeat information already written by Stephen Martin. I only want to add at least three solutions. The classical way of delegation which Stephen Martin suggests is only one way. You can read some more ways here: http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_delegation. I see three practical ways of you solving your problem:
Convert the impersonation token of the user to a token with delegation level of impersonation or to a new primary token. You can do this with respect of DuplicateToken or DuplicateTokenEx.
Use S4U2Self (see http://msdn.microsoft.com/en-us/magazine/cc188757.aspx and http://msdn.microsoft.com/en-us/library/ms998355.aspx) to receive a new token from the old one with respect of one simple .NET statement WindowsIdentity wi = new WindowsIdentity(identity);
You can access another server with respect of one fixed account. It can be a computer account on an account of the application pool of the IIS. It can be another fixed defined account which one will only use for access to the file system.
It is important to know which version of Windows Server you have on the server where IIS is running and which Domain Function Level you have in Active Directory for your Domain (you see this in "Active Directory Domain and Trusts" tool if you select your domain and choose "Raise Domain Functional Level"). It is also interesting to know under which account the application pool of the IIS runs.
The first and the third way will always work. The third way can be bad for your environment and for the current permission in the file system. The second one is very elegant. It allows control of which servers (file server) are accessed from IIS. This way has some restrictions and it needs some work to be done in Active Directory.
Because you use classic ASP, a small scriptable software component must be created to support your implementation.
Which way do you prefer?
UPDATED based on the question from comment: Because you use classic ASP you can not use a Win32 API directly, but you can write a small COM component in VB6 or in .NET which use APIs which you need. As an example you can use code from http://support.microsoft.com/kb/248187/en. But you should do some other things inside. So I explain now which Win32 API can help you to do everything what you need with tokens and impersonation.
First of all a small explanation about impersonation. Everything works very easy. There are always one primary token under which the process runs. To any thread another token (thread token) can be assigned. To do this one needs to have a token of a user hUserToken and call API ImpersonateLoggedOnUser(hUserToken);.
To go back to the original process token (for the current thread only) you can call RevertToSelf() function. The token of user will be received and already impersonated for you by IIS, because you so configured your Web Site. To go back to the original process token you should implement calling of the function RevertToSelf() in your custom COM component. Probably, if you need to do nothing more in the ASP page, it will be enough, but I recommend you be more careful and save current users token in a variable before operation with files. Then you make all operations with file system and at the end reassign users token back to the current thread. You can assign an impersonation token to a thread with respect of SetThreadToken(NULL,hUserToken);. To give (save) current thread token (user token in your case) you can use OpenThreadToken API. It must work.
UPDATED 2: Probably the usage of RevertToSelf() function at the end of one ASP page would be already OK for you. The corresponding C# code can be so:
Create a new Project in C# of the type "Class Library" with the name LoginAdmin. Paste the following code inside
using System;
using System.Runtime.InteropServices;
namespace LoginAdmin {
[InterfaceTypeAttribute (ComInterfaceType.InterfaceIsDual)]
public interface IUserImpersonate {
[DispId(1)]
bool RevertToSelf ();
}
internal static class NativeMethods {
[DllImport ("advapi32.dll", SetLastError = true)]
internal static extern bool RevertToSelf ();
}
[ClassInterface (ClassInterfaceType.AutoDual)]
public class UserImpersonate : IUserImpersonate {
public UserImpersonate () { }
public bool RevertToSelf () {
return NativeMethods.RevertToSelf();
}
}
}
Check in project properties in "Build" part "Register for COM interop". In "Signing" part of the project check Sign the assembly and in "Choose a strong name key file" choose <New...>, then type any filename and password (or check off "protect my key..."). At the end you should modify a line from AssemblyInfo.cs in Properties part of the project:
[assembly: ComVisible (true)]
After compiling this project you get two files, LoginAdmin.dll and LoginAdmin.tlb. The DLL is already registered on the current computer. To register if on the other computer use RegAsm.exe.
To test this COM DLL on a ASP page you can do following
<%# Language="javascript" %>
<html><body>
<% var objNet = Server.CreateObject("WScript.Network");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var objLoginAdmin = Server.CreateObject("LoginAdmin.UserImpersonate");
var isOK = objLoginAdmin.RevertToSelf();
if (isOK)
Response.Write("RevertToSelf return true<br/>");
else
Response.Write("RevertToSelf return false<br/>");
Response.Write("One more time after RevertToSelf()<br/>");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var fso = Server.CreateObject("Scripting.FileSystemObject");
var path = "\\\\mk01\\C\\Oleg";
if (fso.FolderExists(path)) {
Response.Write("Yes");
} else {
Response.Write("No");
}%>
</body></html>
If the account used to run the IIS application pool has access to the corresponding network share, the output will be look like following
Current user: Oleg
Current user's domain: WORKGROUP
RevertToSelf return true
One more time after RevertToSelf()
Current user: DefaultAppPool
Current user's domain: WORKGROUP
Yes
Under impersonation you can only access securable resources on the local computer you cannot access anything over the network.
On Windows when you are running as an impersonated user you are running under what is called a Network token. This token has the user's credentials for local computer access but has no credentials for remote access. So when you access the network share you are actually accessing it as the Anonymous user.
When you are running a process on your desktop (like CScript.exe) then you are running under an Interactive User token. This token has full credentials for both local and remote access, so you are able to access the network share.
In order to access remote resources while impersonating a Windows user you must use Delegation rather then Impersonation. This will involve some changes to your Active directory to allow delegation for the computer and/or the users in your domain. This can be a security risk so it should be reviewed carefully.