Adding module for .exe file in IIS 6.0 - c#

I have problem with configuration for IIS 6.0.
I have a server which is used for download purpose, but for all files I would like to add custom header by a module:
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
String filePath = application.Request.Path;
String fileName = VirtualPathUtility.GetFileName(filePath);
application.Response.AddHeader("Content-Disposition", String.Concat("attachment; filename=\"", fileName, "\""));
}
My problem is that when I try to do that for .exe file it doesn't work.
I tried adding under mapping an extension to .exe -> c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll but that only forces to execute the .exe file on server.
I tried also with different execution permissions but setting anything other than Scripts and Executables resturns: HTTP Error 403.1 - Forbidden: Execute access is denied.
Any idea how to force that module to work with .exe files?

Does it allow you to download .exe file without your module?
On web site properties in IIS manager, Home Directory tab, make sure execute permissions is set to "scripts only".
On web site properties in IIS manager, HTTP Headers tab, be sure to define .exe as a valid MIME type.
Be sure to stop and restart the IIS Service (via Services)
Refer to http://blogs.msdn.com/b/david.wang/archive/2005/07/11/allow-file-downloads-on-iis-6.aspx

Related

Error while updating web.config via ServerManager - Cannot write configuration file - shows wrong path of web.config in error

As part of installer code, we are trying to make changes to IIS (check and create virtual directory, followed by adding a section to its web.config file.
Installer was working fine till recently a strange error started haunting us and blocking the installer from proceeding
Error says /Core/Service/UserService failed. Reason: Filename: \?\ c:\website1\Core\Common\Service\userService\web.config Error: cannot write configuration file
Please note that "Default Web Site/Core/Service/UserService" is a virtual directory under
"Default Web Site/Core" virtual directory in IIS.
"Default Web Site/Core" has physical path of c:\website1\Core\Common whereas "Default Web Site/Core/Service/UserService" is created with physical path of "c:\website1\Core\Service\UserService"
Not sure why error is pointing towards wrong folder path for web.config.
Code we have used is like this
using (ServerManager mgr = new ServerManager())
{
//code to add virtual path to root website (default web site)
mgr.CommitChanges();
}
using (ServerManager mgrpolicy = new ServerManager())
{
Configuration config = mgrpolicy.GetWebConfiguration("Default Web Site","/Core/Service/UserService");
ConfigurationSection hndlesection = config.GetSection("system.webserver/handlers");
hndlesection["accessPolicy"] = "Read,Write"; //this value is dynamic based on installer input but hardcoded here for your reference.
mgrpolicy.CommitChanges(); //issue comes after this line
}
we are running this installer on .net 4.8 windows application where the above code runs as part of a class library pointing to namespace System.Web.Administration.
Installer user is always system administrator and thus has all privileges.

Calling Web Service in a Windows Service

I've used a simple windows service to make a method work in specific time and it works fine. Following that I've already tried:
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(SchedularCallback));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
//Rest of the code here
}
catch(Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
{
serviceController.Stop();
}
}
}
This is done in a simple windows application. So what I am trying to do is to call a web service (A specific method to operate in a specific time) in a windows service. The application I am building is web-based and am little bit confused how would I integrate the windows service into it? Do I need any alternatives or any suggestions would be appreciated.
Note: What I would like to know is it required to create another project for windows service in the web application or any other way to implement?
To call a web service from a Windows Service application, you would first generate a DLL from that web service, then instantiate its namespace. Assuming you have the code for that web service and/or know its namespace, you can perform these commands to do this:
Perform these lines on a command line:
cd C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
wsdl /l:CS /protocol:SOAP %svc%?WSDL
where %svc% is the URL for your web service, i.e. http://localhost:777/MyWebService.asmx
If the code is in VB instead of C#, change /l:CS to /l:VB.
This will output a proxy class file that can be converted to a DLL.
Move the MyWebService.cs file from C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools to the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ directory.
Run these two commands on the command line:
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
csc /t:library %name%.cs /reference:System.Web.Services.dll /optimize
where %name% is the name of the class (without the .cs, since the command will append this). In our case, we'd use MyWebService. (Change .cs to .vb for a VB class.)
Navigate to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 via Windows Explorer. You should see a DLL created in that folder with the name of the class (MyWebService.dll). Copy this file to the bin folder of your Service project. You will need to set the bin folder to be included in your project, and right-click the folder to Add > Existing Item. Select the DLL. Once imported, select the DLL and change its properties to:
Build Action: Content
Copy to Output Directory: Copy if newer (or Copy always, as you prefer)
Right-click References > Add References. Navigate to the DLL in the bin folder for your web service.
Right-click References > Add Service References. Assuming your web service is running, take its full URL (i.e. http://localhost:777/MyWebService.asmx) and put that on the Address line. In the Namespace textbox, give it something more meaningful than ServiceReference1, but it should not be the same as MyWebService (the name/namespace of the ASMX file). Perhaps MWS.
Instantiate your web service in your Windows Service:
MWS.MyWebServiceSoapClient webService = new MWS.MyWebServiceSoapClient();
webService.Open();
string someDataYouWant = webService.SomeMethodToGetData();
webService.Close();
Or you can probably do:
MyWebService webService = new MyWebService();
string someDataYouWant = webService.SomeMethodToGetData();
webService.Dispose();
In answer to your query on my comment;
Another approach is to use an IIS Auto-Start website contaning your Windows Service logic. The IIS Auto-start is supierior to using a Windows Service as it contains all the IIS application hosting logic including auto-restart, and aggressive resource management. A poorly written Windows Service can take down a Server but it takes a lot for an ASP.net IIS hosted application to take down its host (its almost impossible).
Your Auto-Start website need not be visibile to the outside world - it just needs to have an internal timer that keeps it alive when it starts up. Note that the web application might be started and stopped by IIS for various reasons; but the outcome is that it will be running whenever your other web service application is running. The internal timer can wait for a specific time to execute the logic you need to call your second web service.
The key thing to remember is that a Windows Service is designed to be an application that is hosted by Windows and is continually running. An IIS application is designed to be run by Windows but runs only when called. The IIS Auto-Start website concept allows you to provide a "continually running" website but hosted by the robust IIS application hosting components, instead of it running directly as an OS process.
Generally people dont do this because either they dont know about it, or want to avoid needing the IIS infrastructure to run "Windows Service" type applications, but in your case you have already paid the cost of using IIS to host your second web service, so you may as well make full use of IIS (and avoid the second technology stack and deployment headaches of Windows Service deployment).
So I suggest using an IIS Auto Start in preference to a Windows Service in your situation because;
You only need to use on tech stack in your solution, which was what your OP was asking about
IIS carries out active resource management on all its applications, terminating, restarting as neccessary if they become non-functional. Windows Services do not have that capability.
Your IIS based service code is XCOPY deployable with no administrator access credentials on the target machine.
Your IIS service is hot upgradeable without needing OS level administrator rights - IIS handles the stopping and restarting on upgrade without you needing to do anything.

application redirect to IIS root folder during upload excel file in asp.net

I am facing issue in my web application which is made in asp.net. I have host the application on IIS server.and I am going to upload excel file to port data in database from application.when i uploading from locally from server itself its working fine but i when i try to uploading using public ip or outside then my application redirect to IIS root folder can any one tell me whats is the issue.
this could be an permission issue on your web.config, file and folder permission or maybe a missing reference to correct folder.
Web.config
What is the authentication ? Do you allow Anonymous access. I understand that you can upload fine if you open the side from localhost from the server itself. Did you try to open the side with public ip from the server itself ?
Application Pool in IIS
Look for the "Identify" configuration and set this to "ApplicationPoolIdentify"
File Permission
Look for the folder and ensure that the "IIS_IUSERS" got write permissions
Code Try to sepecify the correct path using the server.MapPath()
Dim myPath As String = Server.MapPath("foldername") & "\" & "filename.csv"

How to access a file from IIS web service hosted by ServiceHost

In my IIS application I open a file located in the wwwroot directory that way:
File.ReadAllText("ConfigFile.json");
IISExpress tries to open the file in C:\Program Files (x86)\IIS Express\ConfigFile.json
I thought the wwwroot directory was the working directory but apparently it's not the case.
Log4net log files are written relatively to the working directory, and configuration manager files also. So I don't understand why opening a file with System.IO.File I have C:\Program Files (x86)\IIS Express as the working directory.
What's the best solution for that problem ? I suppose I don't have to touch the Current defined working directory.
Ok, the solution that works in a IIS WCF Service, hosted by a ServiceHost class is:
AppDomain.CurrentDomain.BaseDirectory + "/ConfigFile.json"
It gives the full absolute path that is valid in my IIS Express environment and in the deployed IIS environment.
You will need to inject IHostingEnvironment into your class to have access to the ApplicationBasePath property value
Suppose IHostingEnvironment type is env then you can use
File.ReadAllText(env.WebRootPath + "/ConfigFile.json");
like you have a function named Read then you can use
public void Read(IHostingEnvironment env)
{
File.ReadAllText(env.WebRootPath + "/ConfigFile.json");
}

CreateDirectory in a web service fails on remote server

System.IO.CreateDirectory or System.IO.File.Create won't work from a web service when navigating to the app remotely. It works locally.
Environment:
- .Net 4.5, Asp.Net, C#
- VS 2012
Remote:
- Windows 08 R2
- IIS 7
- App Pool (.Net 4.0, Integrated)
Process:
The web service is in the project and is used in jQuery .ajax call with url: 'Services.asmx/UploadFile'. The WS method creates the folder chain (if not found) and writes the file.
The file upload works perfectly fine locally in VS.
It also works perfectly when published on a remote server and navigating to it locally on the server (thru RDC) either by localhost/{app} or by http://{ip}/{app}. The folder chain is created and file is written.
However, it does not work when navigating to it normally.
I'm pretty sure it's a user permission issue but I've exhausted all options. I've assigned modify rights on the app folder in wwwroot to "NETWORK SERVICE" and even though I'm sure unnecessarily to "IIS_IUSRS", "IUSR", "LOCAL SERVICE", "NETWORK" and none have helped! I just keep getting status 500 when I navigate to it normally. But it has always worked locally as mentioned above once I gave it "NETWORK SERVICE" modify rights.
Publishing a basic test app with a button and CreateDirectory in code-behind on the same server worked after assigning modify rights to "NETWORK SERVICE" on the app folder in wwwroot.
The create directory code in the web service is:
[WebMethod]
public void UploadFile()
{
string _userId = HttpContext.Current.Request.Form["userId"];
HttpPostedFile _file = HttpContext.Current.Request.Files["Filedata"];
string _uploadsFolder = Server.MapPath(String.Format(ConfigurationManager.AppSettings["FileUploadPath"], _userId, "Temp"));
if (!Directory.Exists(_uploadsFolder)) Directory.CreateDirectory(_uploadsFolder);
FileStream _fileStream = File.Create(Path.Combine(_uploadsFolder, _file.FileName));
_file.InputStream.CopyTo(_fileStream);
_fileStream.Close();
}
FileUploadPath in web.config is
When it works, it works with or without the "~/" in the path. And when it doesn't work, it's the same, with or without, it won't work.

Categories

Resources