Padarn OpennetCF Socket Connection is Closed - compact-framework

I'm evaluating Padarn for my project and I'm trying to implement a very simple example. I need Padarn for my WIN CE 5.0 or 6.0 web project and I bought a license
This is my configuration part :
static void Main(string[] args)
{
m_padarnServer = new WebServer();
m_padarnServer.Start();
}
And this is my Render Function:
protected override void Render(HtmlTextWriter writer)
{
if (Response.IsClientConnected)
{
Response.Write("OK");
Response.Flush();
writer.Flush();
}
}
And this is my config file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="WebServer" type="OpenNETCF.Web.Configuration.ServerConfigurationHandler, OpenNETCF.Web" />
<section name ="httpRuntime" type ="OpenNETCF.Web.Configuration.HttpRuntimeConfigurationHandler, OpenNETCF.Web"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<WebServer
DefaultPort="80"
MaxConnections="20"
DocumentRoot="\nandFlash\Inetpub\"
Logging="true"
LogFolder="\Temp\Logs"
LogExtensions="aspx;html;htm;zip"
UseSsl="false"
>
<DefaultDocuments>
<Document>default.aspx</Document>
</DefaultDocuments>
<VirtualDirectories />
<Cookies />
<Caching />
</WebServer>
<httpRuntime
maxRequestLength="3000000"
requestLengthDiskThreshold="256"
/>
<requestLimits maxAllowedContentLength="2097151000"/>
</configuration>
And this is socket connection checker :
private static bool IsPortOpen()
{
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect("127.0.0.1", 80);
return true;
}
catch (Exception)
{
return false;
}
}
I'm checking socket connection that padarn is run on ( 127.0.0.1 : 80 ) periodically (every 5 seconds) but sometimes padarn server is down !!! and I can't connect to that ,when I check the socket's port , its disconnected and I have to restart Padarn
please help me , Is this configuration wrong ? What's my problem ?

The problem I believe is that the TcpClients are never explicitly disconnected or closed, so with each call to IsPortOpen another TCP connection will be created and left open.
At some point the web server reaches the maximum number of concurrent requests it is configured to handle (20?), or the client itself runs out of resources and is unable to create more connections.
Things eventually sort themselves out as the web server may decide to close inactive connections, or the garbage collector on the connecting client may start cleaning up TcpClient instances that have gone out of scope, invoking their Close/Dispose methods along the way and closing the underlying connections.
The fact that restarting Padarn solves the issue shows that it is probably the web server that runs out of resources first (or starts rejecting connections when its maximum number has been reached).
Try explicitly closing each connection:
private static bool IsPortOpen()
{
using(TcpClient tcpClient = new TcpClient())
{
try
{
tcpClient.Connect("127.0.0.1", 80);
return true;
}
catch(Exception)
{
return false;
}
}
}

Related

Over 64 Client requests from WCF client rather than default 2?

I have a WCF Web service client program that will send over 200 concurrent requests through either WCF client proxy async calls generated by SvcUtil.exe to the service. I had presumed that CLR will honer the maxconnection=2 in the client config.
<system.net>
<defaultProxy enabled="true">
<proxy bypassonlocal="False" usesystemdefault="True" />
<bypasslist />
<module />
</defaultProxy>
<connectionManagement>
<add address="*" maxconnection="2" />
</connectionManagement>
I know the default value of maxconnection is 2 anyway, and my codes do NOT have System.Net.ServicePointManager.DefaultConnectionLimit defined. However, when I run Fiddler 2 to monitor the outbound requests, my program always sends 64 requests within 0.5 second concurrently, ignoring maxconnection.
Here's the codes:
namespace DemoClient
{
class Program
{
const string realWorldEndpoint = "DefaultBinding_RealWorld";
static void Main(string[] args)
{
var list = new int[100];
for (int i=0;i<100;i++)
{
list[i] = i;
}
var tasks = list.Select(d =>
{
return GetHardData(d);
});
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All done.");
Console.ReadLine();
}
static async Task<string> GetHardData(int d)
{
using( RealWorldProxy client = new RealWorldProxy(realWorldEndpoint))
{
client.ClientCredentials.UserName.UserName = "test";
client.ClientCredentials.UserName.Password = "tttttttt";
return await client.GetHardDataAsync(d);
}
}
}
}
and the implementation of GetHardData in the service side is:
public string GetHardData(int value)
{
System.Threading.Thread.Sleep(40000);
return string.Format("You entered: {0}", value);
}
I understand my codes had spin off over 100 threads because of thread over-subscription intended, but I would expect them to be queued in the http connection pool which should allow only 2 outbound requests/connections by default.
This behavior may cause client timeout if the Web service is not responding fast enough to finish 64 requests each in 60 seconds, since by default the Web service hosted in IIS will limit 2 concurrent calls from the same client, so the other 62 requests have to wait, thus some of them may timeout.
Do I miss something?
Technically I may construct a thread queue or a custom TaskScheduler to limit the number of concurrent calls to 2, however, I would like to rely to the default settings of thread pool and http / tcp pools to queue.
Do I miss something? how to limit concurrent http requests of the WCF client according to maxconnection in config?

NLog to WCF. Closing client throws SocketException on Server

I've been struggling with this problem for a whole day and do not know how to fix it. I have tried various things to resolve the issue but I am at a loss.
I have a project where I am attempting to use the LogReceiverServer from NLog to send and receive messages between 2 PCs. I followed this example here. Everything actually works fine, my WCF service starts up correctly, my client starts up correctly, even the sending of the message to log from client to server works. But, when I shut the client down, I get SocketExceptions thrown by the server for each message that was transmitted. I know this is due to the channel not being closed properly by the client. I cannot find where I must close the channel to prevent the exceptions being thrown by my server. I have read that to manually close the channel I must use
Channel.Close();
would that be correct and where would I put that?
I want to prevent these SocketExceptions. I have found this, but it does not seem to be the correct thing to do. Correct me if I am wrong, but would the solution not use the same principles?
Unless of course I am understanding this completely wrong...
Everything is done using the config files (App.Config and NLog.Config).
Here is my LogReceiverService Target from NLog.config:
<target xsi:type="LogReceiverService"
name="logreceiver"
endpointConfigurationName="LogReceiverClient"
endpointAddress="net.tcp://server:8888/NLogServices/LogReceiverServer/logreceiverserver" />
Here is my endpoint from my app.config:
<endpoint address="net.tcp://server:8888/NLogServices/LogReceiverServer/logreceiverserver"
binding="netTcpBinding"
bindingConfiguration="LogReceiverClient"
contract="NLog.LogReceiverService.ILogReceiverClient"
name="LogReceiverClient" />
Any help or advise would greatly be appreciated.
EDIT: Extended on problem description
OK, So first, here is the Service on my host pretty much as I got it from here:
/// <summary>
/// Log service server object that logs messages.
/// </summary>
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
public class LogReceiverServer : ILogReceiverServer
{
public void ProcessLogMessages(NLogEvents nevents)
{
var events = nevents.ToEventInfo("Client.");
foreach (var ev in events)
{
var logger = LogManager.GetLogger(ev.LoggerName);
logger.Log(ev);
}
}
}
I then created this class, where I inherit from LogReceiverWebServiceTarget and override protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient(); method. It is exactly the same as is found on GitHub here, except that I registered on the ProcessLogMessagesCompleted event where I close the 'client':
[Target("wcftarget")]
public class WcfTarget : LogReceiverWebServiceTarget
{
protected override WcfLogReceiverClient CreateWcfLogReceiverClient()
{
WcfLogReceiverClient client;
if (string.IsNullOrEmpty(EndpointConfigurationName))
{
// endpoint not specified - use BasicHttpBinding
Binding binding;
if (UseBinaryEncoding)
{
binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
}
else
{
binding = new BasicHttpBinding();
}
client = new WcfLogReceiverClient(binding, new EndpointAddress(EndpointAddress));
}
else
{
client = new WcfLogReceiverClient(EndpointConfigurationName, new EndpointAddress(EndpointAddress));
/*commenting this out causes multiple socket exceptions on host*/
client.ProcessLogMessagesCompleted += client_ProcessLogMessagesCompleted;
}
return client;
}
private void client_ProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs e)
{
WcfLogReceiverClient client = sender as WcfLogReceiverClient;
if (client.State == CommunicationState.Opened)
{
(sender as WcfLogReceiverClient).Close();
}
}
}
The Logger in NLog.config is:
<logger name="*" writeTo="logreceiver" minlevel="Info" />
So then if I try to log like this:
class Program
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private static void Main(string[] args)
{
logger.Info("foo");
}
}
my host gives prints this to Debug:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.dll
Will this have any impact on performance of the host over a long period of time?
The problem has been resolved: https://github.com/NLog/NLog/commit/138fd2ec5d94072a50037a42bc2b84b6910df641

Cross domain policy file over net.tcp for WCF servicehost and Silverlight 5

I have a locally hosted WCF service and a silverlight 5 app that communicates with it. By default silverlight tries to obtain the cross domain policy file over HTTP when making calls to the WCF service. I need to change this so that the policy file is served over net.tcp port 943 instead.
I have setup a local tcp listener that serves up the policy file over port 943 and i have followed this technique whereby i make a dummy socket connection in order to obtain the policy file over tcp as it is only retrieved once per application lifetime. The tcp server is being hit as expected and i am getting SocketError property value as Success (though i must note, the first time i hit the tcp server after starting the listener, the result is always access denied).
From what i can tell, the policy file is either invalid as the silverlight application as still unable to connect or the above mentioned technique does not work with silverlight 5.
What i would like to know is if what i am doing is possible & im doing it correctly, otherwise if there is an alternative means to have the policy file successfully downloaded over tcp and removing the need for retrieving it over HTTP.
Thanks
I wrote a long post about hosting silverlight in WPF - and using WCF with a http listener here:
How can I host a Silverlight 4 application in a WPF 4 application?
Now while not directly answering your question, it does show how to create a http version of the policy file.
I have also written something that serves up a policy listener over port 943, but I can't find where I posted the source - so I'll keep digging. As far as I remember though, silverlight does a cascade find of the policy file, if it doesn't get a connection on port 80, it'll then look on port 943.
I hope this is of some help somewhere.
Ok, here is the policy listener I had for net.TCP transport i.e. not HTTP based. I presume you have sorted this by now, sorry for the delay. It may well be of use to someone else now.
I was looking for the MS thing that said they cascade from HTTP to TCP, however, I can't, and therefore have to assume it was bunk and then changed.
Either way, if you call using a net.TCP service, and want a listener for it, this code should help:
#region "Policy Listener"
// This is a simple policy listener
// that provides the cross domain policy file for silverlight applications
// this provides them with a network access policy
public class SocketPolicyListener
{
private TcpListener listener = null;
private TcpClient Client = null;
byte[] Data;
private NetworkStream netStream = null;
private string listenaddress = "";
// This could be read from a file on the disk, but for now, this gives the silverlight application
// the ability to access any domain, and all the silverlight ports 4502-4534
string policyfile = "<?xml version='1.0' encoding='utf-8'?><access-policy><cross-domain-access><policy><allow-from><domain uri='*' /></allow-from><grant-to><socket-resource port='4502-4534' protocol='tcp' /></grant-to></policy></cross-domain-access></access-policy>";
// the request that we're expecting from the client
private string _policyRequestString = "<policy-file-request/>";
// Listen for our clients to connect
public void Listen(string ListenIPAddress)
{
listenaddress = ListenIPAddress;
if (listener == null)
{
listener = new TcpListener(IPAddress.Parse(ListenIPAddress), 943);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,lo);
}
listener.Start();
WaitForClientConnect();
}
private void WaitForClientConnect()
{
listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), listener);
}
public void StopPolicyListener()
{
if (Client.Connected)
{
// Should never reach this point, as clients
// are closed if they request the policy
// only clients that open the connection and
// do not submit a policy request will remain unclosed
Client.Close();
}
listener.Stop();
}
public void RestartPolicyListener()
{
listener.Start();
}
// When a client connects:
private void OnClientConnected(IAsyncResult ar)
{
if (ar.IsCompleted)
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
// End the operation and display the received data on
// the console.
Client = listener.EndAcceptTcpClient(ar);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Set our receive callback
Data = new byte[1024];
netStream = Client.GetStream();
netStream.BeginRead(Data, 0, 1024, ReceiveMessage, null);
}
WaitForClientConnect();
}
// Read from clients.
public void ReceiveMessage(IAsyncResult ar)
{
int bufferLength;
try
{
bufferLength = Client.GetStream().EndRead(ar);
// Receive the message from client side.
string messageReceived = Encoding.ASCII.GetString(Data, 0, bufferLength);
if (messageReceived == _policyRequestString)
{
// Send our policy file, as it's been requested
SendMessage(policyfile);
// Have to close the connection or the
// silverlight client will wait around.
Client.Close();
}
else
{
// Continue reading from client.
Client.GetStream().BeginRead(Data, 0, Data.Length, ReceiveMessage, null);
}
}
catch (Exception ex)
{
throw new Exception(Client.Client.RemoteEndPoint.ToString() + " is disconnected.");
}
}
// Send the message.
public void SendMessage(string message)
{
try
{
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
//Client.Client.Send(bytesToSend,SocketFlags.None);
Client.GetStream().Write(bytesToSend,0, bytesToSend.Length);
Client.GetStream().Flush();
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion

NServiceBus Sagas using NHibernate - Unable to connect to remote server

I am trying to setup NServiceBus Sagas using NHibernate persistence, but I think I have something configured incorrectly because I'm getting an error connecting to a service at 127.0.0.1:8080. I am able to get my saga to handle the command message, but after a few seconds the error message below appears in the console window and then the same command is fired again causing the handler in the saga to be invoked again. This happens repeatedly as long as I allow the application to run. I can tell NHibernate is connecting to my database because it creates a table for the saga data, however nothing is ever persisted in that table.
I think there is an error persisting the saga data, and my guess is that it may be trying to use the default RavenDb saga persistence but I'm not sure why this would be.
The error message I receive is the following:
WARN
NServiceBus.Unicast.Transport.Transactional.TransactionalTransport
[(null)] <(null)> - Failed raising 'transportmessage received' event
for message with ID=3753b476-7501-4fd8-90d0-b10aee95a578\22314
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: No connection could be made
because the target machine actively refused it 127.0.0.1:8080 at
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress) at
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult,Exception&
exception) --- End of inner exception stack trace --- at
NServiceBus.Unicast.UnicastBus.HandleTransportMessage(IBuilder
childBuilder, TransportMessage msg) at
NServiceBus.Unicast.UnicastBus.TransportMessageReceived(Object sender,
TransportMessageReceivedEventArgs e) at
System.EventHandler`1.Invoke(Object sender, TEventArgs e) at
NServiceBus.Unicast.Transport.Transactional.TransactionalTransport.OnTransportMessageReceived(TransportMessage
msg)
A sample of the saga I am trying to use is (nothing fancy here, same thing happens whether or not I actually do something in the Handle method):
public class ItemSaga : Saga<ItemData>, IAmStartedByMessages<CreateItemCommand>
{
public void Handle(CreateItemCommand message)
{
}
}
public class ItemData : ISagaEntity
{
public Guid Id { get; set; }
public string Originator { get; set; }
public string OriginalMessageId { get; set; }
}
My endpoint configuration looks like this:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
public void Init()
{
var container = new UnityContainer();
container.AddNewExtension<Domain.UnityExtension>();
Configure.With()
.UnityBuilder(container)
.JsonSerializer()
.Log4Net()
.MsmqSubscriptionStorage()
.MsmqTransport()
.PurgeOnStartup(true)
.UnicastBus()
.ImpersonateSender(false)
.DisableTimeoutManager()
.NHibernateSagaPersister()
.CreateBus()
.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install());
}
}
And my app.config looks like this:
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error"/>
<MsmqTransportConfig NumberOfWorkerThreads="1" MaxRetries="5"/>
<NHibernateSagaPersisterConfig UpdateSchema="true">
<NHibernateProperties>
<add Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider"/>
<add Key="connection.driver_class" Value="NHibernate.Driver.Sql2008ClientDriver"/>
<add Key="connection.connection_string" Value="Data Source=(localdb)\v11.0;Integrated Security=True;AttachDbFileName=|DataDirectory|\App_Data\EventStore.mdf"/>
<add Key="dialect" Value="NHibernate.Dialect.MsSql2012Dialect"/>
</NHibernateProperties>
</NHibernateSagaPersisterConfig>
<connectionStrings>
<add name="EventStore" connectionString="Data Source=(localdb)\v11.0;Integrated Security=True;AttachDbFileName=|DataDirectory|\App_Data\EventStore.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" />
<bindingRedirect oldVersion="0.0.0.0-3.3.0.4000" newVersion="3.3.1.4000" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Just a couple of notes:
This is from a sample app that I am using to test this functionality. It uses a local database file attached to localdb, however my full application using SQL Server 2012 is exhibiting the same behavior. I also had to add a dependenteAssembly entry for NHibernate because the NServiceBus.NHibernate NuGet package currently binds to an older assembly version (as of this posting).
As you can see, I am also using Unity as my IOC, but I have replicated this with a project using Ninject as well. I am using EventStore for my domain storage which is working great. I have command handlers that handle the command and publish events through EventStore to be handled by other processes. However, I have tried disabling all of those leaving me with just my Saga as a command handler and I still get the same error.
Does anyone have any ideas of what I may be doing wrong?
I have found a workaround to my problem. It seems to be an issue with using the built-in NServiceBus profiles. I was not specifying a profile in the command line arguments of the host, so by default it was loading the NServiceBus.Production profile. The Production profile, by default, uses RavenDB for all persistence.
Looking at the NServiceBus source on GitHub, the Production Profile Handler contains the following in the ProfileActivated method:
Configure.Instance.RavenPersistence();
if (!Configure.Instance.Configurer.HasComponent<ISagaPersister>())
Configure.Instance.RavenSagaPersister();
if (!Configure.Instance.Configurer.HasComponent<IManageMessageFailures>())
Configure.Instance.MessageForwardingInCaseOfFault();
if (Config is AsA_Publisher && !Configure.Instance.Configurer.HasComponent<ISubscriptionStorage>())
Configure.Instance.RavenSubscriptionStorage();
A couple of things to note here:
The profile will always call RavenPersistence() on the
Configure instance. I have not dug into the inner workings of that
method to see if it will actually bypass configuring Raven if other
persistence is already defined, but it will always run this method.
When I attach to the NServiceBus source and debug through
this code, in the second line HasComponent returns
false causing the RavenSagaPersister configuration to be run. This
happens even if I have NHibernateSagaPerister is defined in the endpoint
configuration.
I'm not sure if this behavior is by design, a bug, or misconfiguration on my part. However my workaround was to create my own profile. I had to move the NHibernate configuration calls from my endpoint config to my new profile, but once I did that I was able to use NHibernate persistence without errors.
My custom profile looks like the following (I borrowed the logging handler from the Production profile's logging handler):
public class MyProfile : IProfile
{
}
internal class MyProfileProfileHandler : IHandleProfile<MyProfile>, IWantTheEndpointConfig
{
void IHandleProfile.ProfileActivated()
{
Configure.Instance.NHibernateUnitOfWork();
Configure.Instance.NHibernateSagaPersister();
Configure.Instance.DBSubcriptionStorage();
Configure.Instance.UseNHibernateTimeoutPersister();
}
public IConfigureThisEndpoint Config { get; set; }
}
public class MyProfileLoggingHandler : IConfigureLoggingForProfile<MyProfile>
{
void IConfigureLogging.Configure(IConfigureThisEndpoint specifier)
{
SetLoggingLibrary.Log4Net<RollingFileAppender>(null,
a =>
{
a.CountDirection = 1;
a.DatePattern = "yyyy-MM-dd";
a.RollingStyle = RollingFileAppender.RollingMode.Composite;
a.MaxFileSize = 1024 * 1024;
a.MaxSizeRollBackups = 10;
a.LockingModel = new FileAppender.MinimalLock();
a.StaticLogFileName = true;
a.File = "logfile";
a.AppendToFile = true;
});
if (GetStdHandle(STD_OUTPUT_HANDLE) == IntPtr.Zero)
return;
SetLoggingLibrary.Log4Net<ColoredConsoleAppender>(null,
a =>
{
LiteLoggingHandler.PrepareColors(a);
a.Threshold = Level.Info;
}
);
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
const int STD_OUTPUT_HANDLE = -11;
}
A final note, I also had to set all of the properties of my saga data object as virtual, per standard NHibernate practice. This became very apparent once the system was actually using NHibernate.
public class ItemData : ISagaEntity
{
public virtual Guid Id { get; set; }
public virtual string Originator { get; set; }
public virtual string OriginalMessageId { get; set; }
}
This is a long explanation, but hopefully it'll help someone else out down the road. If anyone has suggestions on a better way to accomplish this, or the correct way to use profiles, please let me know!

IIS 7 Application Pool - Can't connect to WCF Service

Greetings,
I have to following problem. I have a WCF Service which runs under IIS7. Application connects to it and WCF Service makes some requests to DB. I have notice in activity monitor in SQL Server 2005 that after there are exactly 102 active connections, the application pool in IIS7 hangs. After this I can't connect to my WCF Service. Then only IIS7 restart helps.
For connection I am using ChannelFactory, it's closed after each request. I've also introduced code like this to be sure that Channel is closed:
catch (FaultException)
{
Factory.Abort();
return null;
}
catch (CommunicationException)
{
Factory.Abort();
return null;
}
catch (TimeoutException)
{
Factory.Abort();
return null;
}
catch (Exception ex)
{
Factory.Abort();
return null;
}
finally
{
Factory.Close();
Factory.Abort();
}
I have also the following behvavior for my service class:
[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple, AutomaticSessionShutdown=true)]
I have also the following in my service web.config file:
<serviceBehaviors>
<behavior name="Server.Service1Behavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<serviceThrottling maxConcurrentCalls="2147483647"
maxConcurrentSessions="2147483647"
maxConcurrentInstances="2147483647" />
I tried everything. Please help me because user's can't work like this. Why it's happen that after 102 connections to DB application pool hangs?
Here is the code that calls on the database
internal SqlConnection CheckIfConnectionOpen()
{
if (_Connection.State != ConnectionState.Open)
{
_Connection.Open();
}
return _Connection;
}
using (SqlCommand cmd = new SqlCommand(query, _Connection))
{
CheckIfConnectionOpen();
//some parameters for sqlcommand here and execute nonQuery or execute reader
}
Can someone please help me with this because I am still looking for a solution
On a long shot the link below explains a situation when the app pool crashes it does not restart. If you can get it to restart that should decrease the severity of the issue.
http://i.nconspicuo.us/2008/06/25/iis7-on-windows-server-2008-503-service-unavailable-error-application-pool-stops-unexpectedly/
You mentioned you have checked the Channel is closed, it might be good to confirm the DB connections are closed too.
Hope this helps!
You could set up a web farm (multiple processes for the same IIS) which would help minimise the issue, and depend on a single process less (if one dies and restarts, the others can be there to hold up the fort until it restarts.
As an aside, your code above is equivalent to:
catch (Exception ex)
{
Factory.Abort();
return null;
}
finally
{
Factory.Close();
Factory.Abort();
}
And it's just as bad. You probably want to log the exception somewhere so that you know what happened.
I'd like to see the code that calls on the database. I'd be concerned you might not be cleaning up properly.