Unable to execute ConnectionString in MS visual Studio 2010 - sql

I've been stuck with this for the past week and would be very glad if you guys could help.
I'm working on vb with MS visual studio 2010. I currently have a database under a asp.net folder named "app_data".
I'm trying to execute a connectionString command via web.config file.
Web Config:
<connectionStrings>
<add name="mysqlcon" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\public.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Main code:
Dim a As String = ConfigurationManager.ConnectionStrings("mysqlcon").ConnectionString
Dim conn As New MySqlConnection(a)
Try
conn.Open()
MsgBox("good")
conn.Close()
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
conn.Dispose()
End Try
I'm getting the following error(line 10 is being highlighted):
Server Error in '/MP' Application.
Keyword not supported.
Parameter name: attachdbfilename
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: Keyword not supported.
Parameter name: attachdbfilename
Source Error:
Line 8: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Line 9: Dim a As String = ConfigurationManager.ConnectionStrings("mysqlcon").ConnectionString
Line 10: Dim conn As New MySqlConnection(a)
Line 11:
Line 12:
Stack Trace:
[ArgumentException: Keyword not supported.
Parameter name: attachdbfilename]
MySql.Data.MySqlClient.MySqlConnectionStringBuilder.ValidateKeyword(String keyword) +108
MySql.Data.MySqlClient.MySqlConnectionStringBuilder.set_Item(String keyword, Object value) +18
System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value) +185
MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString(String value) +289
MySql.Data.MySqlClient.MySqlConnection..ctor(String connectionString) +26
test.Button1_Click(Object sender, EventArgs e) in C:\Users\God\Desktop\VB\MP\test.aspx.vb:10
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Would be glad if you guys can help.

user2072778, try this one, it might work:
<add name="mysqlcon" connectionString="Data Source=|DataDirectory|public.mdf" providerName="System.Data.SqlClient" />
And this is a good page for searching this theme: http://www.connectionstrings.com/sql-server-2008

You are trying to connect using a MySQL connection object:
Dim conn As New MySqlConnection(a)
with a Microsoft SQL Server connection string:
<add name="mysqlcon" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\public.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
They just don't match.
If you want to connect to a MySQL database, change the connection string accordingly.

Related

VB.Net Forms Authentication - Roles.CreateRole()

So I recently started moving my applications over to a more secure authentication system for my un-managed users. I saw Forms authentication for VB.Net and had no issues getting started. I got two new users created and logged in with working password resets.
I just tried to use the Roles.CreateRole function to create a simple role and it through an error associated with app_data permissions.
I have already tried the excessive 50+ articles of people deleting the SQL folder in APP_Data from the windows XP days but it doesn't work for me. I tried looking for the readme file the error references but with over 400+ readmes in the Visual Studio file I'm lost on finding that information. I have also tried changing the IIS application pool identity to a local user and restarted the whole PC.
If anyone knows where the readme this error references is I would be more than happy to read that first.
Here is the sub where I try to run my code that throws the error when I call Roles.CreateRole
Protected Sub gvUsers_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim strUsername = CType(sender, GridView).Rows(e.CommandArgument).Cells(0).Text
Dim intLevel = Convert.ToInt16(CType(sender, GridView).Rows(e.CommandArgument).Cells(1).Text)
Dim objMembers = Membership.FindUsersByName(strUsername)
Dim objUser As MembershipUser = objMembers(strUsername)
If e.CommandName = "Reset Password" Then
lblError.Text = "Reset password for: <b>" & strUsername & "</b> New Password: <b>" & objUser.ResetPassword() & "</b>"
ElseIf e.CommandName = "Delete" Then
lblError.Text = "Deletion request for user: <b>" & strUsername & "</b> resulted in a <b>" & Membership.DeleteUser(strUsername).ToString & "</b> result."
ElseIf e.CommandName = "Increase" Then
Roles.CreateRole("MoldMaintAdmin")
Roles.AddUserToRole(strUsername, "MoldMaintAdmin")
ElseIf e.CommandName = "Decrease" Then
Roles.CreateRole("MoldMaintUser")
Roles.AddUserToRole(strUsername, "MoldMaintUser")
End If
End Sub
Here is the error in detail.
Server Error in '/' Application.
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
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.
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.
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:
[SqlException (0x80131904): Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +907
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5968584
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +507
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +154
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +21
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +90
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +443
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +125
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +29
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
Here is the webconfig
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="AuthServices" connectionString="Data Source=localhost\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=authentication;" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="main.aspx" />
</authentication>
<authorization>
<allow users="?"/>
<!--<deny users="?"/>-->
</authorization>
<membership defaultProvider="AuthServices" userIsOnlineTimeWindow="30">
<providers>
<add
name="AuthServices"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
passwordAttemptWindow="10" />
</providers>
</membership>
<roleManager
enabled="true"
cacheRolesInCookie="true" >
<providers>
<add name ="AuthServices"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"/>
</providers>
</roleManager>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>
In the role manager section under < system.web >< roleManager > add a default provider inside role manager. I have already declared "AuthServices" in the connection strings section at the top of my original posting.
<roleManager defaultProvider="AuthServices" enabled="true" cacheRolesInCookie="true">
<providers>
<add name ="AuthServices"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"/>
</providers>
</roleManager>

SqlDependency.Start() gives error Cannot attach the file 'C:\Program Files (x86)\IIS Express\EduTech.mdf' as database 'EduTech'

I am trying to start sql dependency but it gives me the following error:
Cannot attach the file 'C:\Program Files (x86)\IIS Express\EduTech.mdf' as database 'EduTech'.
Full error details follow:
Cannot attach the file 'C:\Program Files (x86)\IIS Express\EduTech.mdf' as database 'EduTech'.
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.Data.SqlClient.SqlException: Cannot attach the file 'C:\Program Files (x86)\IIS Express\EduTech.mdf' as database 'EduTech'.
Source Error: Line 25: BundleConfig.RegisterBundles(BundleTable.Bundles);
Line 26: SqlDependency.Stop(con);
Line 27: SqlDependency.Start(con);
Line 28: }
Line 29: protected void Session_Start(object sender, EventArgs e)
stack trace[SqlException (0x80131904): Cannot attach the file 'C:\Program Files (x86)\IIS Express\EduTech.mdf' as database 'EduTech'.]
Here's what my connection string looks like:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\EduTech.mdf;Initial Catalog=EduTech;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
I'm using it in my controller as follows:
string conStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
When I remove the line SqlDependency.start() the app runs perfectly fine.
i solved myself by replacing default connection sting to
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=W:\ongoing projects\Edutech\EduTech\App_Data\EduTech.mdf;Initial Catalog=EduTech;Integrated Security=True" providerName="System.Data.SqlClient" />
i don't know why DataDirectory doesn't work but specifying the exact location works

Not able to connect to SQL Server using configuration manager

I am trying to connect to a SQL Server database using the configuration manager.
The config file code:
<connectionStrings>
<add name="DBCS"
connectionString="data source =.\\SQLEXPRESS; database = Sample2; integrated security = SSPI;"
providerName ="System.Data.SqlClient" />
</connectionStrings>
The C# code below:
string SC = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//string SC = ("data source =.\\SQLEXPRESS; database = Sample2; Integrated Security = SSPI;");
SqlConnection con = new SqlConnection(SC);
SqlCommand cmd = new SqlCommand("Select * from tblemployee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
When I try to run the application I get an error at
con.Open();
Error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Please help.
You need only one \ before SQLExpress in your connection string:
<add name="DBCS"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS; database = Sample2;Integrated Security=SSPI"/>
Check the documentation for further details

How can I make NServiceBus Host based windows service wait for SQL Server to start?

I have several NServiceBus Generic Host based windows services installed on the same server as the SQL Server instance that contains my subscription storage database. When the server boots my NServiceBus Host services try to access the subscription storage database before SQL Server is up.
Here's what I've tried so far:
Added a windows server dependency on MSSQLSERVER. This did not solve the problem.
Added a 1 minute sleep in IWantCustomInitialization.Init to verify the cause of the problem described above. This solved the problem but it's a very crude solution.
What is the recommended way to handle this problem?
For reference find my DBSubscriptionStorageConfig and the exception that occurs when my windows services try to start below.
<DBSubscriptionStorageConfig>
<NHibernateProperties>
<add Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider"/>
<add Key="connection.driver_class" Value="NHibernate.Driver.SqlClientDriver"/>
<add Key="connection.connection_string" Value="Data Source=.;Initial Catalog=NServiceBus;Integrated Security=SSPI"/>
<add Key="dialect" Value="NHibernate.Dialect.MsSql2008Dialect"/>
</NHibernateProperties>
</DBSubscriptionStorageConfig>
ERROR NHibernate.Tool.hbm2ddl.SchemaUpdate [(null)] <(null)> - could not get database metadata
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "NServiceBus" requested by the login. The login failed.
Login failed for user 'SE1\fooservice'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler,
SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject,
TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,
SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options,
Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,
DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.ManagedProviderConnectionHelper.Prepare()
at NHibernate.Tool.hbm2ddl.SchemaUpdate.Execute(Action`1 scriptAction, Boolean doUpdate)
I ended up creating a class which implements IWantCustomInitialization to prevent my windows services from starting before they can connect to the database. The class should probably have some logging code added but it solves my problem for now.
Here's the code.
public class DbDependencyChecker : IWantCustomInitialization
{
private const int ConnectionRetries = 15;
private const int TimeBetweenRetries = 60000;
private const string DefaultConnectionName = "DbDependency";
private const string CustomConnectionNameKey = "DbDependencyConnectionName";
public void Init()
{
var connectionName = ConfigurationManager.AppSettings[CustomConnectionNameKey];
if (string.IsNullOrWhiteSpace(connectionName))
connectionName = DefaultConnectionName;
var providerName = ConfigurationManager.ConnectionStrings[connectionName].ProviderName;
var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
if (string.IsNullOrWhiteSpace(providerName) || string.IsNullOrWhiteSpace(connectionString))
return;
for (var i = 0; i < ConnectionRetries; i++)
{
if (TryToConnect(providerName, connectionString))
break;
System.Threading.Thread.Sleep(TimeBetweenRetries);
}
}
private static bool TryToConnect(string providerName, string connectionString)
{
try
{
using (var connection = CreateConnection(providerName, connectionString))
{
connection.Open();
}
return true;
}
catch (Exception)
{
return false;
}
}
private static IDbConnection CreateConnection(string providerName, string connectionString)
{
var provider = DbProviderFactories.GetFactory(providerName);
var connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
return connection;
}
}
The config file would look like this:
<connectionStrings>
<add name="SomeDb" providerName="System.Data.SqlClient" connectionString="connection string" />
</connectionStrings>
<appSettings>
<add key="DbDependencyConnectionName" value="SomeDb"/>
</appSettings>
Or like this:
<connectionStrings>
<add name="DbDependency" providerName="System.Data.SqlClient" connectionString="connection string"/>
</connectionStrings>
does using a startup type for the windows service of Automatic (Delayed Start) fix it? wouldn't think it would require a full minute delay and this might be a little more desirable than having that internal to the application (especially if you someday have the database on another machine and don't have sql server running there.

wcf linq to sql error

I am getting an error returning a linq query over http to an ASP.Net application
I have the following wcf service running in IIS
public class ProductService : IProductService
{
NorthwindEntities context = new NorthwindEntities();
public List<Customer> GetCustomers()
{
return context.Customers.Select(c => c).ToList();
}
}
Web Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="WCF_Entity.ProductService">
<endpoint address="" binding="wsHttpBinding" contract="WCF_Entity.IProductService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SHLOMOKATZ-PC;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
I created a ASP.Net application to use the service
myService.ProductServiceClient objService = new ProductServiceClient();
var customers = objService.GetCustomers();
on debuging, I get the following error
An existing connection was forcibly closed by the remote host
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.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
Line 2454:
Line 2455: public ASPWFC.myService.Customer[] GetCustomers() {
Line 2456: return base.Channel.GetCustomers();
Line 2457: }
Line 2458: }
Source File: D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs Line: 2456
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6132200
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +134
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +300
System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +26
System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +265
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +103
[CommunicationException: An error occurred while receiving the HTTP response to http://localhost/WCF_Entity_SVC/ProductService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
ASPWFC.myService.IProductService.GetCustomers() +0
ASPWFC.myService.ProductServiceClient.GetCustomers() in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs:2456
ASPWFC._Default.Page_Load(Object sender, EventArgs e) in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Default.aspx.cs:36
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +37
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +95
System.Web.UI.Control.OnLoad(EventArgs e) +145
System.Web.UI.Control.LoadRecursive() +134
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3412
changing the buffer length, etc... Didn't solve the issue. The database is the sample NorthWind database
I am able to browse to the service
It seems that Aliostad is correct as I recreated the service without using IIs and used ASP to consume the service, and get the below error. So it is a problem invoking the svc from the app, I can still run the service directly via http
The underlying connection was closed: The connection was closed unexpectedly.
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.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
Source Error:
Line 2337:
Line 2338: public NorthwindApp.myService.Customer[] getCustomers() {
Line 2339: return base.Channel.getCustomers();
Line 2340: }
Line 2341: }
Source File: d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs Line: 2339
Stack Trace:
[WebException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +51
[CommunicationException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
NorthwindApp.myService.INorthwindService.getCustomers() +0
NorthwindApp.myService.NorthwindServiceClient.getCustomers() in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs:2339
NorthwindApp._Default.Page_Load(Object sender, EventArgs e) in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Default.aspx.cs:18
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +46
System.Web.UI.Control.OnLoad(EventArgs e) +83
System.Web.UI.Control.LoadRecursive() +120
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3954
I found an article that says that with entity framework 4 there is a problem to serialize entities in wcf with lazy loading enabled
I added the following code to the service and everything works
context.ContextOptions.LazyLoadingEnabled = false;
link to article http://geekswithblogs.net/danemorgridge/archive/2010/05/04/entity-framework-4-wcf-amp-lazy-loading-tip.aspx
How many records are being returned? There are a couple of things in play here:
From a WCF Perspective:
MaxBufferSize: Gets or sets the maximum size of the buffer to use. For buffered messages this value is the same as MaxReceivedMessageSize. For streamed messages, this value is the maximum size of the SOAP headers, which must be read in buffered mode. For a non-streamed message, if the message size is greater than this property, then the message is dropped.
If not specified, this defaults to 65536.
This is only 0.0625 megabytes!
MaxReceivedMessageSize: Gets and sets the maximum allowable message size that can be received.
Default here is also 65536 bytes.
MaxStringContentLength: Gets and sets the maximum string length returned by the reader.
Your service is probably returning a value greater in size than the defaults.
So, you could try modifying your service behavior to include these attributes with higher limits, say 6 MB or so to see if it resolves your issue.
Also - remember there is maxRequestLength limit which is enforced by IIS which trumps any WCF setting, the default is 4096 KB, so you may have to tweak that if you alter the above properties.