WCF: ServiceHost problem (cached adresses?) - wcf

i use a WCF-Service.
It workes fine, and if i use a forbidden IP it shows me a message.
But if i change the ip in my textbox to the right IP it will be again catch the TCP exception, with the OLD IP... The IP-string in the textbox is the corret one and all variables contains the right IP...
The exception:
CommunicationException TCP-Fehler
(10049: Die angeforderte Adresse ist
in diesem Kontext ungültig) beim
Lauschen am
IP-Endpunkt=192.168.178.2:7997.
Should be 192.168.178.25
And after correcting the IP in the textbox and restarting the server i get the same exception with the old IP...
Here is my method:
I create all ressources new in this methode.
Only the ServiceHost host; Variable is stored outside the methode and i tried to set it null before starting or after exception.
Configure Host:
private void MenuItemServerStart_Click(object sender, RoutedEventArgs e)
{
**[ omitted ]**
//Define base addresses so all
//endPoints can go under it
Uri tcpAdrs = new Uri("net.tcp://" +
textBoxLocalIP.Text.ToString() + ":" +
textBoxPort.Text.ToString() + "/WPFHost/");
Uri httpAdrs = new Uri("http://" +
textBoxLocalIP.Text.ToString() + ":" +
(int.Parse(textBoxPort.Text.ToString()) + 1).ToString() +
"/WPFHost/");
Uri[] baseAdresses = { tcpAdrs, httpAdrs };
try
{
host = new ServiceHost(typeof(ChatService.ChatService), baseAdresses);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException != null)
{
**[ omitted ]**
}
return;
}
catch (Exception)
{
**[ omitted ]**
}
NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None, true);
//Updated: to enable file transefer of 64 MB
tcpBinding.MaxBufferPoolSize = (int)67108864;
tcpBinding.MaxBufferSize = 67108864;
tcpBinding.MaxReceivedMessageSize = (int)67108864;
tcpBinding.TransferMode = TransferMode.Buffered;
tcpBinding.ReaderQuotas.MaxArrayLength = 67108864;
tcpBinding.ReaderQuotas.MaxBytesPerRead = 67108864;
tcpBinding.ReaderQuotas.MaxStringContentLength = 67108864;
tcpBinding.MaxConnections = 100;
**[ omitted ]**
host.AddServiceEndpoint(typeof(ChatService.IChatService),
tcpBinding, "tcp");
//Define Metadata endPoint, So we can
//publish information about the service
ServiceMetadataBehavior mBehave =
new ServiceMetadataBehavior();
host.Description.Behaviors.Add(mBehave);
host.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(),
"net.tcp://" + textBoxLocalIP.Text.ToString() + ":" +
(int.Parse(textBoxPort.Text.ToString()) - 1).ToString() +
"/WPFHost/mex");
Start host (Exception):
try
{
**host.Open();** **//Exception here !!!**
}
catch (Exception ex)
{
**[ omitted ]**
}
finally
{
if (host.State == CommunicationState.Opened)
{
((StatusBarItem)statusBar1.Items.GetItemAt(0)).Content = "Gestartet";
MenuItemServerStop.IsEnabled = true;
}
}
}

I have a hunch that there may be some static state associated with the channel runtime infrastructure for HTTP bindings, which maintains details of HTTP listeners keyed by service Uri. If you are not properly tearing down ServiceHost instances which threw on Open, perhaps the old details remain registered in this static state.
What happens in your catch block following the call to host.Open()? If you are not calling host.Abort() and host.Dispose() on the instances which threw on Open, this might be the problem.

Related

javax.naming.CommunicationException: Connection reset [Root exception is java.net.SocketException: Connection reset]; remaining name

I am getting socket exception when I try to connect LDAP. Here is my sample code. I am seeing this issue in java 8. I never observed this issue in the earlier java versions.
public static DirContext getDirectoryContext() throws NamingException {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,
Common.getProperty("ldap.context.factory"));
env.put(Context.PROVIDER_URL,
Common.getProperty("ldap.provider.url"));
env.put(Context.SECURITY_AUTHENTICATION,
Common.getProperty("ldap.security.authentication"));
env.put(Context.SECURITY_PRINCIPAL,
Common.getProperty("ldap.security.principal"));
env.put(Context.SECURITY_CREDENTIALS,
Common.getProperty("ldap.security.credential"));
context = new InitialDirContext(env);
log.debug("NamingContext Initialized");
return context;
}
context = getDirectoryContext();
I am using the same context for all LDAP calls.
private NamingEnumeration getResultsFromLdap(String searchFilter) {
NamingEnumeration results = null;
try {
// Getting the list from LDAP matching the given filter
SearchControls sControls = new SearchControls();
sControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String baseContext = Common.getProperty("ldap.base.context");
results = context.search(baseContext, searchFilter, sControls);
} catch (Exception e) {
log.error("EXCEPTION IN getLDAPConnection METHOD, searchFilter : "
+ searchFilter + " : Exception Message : " + e.getMessage());
}
return results;
} // End of getLDAPConnection_SearchResults
Can someone help?

activemq delete consumed messages

I am using ActiveMQ in my app. My question is how to delete messages that ı consumed successfully from kahadb. Because if it is not deleted, my db.data file is growing up constantly.
Here is my consumer;
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:8182");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("TEST.FOO");
MessageConsumer consumer = session.createConsumer(destination);
MessageListener listner = new MessageListener() {
int count = 0;
public void onMessage(Message message) {
if (message instanceof ObjectMessage) {
ObjectMessage objectMessage = (ObjectMessage) message;
ResponseDuration responseDuration = null;
try {
responseDuration = (ResponseDuration) objectMessage.getObject();
System.out.println("Received Time : " + new Date() + "Received: " + responseDuration.toString());
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ResponseDurationOperations.insertResponseDurations(responseDuration);
count++;
System.out.println("Count = " + count);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
consumer.setMessageListener(listner);
Seems that ActiveMQ has a different meaning for what it means with persistance than you (and me as well).
Persistence is defined not to persist for ever but just to make you safe from message loss when you restart the server. See this
One option for you could be to switch off the persistence. See here.
For example by this way:
ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");

The request was aborted: Could not create SSL/TLS secure channel in Windows 8 Metro App

I have a list of 350 downloadable image urls. I download 10 images parallely at one shot by running multiple tasks. But after downloading N number of images suddenly my code throws the following exception.
Exception: "An error occurred while sending the request."
InnerException: "The request was aborted: Could not create SSL/TLS
secure channel."
StackTrace: "at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n ...
I have created a sample project to reproduce this exception. I have 2 test-cases in my hand. You can download the running test project from My Sky Drive Here. Right click on the file HTTPClientTestCases1and2.zip and download.
Case 1: Using a single instance HttpClient for all image Download.
In this case I'm sending parallel request to 10 urls using same HttpClient. In this case download is successful for most of the time. After last successful download of an image wait for minimum 40 seconds (Max 1 minute 40 seconds) to send the next parallel download request for the next batch. One image will definitely fail due to this exception. But so many places its written and suggested to use single HttpClient for multiple request.
public async void DownloadUsingSingleSharedHttpClient(Int32 imageIndex)
{
Uri url = new Uri(ImageURLs[imageIndex]);
UnderDownloadCount++;
try
{
Byte[] contentBytes = null;
try
{
// Exception IS THROWN AT LINE BELOW
HttpResponseMessage response = await _httpClient.GetAsync(url);
contentBytes = await response.Content.ReadAsByteArrayAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Download Failed at GetAsync() :" + ex.Message);
throw ex;
}
DownloadedCount++;
if (OnSuccess != null)
OnSuccess(this, new DownloadSuccessEventArgs() { Index = imageIndex, Data = contentBytes });
}
catch (HttpRequestException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (TaskCanceledException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (Exception e)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(e, null);
}
}
Case 2: Creating new instance of HttpClient for every image Download
In this case it just fails very frequently due to same exception while downloading images parallely.
public async void DownloadUsingCreatingHttpClientEveryTime(Int32 imageIndex)
{
Uri url = new Uri(ImageURLs[imageIndex]);
UnderDownloadCount++;
try
{
Byte[] contentBytes = null;
using (HttpClientHandler _handler = new HttpClientHandler())
{
_handler.AllowAutoRedirect = true;
_handler.MaxAutomaticRedirections = 4;
using (HttpClient httpClient = new HttpClient(_handler))
{
httpClient.DefaultRequestHeaders.ExpectContinue = false;
httpClient.DefaultRequestHeaders.Add("Keep-Alive", "false");
try
{
// Exception IS THROWN AT LINE BELOW
contentBytes = await httpClient.GetByteArrayAsync(url.OriginalString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Download Failed :" + ex.Message);
throw ex;
}
}
_handler.Dispose();
}
DownloadedCount++;
if (OnSuccess != null)
OnSuccess(this, new DownloadSuccessEventArgs() { Index = imageIndex, Data = contentBytes });
}
catch (HttpRequestException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (TaskCanceledException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (Exception e)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(e, null);
}
}
Please edit the following function in MainPage.xaml.cs to check two cases
private void Send10DownloadRequestParallel()
{
for (Int32 index = 0; index < 10; index++)
{
Task.Run(() =>
{
Int32 index1 = rand.Next(0, myImageDownloader.ImageURLs.Count - 1);
UpdateDownloadProgress();
// Case 1: Download Using Single Shared HttpClient
// myImageDownloader.DownloadUsingSingleSharedHttpClient(index1);
// OR
// Case 2: Download Using Creating Http Client Every Time
myImageDownloader.DownloadUsingCreatingHttpClientEveryTime(index1);
});
}
}
My Question: What I'm doing wrong? What is the best way of implementing parallel downloader in WinRT by overcoming this exception.
I ran your sample application and am only get errors in a couple of scenarios:
When the image that your app is requesting does not exist, the .NET HTTP client throws an exception. Your handler doesn't quite handle this case, as the inner exception is NULL. I had to tweak that code just a little:
async void myImageDownloader_OnFailed(object sender, EventArgs e)
{
await App.CurrentDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
{
TimeSpan time =(DateTime.Now -dateTimeSuccess);
String timeGap = "Ideal For:" + time.ToString() + "\n";
ErrorListBox.Text += "\n Failed When: " + DownloadInfo.Text + "\n";
ErrorListBox.Text += timeGap;
// CX - added null check for InnerException, as these are NULL on HTTP result status 404
var ex = sender as Exception;
if (ex.InnerException != null)
ErrorListBox.Text += ex.InnerException.Message;
else
ErrorListBox.Text += "Inner Exception null - Outer = (" + ex.ToString() + ")";
});
}
The only time I got your other error Could not create SSL/TLS secure channel in Windows 8 Metro App, is when I was using a HTTP debugging proxy (Fiddler). If I don't user Fiddler, which intercepts all HTTP(S) calls, then I have no problems downloading. I even started multiple downloads in rapid succession (by clicking the blue download area multiple times within one second). The result was that all items were downloaded (except for the 404 errors, as mentioned above).
Here is a screenshot of the successful downloads (again except for the 404s). This screenshot is running test case #2 (multiple instances of HttpClient). I did run test case #1 (single instance of HttpClient) and the results were also successful.
In short, I did not see the problems that you are experiencing. The only thing I can think of is for you to try your app from a different machine or location.

Launching different service host with the same contract fails

I'm trying to write a generic host process (WinForm) which host different WCF Service implementation of the same contract.
When I run the first one it works OK, but when I launch the other one (in parallel) with a different address is throws that I use the same address twice (addr and port) -> path is different though..
private bool InitializeServiceHost()
{
bool isInitialized = true;
try
{
Log.InfoFormat("Loading service DLL {0} and class {1}", _dllPath, _serviceClassName);
var asm = Assembly.LoadFile(_dllPath);
_service = (IGfnService) asm.CreateInstance(_serviceClassName);
if (_service == null)
throw new ApplicationException(string.Format("Could not instansiate {0} from DLL {1}", _serviceClassName, _dllPath));
_service.Init(_myGuidStr);
Uri uri = new Uri("net.tcp://localhost:9085/GfnService/" + _myGuidStr);
var host = new ServiceHost(_service, uri);
Log.InfoFormat("About to open host, State: {0}, URI: {1} ", host.State, uri);
host.Open();
_serviceUri = uri.ToString();
Log.InfoFormat("Gfn service started successfully, State: {0}, URI: {1} ", host.State, uri);
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
isInitialized = false;
Application.Exit();
}
return isInitialized;
}
Any help will be appreciated....
Got it! it works now! (thanks to all commenters)
var host = new ServiceHost(_service);
Log.Info("Service host generated.");
ServiceEndpoint serviceEndpoint = host.Description.Endpoints.Find(typeof(IGfnService));
if (serviceEndpoint == null)
{
serviceEndpoint = host.AddServiceEndpoint(typeof(IGfnService), new NetTcpBinding
{
MaxConnections = 10,
PortSharingEnabled = true
}, uri);
Log.InfoFormat("Endpoint [{0}] added", serviceEndpoint);
}
The trick was to add the PortSharingEnabled! so the two instances can share the same port! (I should have though about it before, but at least I got a chance to share!)
Thanks!

Monotouch WCF call crashes with SIGILL error on 10th attempt

Using latest monotouch(4.0.3) we have WCF services that are called. After performing the call the 10th attempt crashes. I have created a test program that calls simple WCF call to see if service is up. Responds with an OK message. On 10th call it fails. Tried Server config settings, Close, Dispose on client still same results. Sample Test code segment below:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
mailButton.TouchUpInside += (o, e) =>
{
BasicHttpBinding BindType = new BasicHttpBinding();
BindType.ReceiveTimeout = new TimeSpan(0,0,15);
EndpointAddress ep = new EndpointAddress(#"http://myservice.mydomain.com/MyBusServiceBusService/MFService.svc/BaseService");
BaseServiceClient MFService = new BaseServiceClient(BindType, ep);
MFService.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0,0,10);
MFService.BaseServiceTestCompleted += delegate(object sender, BaseServiceTestCompletedEventArgs ex)
{
UIAlertView alert = new UIAlertView();
alert.Title = "Base Service Test";
alert.AddButton("Ok");
++timesThrough;
alert.Message = ex.Result + " Times=" + timesThrough.ToString();;
alert.InvokeOnMainThread(delegate{alert.Show(); });
var clientObject = sender as BaseServiceClient;
if (clientObject != null && clientObject.State == System.ServiceModel.CommunicationState.Opened)
{
(clientObject.ChannelFactory).Close();
(clientObject).Close();
((IDisposable)clientObject).Dispose();
clientObject = null;
}
if (MFService != null)
{
(MFService.ChannelFactory).Close();
(MFService).Close();
((IDisposable)MFService).Dispose();
MFService = null;
}
GC.Collect();
};
try
{
MFService.BaseServiceTestAsync();
}
catch (Exception ex)
{
UIAlertView alert = new UIAlertView();
alert.Title = "Base Service Test";
alert.AddButton("Ok");
alert.Message = ex.Message ;
alert.InvokeOnMainThread(delegate{alert.Show();});
MFService = null;
GC.Collect();
}
};
}
This issue was fixed in the latest MonoTouch (4.1 beta). The 4.2 (stable) release should be available soon.