How to automatically turn on IIS - asp.net

please I have an application that needs IIS to run, now IIS needs to be turned on manually in the windows control panel. But I want to avoid this process and automatically turn on IIS how can I do this. Thank you

The IIS is implemented as a Windows Service. So the only thing necessary is you to make sure the Startup type of the W3SVC is set to Automatic. It is set to automatic by default, so your question implies that someone has changed it to one of the other options.
So open the services and look for World Wide Web Publishing Service. Then double-click on it and you'll be present with its properties. From the Startup type drop-down choose Automatic. Restart your computer. The IIS will start automatically.
UPDATE
Based on the OP's comment I assume the re-configuration of the service is necessary.
Unfortunately, there is no managed class to change the service startup type. You can go through P/Invoke and call the native Windows API. Another option is to utilize the WMI. But the quickest way is to spawn a privileged cmd.exe from your application installer and run the following:
sc config w3svc start=auto
However, this is not a bulletproof solution as someone else might later change it again to demand or even disabled.
If you're looking for a mechanism to start the service at the execution of the application installer, you might want the ServiceController class. It can start the service but it cannot change its startup type. Here is the official documentation.
So you could do something like this in your code:
using (var w3cvs = new ServiceController("W3Svc"))
{
if (w3cvs.Status == ServiceControllerStatus.Stopped)
{
w3cvs.Start();
}
}

Related

Web Deployment fails because 'SqlServerSpatial140.dll' file is in use (w3wp.exe) [duplicate]

I am using VS2013 Premium to publish a site to Windows Server 2012.
All files publish ok except these:
SqlServerTypes\x64\msvcr100.dll
SqlServerTypes\x64\SqlServerSpatial110.dll
SqlServerTypes\x86\msvcr100.dll
SqlServerTypes\x86\SqlServerSpatial110.dll
I get this kind of errors for each of the above files I tried to publish:
Web deployment task failed. (The file 'msvcr100.dll' is in use. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_FILE_IN_USE.)
Interrestingly, these files were published the first time (when they were not on the server), then they are no longer overwritten. Tried with 2 different web servers.
I have followed the guide here:
http://blogs.msdn.com/b/webdev/archive/2013/10/30/web-publishing-updates-for-app-offline-and-usechecksum.aspx
...But it only managed to put the site offline (VS is placing the app_offline.htm) but publish still fails with the same error.
All other files publish perfectly.
Any ideas?
You can take you app offline during publishing which hopefully should free up the lock on the file and allow you to update it.
I blogged about this a while back. The support outlined was shipped inside of the Azure SDK and Visual Studio Update. I don't remember the exact releases but I can find out if needed. Any update dating around/after that blog post should be fine.
Prerequisites:
VS 2012 + VS update / VS 2013 + VS Update / VS2015
MSDeploy v3
Note: if you are publishing from a CI server the CI server will need the updates above as well
Edit the publish profile
In VS when create a Web Publish profile the settings from the dialog are stored in Properties\PublishProfiles\ as files that end with .pubxml. Note: there is also a .pubxml.user file, that file should not be modified
To take your app offline in the .pubxml file add the following property.
<EnableMSDeployAppOffline>true</EnableMSDeployAppOffline>
Notes
ASP.NET Required
The way that this has been implemented on the MSDeploy side is that an app_offline.htm file is dropped in the root of the website/app. From there the asp.net runtime will detect that and take your app offline. Because of this if your website/app doesn't have asp.net enabled this function will not work.
Cases where it may not work
The implementation of this makes it such that the app may not strictly be offline before publish starts. First the app_offline.htm file is dropped, then MSDeploy will start publishing the files. It doesn't wait for ASP.NET to detect the file and actually take it offline. Because of this you may run into cases where you still run into the file lock. By default VS enables retrys so usually the app will go offline during one of the retrys and all is good. In some cases it may take longer for ASP.NET to respond. That is a bit more tricky.
In the case that you add <EnableMSDeployAppOffline>true</EnableMSDeployAppOffline> and your app is not getting taken offline soon enough then I suggest that you take the app offline before the publish begins. There are several ways to do this remotely, but that depends on your setup. If you only have MSDeploy access you can try the following sequence:
Use msdeploy.exe to take your site offline by dropping app_offline.htm
Use msdeploy.exe to publish your app (_make sure the sync doesn't delete the app_offline.htm file_)
Wait some amount of time
Publish the site
Use msdeploy.exe to bring the app online by deleting app_offline.htm
I have blogged how you can do this at http://sedodream.com/2012/01/08/howtotakeyourwebappofflineduringpublishing.aspx. The only thing that is missing from that blog post is the delay to wait for the site to actually be taken offline. You can also create a script that just calls msdeploy.exe directly instead of integrating it into the project build/publish process.
I have found the reason why the solution at
http://blogs.msdn.com/b/webdev/archive/2013/10/30/web-publishing-updates-for-app-offline-and-usechecksum.aspx
did not work for the original poster, and I have a workaround.
The issue with the EnableMSDeployAppOffline approach is that it only recycles the app domain hosting the application. It does not recycle the app pool worker process (w3wp.exe) which the app domain lives in.
Tearing down and recreating the app domain will not affect the Sql Server Spatial dlls in question. Those dlls are unmanaged code which are manually loaded via interop LoadLibray calls. Therefore the dlls live outside the purview of the app domain.
In order to release the files locks, which the app pool process puts on them, you need to either recycle the app pool, or unload the dlls from memory manually.
The Microsoft.SqlServer.Types nuget package ships a class which is used to load the Spatial dlls called SqlServerTypes.Utilities. You can modify the LoadNativeAssemblies method to unload the unmanaged dlls when the app domain is unloaded. With this modification when msdeploy copys the app_offline.htm the app domain will unload and then unload the managed dlls as well.
[DllImport("kernel32.dll", SetLastError = true)]
internal extern static bool FreeLibrary(IntPtr hModule);
private static IntPtr _msvcrPtr = IntPtr.Zero;
private static IntPtr _spatialPtr = IntPtr.Zero;
public static void LoadNativeAssemblies(string rootApplicationPath)
{
if (_msvcrPtr != IntPtr.Zero || _spatialPtr != IntPtr.Zero)
throw new Exception("LoadNativeAssemblies already called.");
var nativeBinaryPath = IntPtr.Size > 4
? Path.Combine(rootApplicationPath, #"SqlServerTypes\x64\")
: Path.Combine(rootApplicationPath, #"SqlServerTypes\x86\");
_msvcrPtr = LoadNativeAssembly(nativeBinaryPath, "msvcr100.dll");
_spatialPtr = LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial110.dll");
AppDomain.CurrentDomain.DomainUnload += (sender, e) =>
{
if (_msvcrPtr != IntPtr.Zero)
{
FreeLibrary(_msvcrPtr);
_msvcrPtr = IntPtr.Zero;
}
if (_spatialPtr != IntPtr.Zero)
{
FreeLibrary(_spatialPtr);
_spatialPtr = IntPtr.Zero;
}
};
}
There is one caveat with this approach. It assumes your application is the only one running in the worker process that is using the Spatial dlls. Since app pools can host multiple applications the file locks will not be released if another application has also loaded them. This will prevent your deploy from working with the same file locked error.
There are known issues with IIS and file-locks (why they aren't solved yet i dont know).
The question i want to ask however is if you even need to re-deploy these files?
I recognize the file-names and recall them to be system-files which should either already be present on the server or simply not need to be re-deployed.
I am not very experienced when it comes to IIS but i have ran into this problem before and several of my more experienced co-workers have told me that this is as i said a known IIS-issue and i believe the answer to your question is:
Avoid deploying unnecessary files.
try again
Reset website
try again
iisreset
I think what would be the easiest thing to do is to make these dll's as CopyLocal as true. I am assuming these dll's are pulled out from program files folder. Try marking them as copylocal true and do a deployment.Try to stop any IIS local process running in your local machine.
Watch out you don't have one of those new-fangled cloud backup services running that is taking file locks - and also you don't have things open in explorer or a DLL inspection tool.
I think it's kind of ridiculous that MS doesn't make better provisions for this problem. I find that 9 times out of 10 my deployment works just fine, but then as our traffic increases that can become 1 in 10 times.
I am going to solve the problem with :
two applications MySite.A and MySite.B, where only one is running at a time.
I always then deploy to the dormant site.
If there's a problem during the deployment it will never cause the whole site to go down.
If there's a major problem after deployment you can revert back very easily.
Not quite sure how I'm implementing it, but I think this is what I need to do.

Initializing an asp.net deployment

I have a basic webforms asp.net site. Currently its working on pre-created sql tables and I have to manually triger it to update data. Moving towards a live deployment though, I'd like to make it more comfortable.
How would I make it so that whenever the server software loads it up, the first thing it does before accepting any requests is to run an initialization sub? Just so I can make sure all the tables are there and if not I would create them etc.
Also, I'd like to run another sub that would trigger the data update periodically every few hours. I was thinking that if I could get my initialization sub, I could just spawn a background thread to deal with that but if theres a built-in option, I'll take it.
whenever the server software loads it up
In asp.net, you have the global.asax file - open the code behind for that and look at the possible overrides. Among them will be:
protected void Application_Start()
This always runs when the application starts up and you could use this to check the DB.
If you're in an "in-house" environment where there's a single live database server and a single live application server, then it should be ok to assume that the database is deployed before the application and you won't need this. If you're providing an application to a third-party or providing it on the web, then this is a good place to check. How you generate the DB is up to you, but checking here is a good idea. You could also have a (hidden) admin page on your site that checks the database connection etc.
trigger the data update periodically
This won't be built-in to asp.net as asp.net waits for requests and responds to them. There are ways around this, but generally triggered externally to the application. The easiest is a simple windows scheduled task that hits a page to trigger the check.
This is what's referred to as "deployment".
If your web site is deployed via MSI, this step should be done in MSI.
If your web site is deployed via Visual Studio "publish" option, this is where you need to create tables.
Some applications indeed do as you say, e.g.: create SQL tables on the 1st run. The problem with this approach is that your app will need sa rights, instead or simple read/write. This could lead to security issues.
Code which runs on web site launch (which is where initialization belongs to) is located in global.asax in:
protected void Application_Start()

Shut Down Web Application

I need to shut down my web application during maintenance process, have already gone through many ways like putting app_offline.htm in root directory , disabling the Runtime or disabling it manually via server but i what i need to implement is to do this process completely automated.
What i have is the start and end dates for shut down and flag for those days i.e whether application needed to be shut down on those dates.
Solution that i already have is to create a job in sql server agent which creates and deletes the app_offline.htm file in and from the root directory but what the problem is i need to give static path for the root directory of my application which i don not want to do.
You can use the appcmd command line utility for managing sites on IIS. It's located in %systemroot%\system32\inetsrv\APPCMD. I think it is available in IIS v7 and above only though, not sure if your using an older version of IIS.
To stop and start a site, the command will look like the following:
%systemroot%\system32\inetsrv\APPCMD stop site <Your Site's Name>
%systemroot%\system32\inetsrv\APPCMD start site <Your Site's Name>
More info on the appcmd utility is here: http://www.iis.net/learn/get-started/getting-started-with-iis/getting-started-with-appcmdexe
This is part of the answer which deals with probing the IIS to get the physical path. It might need some tweaking
//eg of site = 'Default Web Site'
//eg of Application = 'MySite'
var appName = "MySite";
//Initializes a new instance of the ServerManager class by using the default path of the ApplicationHost.config file.
ServerManager mgr = new ServerManager();
var applications = mgr.Sites.Cast<Site>().SelectMany(s => s.Applications);
var app = applications.SingleOrDefault(a => a.Path.Equals("/" + appName));
IList<string> physicalPaths = app.VirtualDirectories.Cast<VirtualDirectory>().Select(v => v.PhysicalPath).ToList();
//Calling dispose manually. Per MSDN, cannot wrap the ServerManager instance in 'Using' as it causes memory leaks
mgr.Dispose();
//Releasing the reference to the Server Manager, per MSDN guidance
mgr = null;
return physicalPaths;
One issue that you have here is that web application work on a request basis. You make a request, request is processed and returned. Therefore, to rely on this principle to shutdown your application will not work. What you need is to register a scheduler of some type in Application_Start that would configure itself based on the values in the database. Although I am not sure which scheduling mechanism would be appropriate, you might want to look at Timer (but you must keep a reference to the this object because of garbage collection) or Task scheduler in System.Threading.Tasks namespace.
I might be wrong with a choice of classes but this could be a starting point.
Now, as for you design decision, I would avoid it completely. If your web application can create app_offline.html or rename a file into that one, you have no way of bringing the server back online without manual intervention by removing the file. Instead of that why not create some maintenance Windows Service that can query the database and take offline and bring back online again? If you don't care about bringing the web application online automatically then you should not care about taking it offline automatically.
Another thing to consider is a human mistake in configuring the time when application goes offline. Wrongly configured time can bring down your application much too sooner or much later. Wouldn't it be easier if you created some batch scripts or PowerShell scripts that could take down and bring back up the web application? With the PowerShell script you can query IIS for your application without specifying any physical location.

How to auto start a WCF windows service upon server start using configuration settings

I am looking to find a solution to auto start a WCF Windows service using any settings in the config file. Appreciate your help in advance.
Thanks!
Putting an entry in the Config file will not make any program start automatically. Something else, different than the service itself -or whatever program- would need to check the value in the Config file and determine whether the service should be started or not.
Alternatively, you could configure the service to always start automatically and either continue running if certain value is present in the Config file or shutdown itself otherwise.
Using config file won't solve your problem. Instead, you should install your WCF windows service as a windows service by using InstallUtil command. Then, you can mark your service as auto start one in services.msc

System.Security.SecurityException when writing to Event Log

I’m working on trying to port an ASP.NET app from Server 2003 (and IIS6) to Server 2008 (IIS7).
When I try and visit the page on the browser I get this:
Server Error in ‘/’ Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application’s trust level in the configuration file.
Exception Details: System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and the location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.]
System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly) +562
System.Diagnostics.EventLog.SourceExists(String source, String machineName) +251
[snip]
These are the things I’ve done to try and solve it:
Give “Everyone” full access permission to the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Security. This worked. But naturally I can’t do this in production. So I deleted the “Everyone” permission after running the app for a few minutes and the error re-appeared.
I created the source in the Application log and the Security log (and I verified it exists via regedit) during installation with elevated permissions but the error remained.
I gave the app a full trust level in the web.config file (and using appcmd.exe) but to no avail.
Does anyone have an insight as to what could be done here?
PS: This is a follow up to this question. I followed the given answers but to no avail (see #2 above).
To give Network Service read permission on the EventLog/Security key (as suggested by Firenzi and royrules22) follow instructions from http://geekswithblogs.net/timh/archive/2005/10/05/56029.aspx
Open the Registry Editor:
Select Start then Run. Enter regedt32 or regedit
Navigate/expand to the following key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security
3. Right click on this entry and select Permissions
Add the Network Service user
Give it Read permission
UPDATE: The steps above are ok on developer machines, where you do not use deployment process to install application.
However if you deploy your application to other machine(s), consider to register event log sources during installation as suggested in SailAvid's and Nicole Calinoiu's answers.
I am using PowerShell function (calling in Octopus Deploy.ps1)
function Create-EventSources() {
$eventSources = #("MySource1","MySource2" )
foreach ($source in $eventSources) {
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
}
}
}
See also Microsoft KB 2028427 Fail to write to the Windows event log from an ASP.NET or ASP application
The problem is that the EventLog.SourceExists tries to access the EventLog\Security key, access which is only permitted for an administrator.
A common example for a C# Program logging into EventLog is:
string sSource;
string sLog;
string sEvent;
sSource = "dotNET Sample App";
sLog = "Application";
sEvent = "Sample Event";
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234);
However, the following lines fail if the program hasn't administrator permissions and the key is not found under EventLog\Application as EventLog.SourceExists will then try to access EventLog\Security.
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
Therefore the recommended way is to create an install script, which creates the corresponding key, namely:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\dotNET Sample App
One can then remove those two lines.
You can also create a .reg file to create the registry key. Simply save the following text into a file create.reg:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\dotNET Sample App]
The solution was to give the "Network Service" account read permission on the EventLog/Security key.
For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.
I had a very similar problem with a console program I develop under VS2010 (upgraded from VS2008 under XP)
My prog uses EnLib to do some logging.
The error was fired because EntLib had not the permission to register a new event source.
So I started once my compiled prog as an Administrator : it registered the event source.
Then I went back developping and debugging from inside VS without problem.
(you may also refer to http://www.blackwasp.co.uk/EventLog_3.aspx, it helped me
This exception was occurring for me from a .NET console app running as a scheduled task, and I was trying to do basically the same thing - create a new Event Source and write to the event log.
In the end, setting full permissions for the user under which the task was running on the following keys did the trick for me:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog
I try almost everything in here to solve this problem... I share here the answer that help me:
Another way to resolve the issue :
in IIS console, go to application pool managing your site, and note the identity running it (usually Network Service)
make sure this identity can read KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog (rigth-click, authorisations)
now change the identity of this application pool to Local System, apply, and switch back to Network Service
Credentials will be reloaded and EventLog reacheable
in http://geekswithblogs.net/timh/archive/2005/10/05/56029.aspx , thanks Michael Freidgeim
A new key with source name used need to be created under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application in the regEdit when you use System.Diagnostics.EventLog.WriteEntry("SourceName", "ErrorMessage", EventLogEntryType.Error);
So basically your user does not have permission to create the key. The can do the following depending of the user that you are using from the Identity value in the Application Pool Advanced settings:
Run RegEdit and go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog
Right click in EventLog key and the select Permissions... option
3.Add your user with full Control access.
-If you are using "NetworkService" add NETWORK SERVICE user
-If you are usinf "ApplicationPoolIdentity" add IIS APPPOL{name of your app pool} (use local machine location when search the user).
-If you are using "LocalSystem" make sure that the user has Administrator permissions. It is not recommend for vulnerabilities.
Repeat the steps from 1 to 3 for HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security
For debugging with Visual Studio I use "NetworkService" (it is ASP.NET user) and when the site is published I used "AppicationPoolIdentity".
I ran into the same issue, but I had to go up one level and give full access to everyone to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ key, instead of going down to security, that cleared up the issue for me.
Same issue on Windows 7 64bits.
Run as administrator solved the problem.
There does appear to be a glaringly obvious solution to this that I've yet to see a huge downside, at least where it's not practical to obtain administrative rights in order to create your own event source: Use one that's already there.
The two which I've started to make use of are ".Net Runtime" and "Application Error", both of which seem like they will be present on most machines.
Main disadvantages are inability to group by that event, and that you probably don't have an associated Event ID, which means the log entry may very well be prefixed with something to the effect of "The description for Event ID 0 from source .Net Runtime cannot be found...." if you omit it, but the log goes in, and the output looks broadly sensible.
The resultant code ends up looking like:
EventLog.WriteEntry(
".Net Runtime",
"Some message text here, maybe an exception you want to log",
EventLogEntryType.Error
);
Of course, since there's always a chance you're on a machine that doesn't have those event sources for whatever reason, you probably want to try {} catch{} wrap it in case it fails and makes things worse, but events are now saveable.
FYI...my problem was that accidently selected "Local Service" as the Account on properties of the ProcessInstaller instead of "Local System". Just mentioning for anyone else who followed the MSDN tutorial as the Local Service selection shows first and I wasn't paying close attention....
I'm not working on IIS, but I do have an application that throws the same error on a 2K8 box. It works just fine on a 2K3 box, go figure.
My resolution was to "Run as administrator" to give the application elevated rights and everything works happily. I hope this helps lead you in the right direction.
Windows 2008 is rights/permissions/elevation is really different from Windows 2003, gar.
Hi I ran into the same problem when I was developing an application and wanted to install it on a remote PC, I fixed it by doing the following:
1) Goto your registry, locate: HKLM\System\CurrentControlSet\Services\EventLog\Application(???YOUR_SERVICE_OR_APP_NAME???)
Note that "(???YOUR_SERVICE_OR_APP_NAME???)" is your application service name as you defined it when you created your .NET deployment, for example, if you named your new application "My new App" then the key would be: HKLM\System\CurrentControlSet\Services\EventLog\Application\My New app
Note2: Depending on which eventLog you are writing into, you may find on your DEV box, \Application\ (as noted above), or also (\System) or (\Security) depending on what event your application is writing into, mostly, (\Application) should be fine all the times.
2) Being on the key above, From the menu; Select "FILE" -> "Export", and then save the file. (Note: This would create your necessary registry settings when the application would need to access this key to write into the Event Viewer), the new file will be a .REG file, for the argument sake, call it "My New App.REG"
3) When deploying on PRODuction, consult the Server's System's administrator (SA), hand over the "My New App.REG" file along with the application, and ask the SA to install this REG file, once done (as admin) this would create the key for your applicaion.
4) Run your application, it should not need to access anything else other than this key.
Problem should be resolved by now.
Cause:
When developing an application that writes anything into the EventLog, it would require a KEY for it under the Eventlog registry if this key isn't found, it would try to create it, which then fails for having no permissions to do so. The above process, is similar to deploying an application (manually) whereas we are creating this ourselves, and no need to have a headache since you are not tweaking the registry by adding permissions to EVERYONE which is a securty risk on production servers.
I hope this helps resolving it.
Though the installer answer is a good answer, it is not always practical when dealing with software you did not write. A simple answer is to create the log and the event source using the PowerShell command New-EventLog (http://technet.microsoft.com/en-us/library/hh849768.aspx)
Run PowerShell as an Administrator and run the following command changing out the log name and source that you need.
New-EventLog -LogName Application -Source TFSAggregator
I used it to solve the Event Log Exception when Aggregator runs issue from codeplex.
Had a similar issue with all of our 2008 servers. The security log stopped working altogether because of a GPO that took the group Authenticated Users and read permission away from the key HKLM\System\CurrentControlSet\Services\EventLog\security
Putting this back per Microsoft's recommendation corrected the issue. I suspect giving all authenticated users read at a higher level will also correct your problem.
I hit similar issue - in my case Source contained <, > characters. 64 bit machines are using new even log - xml base I would say and these characters (set from string) create invalid xml which causes exception. Arguably this should be consider Microsoft issue - not handling the Source (name/string) correctly.
My app gets installed on client web servers. Rather than fiddling with Network Service permissions and the registry, I opted to check SourceExists and run CreateEventSource in my installer.
I also added a try/catch around log.source = "xx" in the app to set it to a known source if my event source wasn't created (This would only come up if I hot swapped a .dll instead of re-installing).
Solution is very simple - Run Visual Studio Application in Admin mode !
I had a console application where I also had done a "Publish" to create an Install disk.
I was getting the same error at the OP:
The solution was right click setup.exe and click Run as Administrator
This enabled the install process the necessary privilege's.
I had this issue when running an app within VS. All I had to do was run the program as Administrator once, then I could run from within VS.
To run as Administrator, just navigate to your debug folder in windows explorer. Right-click on the program and choose Run as administrator.
try below in web.config
<system.web>
<trust level="Full"/>
</system.web>
Rebuilding the solution worked for me

Resources