error CS0006: Metadata file 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\...\some.dll' could not be found - .net-2.0

I am experiencing this problem very often at my hosting server.
The error starts happening occasionally for random DLL and until I ftp the web.config file again (even the same file), the error goes and the site starts working fine.
I am posting the exception and stack trace below.
Please help...
Exception: error CS0006: Metadata file 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root...\some.dll' could not be found
Stack Trace: at System.Web.Compilation.BuildManager.PostProcessFoundBuildResult(BuildResult result, Boolean keyFromVPP, VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetBuildResultFromCacheInternal(String cacheKey, Boolean keyFromVPP, VirtualPath virtualPath, Int64 hashCode) at System.Web.Compilation.BuildManager.GetVPathBuildResultFromCacheInternal(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.UI.BaseTemplateParser.GetReferencedType(VirtualPath virtualPath, Boolean allowNoCompile) at System.Web.UI.BaseTemplateParser.GetUserControlType(VirtualPath virtualPath) at System.Web.UI.MainTagNameToTypeMapper.ProcessUserControlRegistration(UserControlRegisterEntry ucRegisterEntry) at System.Web.UI.MainTagNameToTypeMapper.TryUserControlRegisterDirectives(String tagName)

Mostly likely, you're forcing a recompile while the server is under load. This can have unpredictable effects. ASP.NET does dynamic recompilation, but if you're deploying multiple files you can get a geometric expansion of the nummber of dynamic recompiles required to swallow your whole code migration. Redeploying web.config probably kind of resets the compile process.
Recycling your app pool will clear such a problem, but you may lack that access. Deploying off-peak can probably mitigate the problem.

The best answer for this please open you web.config file and add below two setting add in the compilation tag
<compilation targetFramework="4.0" debug="false" batch="false">
Keep coidng, Also i tried following things when i get the same error in my application which i tried to host in the server
Click Start, click Run, type iisreset /stop, and then click OK.
Open the C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary
ASP.NET Files directory.
Delete all files and all folders in the directory that you located
in step
Click Start, click Run, type iisreset /start, and then click OK.
Do a build again and then try to access your site.

Related

Database from AlwaysOn availability group restored as normal database

I have a problem with a normal SQL database restored from a DB set in AlwaysOn high availability group in SQL Server 2017.
I restored a copy of production db to a different server, to be used as QA test database, with a different name also - MyDB_demo
The problem is, the QA app copy (same code as production with new development enhancements) get an error at some point.
Even if my conn str points to MyDB_demo, I get the following error
[SqlException (0x80131904): The target database ('MyDB') is in an availability group and is currently accessible for connections when the application intent is set to read only. For more information about application intent, see SQL Server Books Online.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +2444190
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +5775712
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2127
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +139
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +136
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +88
MyApp.SqlHelper.ExecuteDataset(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) +163
MyApp.PermitFunctions.GetSystemMessages(String sp, Int32 iPermitID, Int32 iAppID, SqlConnection cn) +219
MyApp.Municipality.LoadSystemMessage() +3869
MyApp.Municipality.Page_Load(Object sender, EventArgs e) +101
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
Is there any reference in the newly restored DB (named now MyDB_demo) that stores the original name of production DB and why is it trying to access it?
Any suggestion is appreciated.
EDIT
Actually, the server used to restore MyDB_demo is one of the secondary nodes for AlwasyOn availability group; it also contains a RO copy of production database, MyDB.
So the server has:
RO copy of production DB (MyDB)
normal, stand-alone db restored for QA - MyDB_demo
Hence, I understand the error message - it would makes sense if I tried to access directly the secondary, RO copy of production db from connection string.
But I do not: the connection string (which I double-checked) is trying to connect to QA db, MyDB_demo.
Here is some additional info:
the error is thrown in SQLHelper class, the helper class from MS to work with SQL Server, in the ExecuteDataset function
the error is thrown ONLY on one stored procedure - lot of other stored procedures and also direct SQL statements run just fine
I inspected the stored procedure, thinking it might contains accidentally a hardcoded reference to DB name - it doesn't
and the strange part - I run the stored procedure with the same parameters as called from the app in SSMS - and it run just fine - no error
So it looks somehow the connection string MIGHT be altered (!!!) is some way by the NET application itself, and only for this stored procedure?
Anyone ever encountered something like this?
Thank you
Due to the strange (read: stupid) situation that the culprit SP fails only when called from within app, but runs ok when tried in SSMS, I tried a "stupid" approach: I inspected its code, commented out two fields that were set with sub-selects like select top 1 from ..... where.... (actually I replaced theit values with dummy ones) and I changed an Order By field that was initially specified like "InspectionType" Desc, which I removed quotation marks from.
Doing this, the SP suddenly started to work ok even when called from the app.
Then I reverted all changes to original (added quoted back and put back the sub-selects) and the SP continued to work ok.
So ... problem solved.
Stupid approach for stupid problem (!?!?!)
In any case, if anyone has a better idea or explanation of what might have happened, I'd be glad to hear it
EDIT
I think I understand the fix.
By editing and saving the stored procedure, its query plan was recompiled.
So the original error might have been caused by the old query plan.
But why did it referenced the database name? Is the actual database name referenced in query plans? This looks a little odd to me.
And another question (open):
Does the SQL Server optimizer detect if a DB runs in high-availability mode, and when optimizing the queries, does it decide if a query is read-only mode and automatically redirects it toward a read-only node? Even if the ApplicationIntent readonly parameter is not present in connection string?
Because it was not in this case, even in production - we just implemented AlwaysOn functionality and are in the process of updating app to take advantage of R/O nodes.
Any comments are appreciated

Word document error

I am trying use a Word document from my application on a Windows 2008 server 64bit from my MVC 2 application. I encountered this error message:
System.UnauthorizedAccessException: Retrieving the COM class factory
for component with CLSID {000209FF-0000-0000-C000-000000000046} failed
due to the following error: 80070005 Access is denied. (Exception from
HRESULT: 0x80070005 (E_ACCESSDENIED)).
at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache)
at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean
fillCache)
at System.Activator.CreateInstance(Type type, Boolean
nonPublic).
I have tried all know solutions, but still cannot fix it.
First of all, please note that serverside office interop isn't
officially supported by Microsoft:
http://support.microsoft.com/kb/257757
Nevertheless I got a similar scenario running with power point and had to do the following steps to get rid of the error you describe:
Run Microsoft Management Console (mmc.exe)
Add Snap-In for "Component Services"
Search for Computers\My Computer\DCOM Config\Microsoft Office Power Point Slide\ (you may search for something that sounds correct for your word-scenario)
Open Properties > Tab "Security"
"Launch and Activation Permissions" > Edit ...
Add your application pool user to this list and allow "Local Launch" and "Local Activation"

Format of the initialization string does not conform to specification starting at index 0 on azure

Have been with thi problem for hours, this is my connectionstring:
<connectionStrings>
<add name="OL4RENTDb"
connectionString="Server=v812xrqz2w.database.windows.net;Database=ol4rentDB;User ID=AdminOL4RENT#v812xrqz2w;Password=Grupo501TSI;Trusted_Connection=False;Encrypt=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
an error:
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5314705
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
Do you see any problem there?
I am deploying to azure..
I had the same error and I fix it by going via FTP to my Azure Website and edited the Web.Config. I noticed that a new connection string entry has been added. I removed it to keep those that I had on my PC and everything worked well. So, if you have this error when you deploy to Azure, check your connections strings.
The problem wasnt that web.config's connection string, but the one you specify in publish settings, the one that azure will use to connect to db.
Lets say you can have in the local pc the connection string to you local database, and when you publish you put the azure database connection string, and that override your local connection string at web.config.

MigrateDatabaseToLatestVersion and dbo.__MigrationHistory

I am trying to deploy an MVC4 application that is built using EF5 codefist and migrations.
I want the app to update the database when I in the future deploy new versions of the app with new migrations, so in Global.asax I do this:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<GoDealMvc4Context, Configuration>());
using (var ctx = new GoDealMvc4Context()) {
ctx.Database.Initialize(false);
}
The initial database on the server is deployed by attaching an MDF file copied from my dev machine. This database contains the __MigrationsHistory system table. So this database should not need to execute any migrations, because it is up to date with latest migration.
When I try to start the app on the server, it I get this error:
There is already an object named 'UserProfile' in the database.
[SqlException (0x80131904): There is already an object named 'UserProfile' in the database.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +388
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +688
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout) +2755286
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +527
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +290
System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement) +247
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements) +202
System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration) +472
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) +175
System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) +150
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +66
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +225
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +208
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +235
GoDeal.Mvc4.MvcApplication.Application_Start() +342
So apparently the app thinks it needs to apply a migration even though the __MigrationHistory table is present in the database with this content:
MigrationId Model ProductVersion
201210161046508_initial 0x1F8... 5.0.0.net45
and the app contains a single migration class:
201210161046508_initial.cs:
public partial class initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.UserProfile",
....
So my questions are:
1) why do my application think it needs to apply this migration when the contents of the __MigrationsHistory table is as described.
2) is this the recommended way of making an application that automatically applies new migrations wehn restarted on a new version.
There is also another NASTY gotcha here for anyone looking for answers. Check the content of the
[dbo].[__MigrationHistory] table column ContextKey
This table Tells how the DB was created (migration mode, Create mode etc...) was created. AND with what Migration Configuration Program. I got hurt with a change of MigrationsConfiguration Class name.
Changing the entry in table worked :-) Or renaming your code back.
1)
As your migration is called "initial" rather than "InitialCreate" this implies that you created this manually and when you enabled code first migrations the database didn't exist already. Or at least the context was not pointing to it. http://msdn.microsoft.com/en-us/data/jj591621.aspx
I believe that MigrateDatabaseToLatestVersion will first trying the create the entity tables for entities that existed before migrations was enabled. As the InitialCreate migration does not exist in your database this first step will then clash with the tables that already exist. Sorry this is a bit vague but I don't fully understand it. To fix this I would remove the migrations by deleting them (first saving any custom changes) and then enable them again with the context pointing at the exiting DB. You should now have an "InitialCreate" migration. You should now be able to copy up the db and use MigrateDatabaseToLatestVersion in the production environment.
2)
Personally letting code first update a production DB worries me quite a bit. I have been using update-database -script -sourcemigration xx to generate the scripts to migrate the DB. This way you can see what is going to happen before you break anything. It also allows you to run in a transaction and roll back after a failure.
In my case this issue was caused by missing migration. I did some changes into model, but I forgot to create new migration file.
My solution is to run in Package Manager Console: Add-Migration MyMigrationName
Just in case someone else encounters SqlException with the message There is already an object named '<TABLE_NAME>' in the database. after changing the model while using automatic migrations. It seems the migrations' Configuration requires in some cases explicit naming of the context key:
internal sealed class Configuration : DbMigrationsConfiguration<MyDatabaseContext>
{
public Configuration ()
{
AutomaticMigrationsEnabled = true;
ContextKey = "MyNamespace.MyDatabaseContext"; // this line was missed
}
protected override void Seed(MyDatabaseContext context)
{
}
}
After adding the line above to the constructor of Configuration, the migration ran without any issues. You can check which ContextKey value is already in use in the __MigrationHistory database.

Code-First Entity Framework - error creating SQL CE DB

I have been using Entity Framework CTP with Code-First as in this tutorial by Scott Guthrie and another by Scott Hanselman (can't post the link, but google "Simple Code First with Entity Framework 4 - Magic Unicorn Feature CTP 4"). This is working perfectly for the main MVC application, but I am now trying to add a testing project, that uses a separate SQL CE Database.
I have added the following to the App.Config file:
<connectionStrings>
<add name="MyData"
connectionString="Data Source=D:\myProject\myDb.sdf;"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
However when I try to run the tests it throws the following error when trying to create the database:
Test method
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList
threw exception:
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.TypeInitializationException:
The type initializer for
'System.Data.SqlServerCe.SqlCeProviderServices'
threw an exception. --->
System.Security.VerificationException:
Operation could destabilize the
runtime.
With the following stack trace:
System.Data.SqlServerCe.SqlCeProviderServices..ctor()
System.Data.SqlServerCe.SqlCeProviderServices..cctor()
System.RuntimeFieldHandle.GetValue(RtFieldInfo
field, Object instance, RuntimeType
fieldType, RuntimeType declaringType,
Boolean& domainInitialized)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck,
Boolean doCheckConsistency)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck)
System.Reflection.RtFieldInfo.GetValue(Object
obj)
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance_GetValue()
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance()
System.Data.SqlServerCe.SqlCeProviderFactory.System.IServiceProvider.GetService(Type
serviceType)
System.Data.Common.DbProviderServices.GetProviderServices(DbProviderFactory
factory)
System.Data.Common.DbProviderServices.GetProviderServices(DbConnection
connection)
System.Data.Entity.ModelConfiguration.Internal.Configuration.CodeFirstCachedMetadataWorkspace.GetMetadataWorkspace(DbConnection
storeConnection)
System.Data.Entity.Infrastructure.DbModel.CreateObjectContext[TContext](DbConnection
existingConnection)
System.Data.Entity.Internal.LazyInternalContext.InitializeFromModel(DbModel
model)
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
System.Data.Entity.Internal.InternalContext.Initialize()
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType)
System.Data.Entity.Internal.Linq.EfInternalQuery1.Initialize()
System.Data.Entity.Internal.Linq.EfInternalQuery1.Include(String
path)
System.Data.Entity.Infrastructure.DbQuery`1.Include(String
path)
MyProjet.Areas.Administration.Models.BusinessModel.GetBusinesses()
in
D:\projects2010\MyProjet\MyProjet\Areas\Administration\Models\BusinessModel.cs:
line 47
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList()
in
D:\projects2010\MyProjet\MyProjet.Tests\Administration\ModlelTests\Business.cs:
line 45
I have tried replacing the existing MyData connection string in the MVC application, and it works fine. It only causes this problem when this is added to the Testing project. Additionally the testing project works without problem when pointed at an SQL or SQL Express Database.
Have been struggling with this for a while now, and just can't figure it out. I am sure I have overlooked something simple.
Try using
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
See my blog post for an example http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/
I have been running the tests under the Built in Microsoft testing framework. Changing the test framework to NUnit (as in Jag's tutorial) has fixed the problem.
So looks like there is a conflict between SqlServerCe and the Visual Studio Unit Testing Framework.