.NET 4.0 Medium Trust Level and MYSQL connection - .net-4.0

I have a problem and I think a proper answer will help a lot of people which is having same problem.Because it is a common and not well answered problem.
The problem is about "Medium trust level" configuration in IIS.A few months ago I coded my website with "Full trust level" configuration on my local machine and when I uploaded it to host that was working fine.
But my hosting company have a new rule about trust level,now they only allows "Medium trust level".
My web page doesn't work now.I tried to adapt my website but I have no idea how to do that.And that's sure a lot of people don't know either..
So I will tell what I have done so far, can you help me?
First I tried to changed my local configuration by going here,
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
and opened my webconfig file,and changed
<trust level="Full" originUrl="" />
to
<trust level="Medium" originUrl="" />
After that just for testing I created a new website with ASP Default template.It was working.Then I add Mysql.dll as references to connect to Mysql database.But it throwed Security Exception with that stack:
[SecurityException: Request for the permission of type
'System.Security.Permissions.SecurityPermission, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
failed.] MySql.Data.MySqlClient.MySqlTrace..cctor() +0
So what now? Can't we connect to mysql database anymore? Or is there a solution?I never changed my webconfig file in website project folder do I need to change something here?
Please help me guys?

Hi everyone I finnally find solution to my problem, so I will try to help that people having same problem.Partial trust and Medium Trust level are same thing note that out.
My first step at the question is absolutely necessary.Don't forget to change your trust level to "Medium". After that you need to get right .Net Connector version from
The Oficial Website
Be careful to choose version that your hosting provider using. For example my Hosting company is using Mysql Connector Net 6.5.4
Secondly you need to configure your projects webconfig file that will use your .dll files and get the necessary permisson under Medium Trust Level.
You need to add under your <configuration> something like this;
<mscorlib>
<security>
<policy>
<PolicyLevel version="1">
<SecurityClasses>
<SecurityClass Name="MySqlClientPermission" Description="MySql.Data.MySqlClient.MySqlClientPermission, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</SecurityClasses>
</PolicyLevel>
</policy>
</security>
</mscorlib>
And if your system doesn't add it automatically under your <system.web> you need to add;
<assemblies>
<add assembly="MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
<add assembly="MySql.Data.Entity, Version=6.5.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
<add assembly="MySql.Web, Version=6.5.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
</assemblies>
Sometimes this steps may not be enough and you need to edit your web_mediumtrust.config under the
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
You need to add this lines under the
<SecurityClasses>
<securityclass Name="MySqlClientPermission" Description="MySql.Data.MySqlClient.MySqlClientPermission, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
and
<NamedPermissionSets>
<iPermission class = "MysqlClientPermission" version = "1">
<add connectionString = "Server =; Database =;" restrictions = "User =; User Id =; Password =; Port =; Pooling =;" KeyRestrictionBehavior = "(Prevent Usage | Allow Only)" />
</iPermission>
Be careful about version you are using dont forget to change lines according to that. If still you can't figure that out there is a pretty useful link for you
Trust Level Under the Partial Trust

Here is how I solved a similar issue with trying to get MySql to work in a medium trust environment.
We tried everything to the ‘book’ and simply could not get it to work!
Turns out the MySql connecter version is the key. Ask you web hosting company what version of the MySqlClient they have installed on their server in GAC.
(GAC simply means the library is installed on the server so that it can be referenced directly and without you having to upload the MySql.Data.dll to your bin folder. The latest installable version is available here: http://dev.mysql.com/downloads/connector/net/).
Once the driver is installed on the server in GAC you just need to reference it in your web.config like this, but replace Version=6.6.5.0 with your web hosting companies version:
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="MySql.Data, Version=6.6.5.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
</assemblies>
</compilation>

Related

Deploy ASP.NET Core Web API on IIS 10 [duplicate]

I developed a web api in asp.net core version 1.0.1 using visual studio 2015, when I published the web api in IIS 10 of the same pc where it was developed, everything works correctly. The problem arises when I copy and paste the publication folder of the web api to a different pc, the browser shows the error 500.19 Internal Server Error, error code 0x8007000d, "The requested page can not be accessed because the related configuration data for the page is invalid ", which leads to some problem in the web.config.
I do not think the version of IIS is the problem because moving from IIS 10 to IIS 8 or from IIS8 to IIS 10 gives the same error, and the same happens between two pcs with IIS 10.
I have already reviewed several related issues, like, The element 'system.webServer' has invalid child element 'aspNetCore', and others related to web.config file where it seems the error is found. The web.config file in the development environment is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
After publish the web api, the web.config file looks like:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\buildingSecureWebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
</system.webServer>
</configuration>
This web.config file has the same content no matter what computer was publish.
Some idea of ​​what the solution to my problem may be, I need to mount the web api in any version of windows and until now it only works correctly on the pc that was developed.
To get a more detailed error message:
Verify that the log directory exists at the path referenced by the web config. If it does not, create it. The path shown in your config would place the "logs" directory in the root folder of the deployed site.
Verify that the application pool has write access to the logs directory and
Verify that `stdoutLogEnabled="true".
If you have verified all 3 of these items, then you should get log entries that will contain a more detailed description of the error
What could cause a "500.19 Internal Server Error, error code 0x8007000d" error?
.NET Core hosting bundle is not installed on the webserver where the site is deployed. To remedy this, obtain this download .NET Core Windows Server Hosting bundle
You may also want to verify that the path to the dotnet executable exists in the deployment machine's environment variables. To check this, first find the path where dotnet.exe is installed. It is generally located in either C:\Program Files\dotnet or C:\Program Files (x86)\dotnet. Once you know the path, ensure that the path exists in your Environment Variables.
Control Panel > System > Advanced System Settings > Environment Variables. highlight "Path", click 'Edit' and verify that the path to the dotnet folder is present. If it isn't, add it. Do the same for both the User variables and System variables. Restart your machine and try again.

ImageResizing Not Working In Hosting

I have an asp.net mvc project. I installed imageresizing nuget packages. It's working in local.
When I published to my hosting then it's not working.
I set IIS situation integrated and classic but still didn't work.
I couldn't solve, can you help please? Thanks.
The following definitions are exist in web.config
<resizer>
<plugins>
<add name="MvcRoutingShim" />
<add name="DiskCache" />
<add name="SimpleFilters" />
<add name="PrettyGifs" />
</plugins>
</resizer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
</modules>
The self-diagnostics page at /resizer.debug explains the configuration issues present on your hosting environment
Image resizer diagnostic sheet 24.11.2014 22:15:04
2 Issues detected:
(Critical): Grant the website SecurityPermission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal
Without this permission, it may be possible for users to bypass UrlAuthorization rules you have defined for your website, and access images that would otherwise be protected. If you do not use UrlAuthorization rules, this should not be a concern. You may also re-implement your security rules by handling the Config.Current.Pipeline.AuthorizeImage event.
DiskCache(ConfigurationError): Not working: Your NTFS Security permissions are preventing the application from writing to the disk cache
Please give user read and write access to directory "D:\inetpub\adafirin.com\www\imagecache" to correct the problem. You can access NTFS security settings by right-clicking the aformentioned folder and choosing Properties, then Security.

elmah on IIS 6 box

I've got a web site with elmah running on it logging to a sql box. In my test env it's a IIS 7 machine and all works well. When i upload to a network solutions web running IIS 6 I get an error
[SecurityException: Request for the permission of type 'System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +58
System.Configuration.BaseConfigurationRecord.CheckPermissionAllowed(String configKey, Boolean requirePermission, Boolean isTrustedWithoutAptca) +99
The website is setup to run .net 3.5. All of our pages work fine, but elmah gives this error. I've done some searching but can't find what i've setup incorrectly. Was hoping someone else has already solved this.
I suspect your hoster is running ASP.NET in Medium Trust. There's a couple of things to try.
Add the requirePermission="false" attribute to each of the Elmah configuration sections declared in your web.config, for example:
<sectionGroup name="elmah">
<section name="security" type="Elmah.SecuritySectionHandler, Elmah"
requirePermission="false"/>
<section name="errorLog" type="Elmah.ErrorLogSectionHandler, Elmah"
requirePermission="false"/>
</sectionGroup>
If this doesn't work you could also try overriding the trust level by adding this to <system.web> in your web.config file:
<trust level="Full"/>
If this doesn't work then you may need to contact your hoster and ask them to relax their trust policy. However if your site is in a shared pool it's unlikely that they'll entertain this.
Update:
About the requirePermission attribute: The default Medium Trust policy doesn't permit partially trusted callers access to configuration file settings, even in your own application.
You can elect to override this for your application's local configuration settings by setting requirePermission="false". This is done in the <section name="..." type="..." /> declarations in your web.config file. So, when you set:
<section name="errorLog" type="Elmah.ErrorLogSectionHandler, Elmah"
requirePermission="false"/
Effectively what your saying is please grant Elmah permission to read this setting:
<errorLog type="Elmah.VistaDBErrorLog, Elmah" connectionStringName="ElmahDB" />

upload ASPNETDB.mdf to shared hosting?

I am developing asp.net mvc2 application and I use asp.net membership provider which uses ASPNETDB.mdf database. I have also my own database and now I wonder how to upload these 2 databases to server? Should I upload them as .mdf file or should I use SQL server? I prefer using SQL server and if someone knows the shortest way to convert and upload these 2 databases it would help me a lot.
Thanks in advance,
Ilija
Funny I just finished doing the same thing. The basic steps are as follows:
From Visual Studio, load your .mdf and choose "publish to provider" to make a .sql file.
Open SQL Management Studio, open a connection to your database and load the sql file. Add a "use yourdbname;" on top to have it output the tables to your database, then run it.
Now you should have the full table structure. What's left is to modify web.config to read the new tables:
First the membership provider:
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a "
connectionStringName="ConnectionStringLoginInfo"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/"
/>
</providers>
</membership>
Now the role provider:
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a "
connectionStringName="ConnectionStringLoginInfo"
applicationName="/"
/>
</providers>
</roleManager>
And lastly the WebPart provider, if you use it:
<webParts>
<personalization defaultProvider="SqlDatabaseProviderDRDBLoginInfo">
<providers>
<clear/>
<add connectionStringName="ConnectionStringLoginInfo"
type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"
name="SqlDatabaseProviderDRDBLoginInfo"/>
</providers>
</personalization>
</webParts>
In this example I called the connection string ConnectionStringLoginInfo, but whatever you name it, make sure you set it in the connection strings part. Not gonna paste that too :)
This all took me way more than I care to say, but when I saw my app working flawlessly with the App_Data folder deleted, that was quite the moment!
Your simplest option for a hosted solution (i.e. your hosting plan is not a Virtual Private Server) is to generate SQL scripts of your database, exporting these to *.sql files and then run them in your hosted SQL connection.
I would normally connect to my web host's SQL instance using SQL Server Management Studio and either open or paste in the scripts generated by my local copy.
Depending on whether or not your web host provides the service, you might also be able to use the "Publish to provider..." option in Visual Studio.
As a supplement to Blindy's answer I wanted to mention that another way to configure the providers is to change the connection string settings of the default ConnectionString used by most of the providers, which is LocalSqlServer. To do this you just override that particular ConnectionString in your web.config like so:
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="change this to be the details of your host database" providerName="System.Data.SqlClient" />
</connectionStrings>
Also, if you don't want to clear the entire connectionStrings section you can just remove the particular connection string like this:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="change this to be the details of your host database" providerName="System.Data.SqlClient" />
</connectionStrings>
This works, because all providers that default to using Sql Server for their Data Store - such as the membership provider - use the "LocalSqlServer" connection string by default. Thus, if you override it, you don't have to change each provider to point to a different Connection String.
Also, for security reasons, you might want to look into encrypting the connectionString section of your web.config file. The following two articles provide more info.
Encrypting and Decrypting Configuration Sections
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA

IIS 7.5 Error on Restful WCF 4.0

I've been trying to do a simple restful wcf service that will return JSON. Its working if i will run it in the development server. However if I deploy it on IIS 7.5, i will have this error when i accessed it using http://localhost:70
HTTP Error 500.19 - Internal Server
Error The requested page cannot be
accessed because the related
configuration data for the page is
invalid.
Config Error The configuration section
'standardEndpoints' cannot be read
because it is missing a section
declaration
Here is my configuration file: This is the default file generated by the VS2010.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="LocationService" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
Im new to WCF specially on .net 4.0 and IIS 7.5.
Can anybody help? Or anybody has experienced the same and has fixed already?
Do you definitely have the IIS application pool for your site configured to run with ASP .NET 4.0?
Right click your Virtual Directory in IIS Manager > Manage Application > Advanced Settings > read the app pool name.
Then go to Application Pools, find that name and make sure the .NET Framework column says v4.0.
I had the same error on a w2008 x64 with the app pool running .net 4.0; after installing SP2 the issue disappeared
This issue can be seen on Windows Server 2008 without service pack 2 installed. To fix the problem install Windows Server 2008 Service Pack 2.
Taken from Ram Poornalingam's WebLog entry from the 26th October 2009:
If you encounter the following error in your web application (things hosted in IIS) “The configuration section cannot be read because it is missing a section declaration"
examples
“The configuration section 'standardEndpoints' cannot be read because it is missing a section declaration”
“The configuration section ‘tracking’ cannot be read because it is missing a section declaration”
then you need to install either SP2 of Vista/Win2k8 or the hotfix mentioned in KB article 958854.
Sorry to ask a question that may seem obvious to some, but it might help others (mainly me) if you could clarify the last step:
Then go to Application Pools...
Where do I find Application Pools ?
If you can't tell I am used to working for big companies where someone else did that for me and now I am playing developer and IT director.
Thanks
Ok, after 10 seconds of research (I opened my eyes) and looked right above Sites in IIS Manager