How to deploy an ASP.NET website with a Linq to Sql component - asp.net

I have a .NET 3.5 web application that I recently added some Linq to Sql functionality to -- a dbml file, etc. Locally, it works fine.
However, when I try to deploy it, I get a null reference exception, apparently when it's trying to call the constructor for the context object.
To add to the complexity, I use a Web Deployment Project which compiles it into a single DLL. I assumed the Linq to Sql stuff would get compiled along with everything else. However, now I'm thinking that I need to move the dbml file up along with the DLL.
I had the dbml file in the App_Code directory, so I tried recreating that directory structure on the remote server. But .NET will not let me have an App_Code directory on a precompiled application. So I just moved the dbml file into the root directory -- but I still get the error.
Help!
Here's the stack trace for the error I'm getting:
[NullReferenceException: Object reference not set to an instance of an object.]
codeCS.SarcStateDataDataContext..ctor() +28
DB_Interface.SarcStateDataDB..ctor() +26
eSARC_Basic..ctor() +56
ASP.esarc_basic_aspx..ctor() +14
__ASP.FastObjectFactory_sarcwriting.Create_ASP_esarc_basic_aspx() +20
System.Web.Compilation.BuildResultCompiledType.CreateInstance() +32
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +119
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +33
System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +40
System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +160
System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
DB_Interface.SarcStateDataDB is a class I wrote that calls the constructor for the context object:
codeCS.SarcStateDataDataContext context = new SarcStateDataDataContext();
I don't send it a connection string or connection object, because both the local and deployed versions of the program use the same remote database. But could that be the problem? The local application has access to the connection string in the dbml file, but the deployed application doesn't ... ??
UPDATE: I looked at the code in Reflector and it is getting the connection string from the web.config, and everything looks copasetic on that issue ...

OK, I found the problem! The connection string name it was looking for -- SarcWritingConnectionString -- was something that apparently Linq to Sql had added to the web.config when I was setting it up initially, going through the wizard. And I did not move up the new web.config to the server when I deployed the project, because I thought that it had not changed. When I move it up, everything works!
(I used a data connection I had already set up in Server Explorer instead of a connection string that was already in the web.config -- I wasn't even sure how to do that.)
Thanks for your help -- it's good to know I don't need to move up the dbml file. Next time will be easier!

Hi Cynthia
You don't need to deploy .dbml file. The null reference exception is not caused by the lack of .dbml. It's hard to guess the problem with the provided information, but first of all check that the data on the production and development database are the same. Maybe the production database lacks some records and you get nullreference from there. Also make sure that you deploy the project using VS Publishing Wizard (Right click on the project -> Publish). Also, if this doesn't help, could you post a stack trace of the exception?
Thanks

I'd suggest that you pass DB_Interface.SarcStateDataDB the connection string you want to use when you instantiate the class, then use that in its codeCS.SarcStateDataDataContext context = new SarcStateDataDataContext();.
Then you can manage the connection string at the application level, presumably in your web.config file. This way if you ever switch to using a dev db that is separate from prod, then you easily transition to separate connection strings.

Related

Why do i need to have create database permissions for asp.net web app?

I am building an ASP.NET, code-first web app. I am using a company owned database, and have crud permissions for tables within one database on this server. I do not believe I have "Create Database" permissions. I am running into issues publishing my web app. I can run everything locally, but when I publish the code on the company server I get errors like:
Format of the initialization string does not conform to specification starting at index 0.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[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) +1742
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +191
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +136
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +75
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +35
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +241
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +78
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +116
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +434
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +39
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +160
System.Data.Entity.Internal.LazyInternalConnection.get_Connection() +16
[Project].DBContext.Context..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\DBContext\Context.cs:20
[Project].Data_Manager.DataManager..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Data_Manager\DataManager.cs:15
[Project].Controllers.HeaderController..ctor() in C:\Users\[UserName]\Documents\[FilePath]\[Project]\Controllers\HeaderController.cs:12
This error makes me believe I have an issue with my connection string. When using Unit Testing, I get the error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code
Additional information: CREATE DATABASE permission denied in database 'master'.
I recently changed my context constructor from:
public Context() : base("[server_Name].[database_name]")
{}
to:
public Context() : base("[server_Name].[full_company_server_file_path]")
{}
And when I ran the solution locally, also got the "CREATE DATABASE permission denied in database 'master'" error.
For the record, my connection string is:
<connectionStrings>
<clear />
<add name="[server_Name].[database_name]" providerName="System.Data.SqlClient" connectionString="Data Source=[server_Name].[full_company_server_file_path];Initial Catalog=[database_name];Persist Security Info=True;User ID=userid;Password=password;MultipleActiveResultSets=True;Application Name=EntityFramework" />
< /connectionStrings>
My question is:
Why do I need Create Database Permissions in order for this all to work?
And if that isn't the case, why do I keep getting this error? (No where in my code do I say create DB, nor should / can I).
Secondly, any suggestions as to fixing my connection string? I got this connectionString from database -> properties -> Connection String (so I feel like it's correct).
Thanks for all help / tips / explanations.
Using:
ASP.NET / Entity Framework / C#
Visual Studio 2015
SQL Server Management Studio 2014
There is nothing much you can do here except getting the privileges for your application to do such activities on db server which is very unlikely to happen in large organizations.
The best solution to this is not to include database creation operation as part of web application publishing process.
Surely organization's policy will not allow application to run with master db privileges.
Leave database creation activity to the DBAs who are managing the DB Servers and the databases. They will have necessary access and permissions to perform such operations. They will create database and run the script to make your database ready to use by the application.
Create a script which will create the entire database structure including tables, views, stored procs, functions, keys, indexes etc and raise a ticket or RFC or follow whatever process required to get the database created with proper structure on the target server. Let your application deal with the data only without worrying about database creation and updates.
That's how the applications in production environment works and that's how the processes are implemented and followed with very rare exceptions to it.
SOLUTION
For anyone curious, in the process of publishing (native Visual Studio action) the connection string was being garbled to:
connectionString="$(ReplacableToken_[server_name].[database_name]-Web.config Connection String_0)"
I edited the published connection string to my real connection string and that fixed the problem.

CSHTML rendering text only - static page?

This is a continuation of my previous question (.CSHTML pages will not render), but I am no longer getting a 500 error, thus the new post. My pages are now just rendering plain text / html (regardless of what I do).
I can get the pages to work correctly if I try to view them through WebMatrix3, but I cannot view them from the browser (either localhost or through the web).
I recently realized that my pages were set up for ASP.NET v2.0, which I am guessing does not support .cshtml. So, I changed everything to v4.0 but I still don't have any luck view the pages correctly. It's just plain text.
I have:
MVC 3 installed
IIS 7.5 on Win7 Home Premium
The dir of the pages that I want to load converted to application
web.config functioning, though I am not sure what else, if anything I need to have it in
My server functioning normally with HTML, .css, .php, python, etc... But I am having horrible luck with any ASP.NET functionality (this includes .aspx).
I really don't know what other information I need to put here, but if you ask for it, I shall provide it.
EDIT 1:
Now I am just getting 404 errors on any .cshtml page I try to view. This happened before when I didn't have the MIME types in, but was corrected (to at least plain text) when I entered the MIME type in. I have no idea what is going on... at this point I am almost ready to just uninstall everything and try to start over. =\
EDIT 2:
Okay, so I have gotten rid of my 404 and 500 errors. I ended up adding a privileged user to the application pool (advanced settings > process model > Identity). It was set as defaultAppPool before. Now I am getting this:
Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.]
System.Web.UI.Util.CheckAssignableType(Type baseType, Type type) +9633480
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +66
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(String virtualPath, Type requiredBaseType) +28
System.Web.WebPages.BuildManagerWrapper.CreateInstanceOfType(String virtualPath) +203
System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +145
System.Web.WebPages.VirtualPathFactoryManager.CreateInstanceOfType(String virtualPath) +153
System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +73
System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(String virtualPath, IVirtualPathFactory virtualPathFactory) +23
System.Web.WebPages.WebPageRoute.DoPostResolveRequestCache(HttpContextBase context) +349
System.Web.WebPages.WebPageHttpModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +89
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Any more ideas? Oh, and creating a new application didn't help, but it was a good idea.
It could be that an older version of System.Web.WebPages.dll is loaded to memory, and it tries to cast the your cshtml page to a version of WebPages class from that dll.
To test this, try to see what http modules are currently registered:
var allModules = HttpContext.Current.ApplicationInstance.Modules;
for( int i = 0; i < allModules.Count; i++ ) {
Trace(allModules.GetKey(i));
}
In my case that was:
....
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_bca8e05a-5746-45b0-be95-2b920b455ccf
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_c1a67b42-31a9-47f1-8483-9e712fabe2a7
To fix the problem you need to replace the older version of System.Web.WebPages.dll in your /Bin folders, or some other dlls that might be referencing it.
You can try explicitly setting the ContentType in the action:
public ActionResult NotFound() {
Response.ContentType = "text/html";
return View(); }

Unable to find the requested .Net Framework Data Provider. It may not be installed

After completing the ASP.NET MVC 3 tutorial (find here), I tried to publish the app online. I contacted the hosting company to be sure if it's possible to host MVC 3 apps. I had to bin deploy the (dll files) application. So after following some steps on hanselmans blog, I'm getting stuck on following error:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unable to find the
requested .Net Framework Data Provider. It may not be installed.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Unable to find the requested .Net Framework Data
Provider. It may not be installed.]
System.Data.Common.DbProviderFactories.GetFactory(String
providerInvariantName) +1420503
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String
name) +362
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +49
System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
+10 System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
+265 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType) +17
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +62 System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
+15 System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +37 System.Linq.Queryable.OrderByDescending(IQueryable1 source, Expression1 keySelector) +66 MvcMusicStore.Controllers.HomeController.GetTopSellingAlbums(Int32 count) +420 MvcMusicStore.Controllers.HomeController.Index() +47 lambda_method(Closure , ControllerBase , Object[] ) +40 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters) +27
Any help is appreciated.
From my experience, that error means that the value of the providerName attribute on the connection string in your web.config is either incorrect, or the provider literally is not installed. If your providerName is set to System.Data.SqlServerCe.4.0 (SQL Server Compact), which is not uncommon in development, I can guarantee you that it's not installed on your web host; it's only used inside Visual Studio for development. You probably just need to change it to a the real SQL Server provider: System.Data.SqlClient.
Another data point...
I work with Oracle and the Entity Framework. I installed the Oracle ODP.NET, Managed Driver to get by this problem. In the NuGet Package Manager enter
Install-Package Oracle.ManagedDataAccess
It will update the App.config with the appropriate assembly information and the DbProviderFactories. I'm using VS 2015, Entity Framework 6. I also have the Oracle Developer Tools installed.
I resolved the issue.
I find a space in providerName. So, .net framework is not able to estblish connection string with database.
Check your connectionString tag attribute value.
Your providerName may be not well defined. Look for any spaces (as the naming does not allow any) and check extra characters in providerName value.
I faced the similar Issue .. and there is very funny solution for that .. Just look into your ConnectionString -- If it is same that you have used for your other ASP.Net apps, then it should not be... Entity Framework has a different case altogether
<add name="EmployeeContext" connectionString="Server=.\SQLEXPRESS;Database=DB1;User Id=user1;password=password1;" providerName="System.Data.SqlClient**;**" />
Change it to --
<add name="EmployeeContext" connectionString="Server=.\SQLEXPRESS;Database=DB1;User Id=user1;password=password1;" providerName="System.Data.SqlClient"/>
Can you identify the difference .. only one small -- There is no ';' at the end of ProviderName ..
Yes and that makes the difference .. it should be same to same copy of the ProviderName, though I have not checked the case sensitivity. But that solved my Problem
The error was perfect, and the comments above were good but in my case i literally spelled the provider wrong in the web.config file: System.Data.SqlClinet not System.Data.SqlClient

ASP.NET 4.0 application cannot find Default.aspx under IIS6

I've got an ASP.NET 4.0 web application (webforms, not mvc; asp.net routing isn't used) that runs fine under IIS7. When I try to run it under IIS6 and navigate to http://localhost/MyApp/, I get the following exception:
File does not exist.
System.Web.HttpException
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response) (+0 IL, +2509040 JIT)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String overrideVirtualPath) (+54 IL, +198 JIT)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) (+263 IL, +347 JIT)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() (+214 IL, +8967220 JIT)
at System.Web.HttpApplication.ExecuteStep(HttpApplication.IExecutionStep step, Boolean& completedSynchronously) (+54 IL, +184 JIT)
Note that this output comes from my own custom error page. Thus, .NET itself is working fine. I can even remotely debug it and stuff.
Now, if I enter http://localhost/MyApp/Default.aspx, all works fine, I get the default page, etcetera. The first thought would be that the default document isn't specified in IIS, but it is. Even worse - if I disable it altogether, I still get the same error message (and yes, I restarted IIS and cleared my browser cache)!
It seems as if the request for / is always sent directly to ASP.NET which then gets confused because it doesn't have any default document concept. But I don't have any wildcard mappings defined, so how can that be?
After Googling I found this one as a solution. Its unrelated but some commented its working.
Can you please try this.
In the Windows registry, open the following node: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0
1.Create a new DWORD value named EnableExtensionlessUrls.
2.Set EnableExtensionlessUrls to 0. This disables extensionless URL behavior.
3.Save the registry value and close the registry editor.
4.Run the iisreset command-line tool, which causes IIS to read the new registry value

ASP.NET URL validation

We have a custom REST handler on ASP.NET that is configured like this to handle all incoming requests:
<add path="*" verb="*" type="REST.RESTProtocolHandler"/>
However, passing it a pipe character, properly encoded or not at all, triggers a validation error that seems to come from inside ASP.NET.
Accessing http://localhost:8080/%7c or http://localhost:8080/| yields this error:
[ArgumentException: Illegal characters in path.]
System.IO.Path.CheckInvalidPathChars(String path) +7489125
System.IO.Path.Combine(String path1, String path2) +40
System.Web.Configuration.UserMapPath.GetPhysicalPathForPath(String path, VirtualDirectoryMapping mapping) +114
System.Web.Configuration.UserMapPath.GetPathConfigFilename(String siteID, VirtualPath path, String& directory, String& baseName) +72
System.Web.Configuration.UserMapPath.MapPath(String siteID, VirtualPath path) +30
System.Web.Configuration.UserMapPath.MapPath(String siteID, String path) +31
System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull) +297
System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath, Boolean permitNull) +51
System.Web.CachedPathData.GetConfigPathData(String configPath) +341
System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) +110
System.Web.HttpContext.GetFilePathData() +36
System.Web.HttpContext.GetConfigurationPathData() +26
System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context) +43
System.Web.Configuration.CustomErrorsSection.GetSettings(HttpContext context, Boolean canThrow) +41
System.Web.HttpResponse.ReportRuntimeError(Exception e, Boolean canThrow, Boolean localExecute) +101
System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +383
No userland code gets executed. Is this a configuration option somewhere? Reproduced on IIS 7 & VS Studio's 2008 devel server.
Stack Overflow seems to handle this error OK, it looks like a dynamically generated 404 MVC page gets rendered for https://stackoverflow.com/%7c.
Any ideas?
Try to intercept the exception in Global.asax file. Implement there (Global.asax.cs) this method:
protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
//do whatever you want with that exception
//or get the url from the context, reformat and redirect
}
First you need to tinker in the
Registry :
http://support.microsoft.com/default.aspx?scid=kb;EN-US;826437
Restart IIS
and voila it works.
But i've made this work with IIS7 without problems, but with IIS6 I get this error (Illegal characters in path).
I have a similar program that intercepts all and trying it with a pipe gives me the same error. I assume it has to do with IIS doing path tests (mappath) before it knows who is to handle the request.
Your handler takes the root(meaning all calls) but i assume the way IIS does it is generic.
So I assume any or most of pathing characters that you cant use on your filesystem will fail on IIS request (GET/POST).
Maybe someone knows how to disable the IIS check. According to the error, it seems to happens even before your web.config is read, as it is trying to locate the right config?,
Maybe it is possible to use your own error page as an redirect back to your handler?
I think the answer is in your stack trace. The error is thrown on the System.IO.Path.CheckInvalidPathChars() call - this is not checking the Url, but checking the Windows file system upon which IIS sits. It's not so much a case of the pipe character being Url illegal, but basically DOS illegal.
If you intercept the Url before IIS tries to find the matching path on the server, I expect you can deal with this error. That probably lies in having a rewrite rule or similar to find and rewrite the Url with unwanted characters in it.
By default IIS does not allow certain characters in the URL and considers them illegal. This is where you problem comes from - it doesn't even call the handler you have. As far as I know there is no place that you can configure which characters are accepted through UI, except for Windows Registry. I don't know why you want to use pipe, but I don't think it is good practice. As for the error page - you can always have your own error page for any exception, so that users don't see the ugly messages.

Resources