Limilabs IMAP exception - imap

I am trying to use Limilabs imap library to connect to email;
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
works fine ; while limilabs imap does not
using (Imap imap = new Imap())
{
imap.Connect("imap.gmail.com", 993);
gives exception :
Limilabs.Client.ServerException was unhandled
HResult=-2146233088
Message=Tried to read a line. No data received. Please make sure that antivirus and firewall software are disabled or configured correctly.
Source=Mail
StackTrace:
at   .()
at   .(MemoryStream )
at   .()
at Limilabs.Client.IMAP.ImapResponse.(Stream )
at Limilabs.Client.IMAP.Imap.(ImapResponse )
at Limilabs.Client.IMAP.Imap.(String , Boolean )
at Limilabs.Client.IMAP.Imap.ReceiveResponse(String tag)
at Limilabs.Client.IMAP.Imap.wqf45mzzsju7786nbrb2h8aclqm8jmnx    ()
at Limilabs.Client.ClientBase.Connect(String host, Int32 port, Boolean useSSL)
at Limilabs.Client.ClientBase.Connect(String host, Int32 port)
at ConsoleIMAP.Program.Main(String[] args) in c:\users\hmohamed\WcfServiceLibrary1\ConsoleIMP\Program.cs:line 136
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233088
Message=Tried to read a line. No data received.
Source=Mail
StackTrace:
at   .()
InnerException:

Limilabs imap.Connect has an overload to specify if SSL is to be used. It does not infer it from the port you specify. You can also use the imap.ConnectSSL method.
For more info, see:
http://www.limilabs.com/blog/use-ssl-with-imap

I know this question is 2 years old, but it may be important for someone else having this problem.
Imap.Connect/Imap.ConnectSSL methods not only connect, they also start TLS/SSL negotiation (if needed), receive initial server response, and get extensions supported by IMAP server.
That's why connecting with TcpClient may look like it's working at first, but in fact, you haven't started TLS/SSL negotiation nor any other communication with the server.
Gmail supports TLS/SSL connections only, so you must use ConnectSSL method, there is also no need to specify port explicitly:
using (Imap imap = new Imap())
{
imap.ConnectSSL("imap.gmail.com");
//...
imap.Close()
}
Remember that you must enable IMAP access for your account in Gmail.

I know this is a very old question, we just had the same error and solved it, hope can help anyone who has the same situation as us.
We use Amazon Simple Email Service (SES) and SES provides different ports: STARTTLS Port(25, 587 or 2587) and TLS Wrapper Port(465 or 2465)
In our code, we call smtp.StartTLS() after smtp.Connect(Server, Port), we should use the port STARTTLS Port(25, 587 or 2587), if we use TLS Wrapper Port(465 or 2465) will raise the error:
Tried to read a line. Only '' received. Please make sure that antivirus and firewall software are disabled or configured correctly.

Related

Integration test is unable to connect to Postgres 9.6 Db in Jenkins

Description:
A .Net Core 3.1 Web API project contains an IHostedService-implementing service which reads cache data from PostgresDB in StartAsync method. This cache-retrieving service has been registered in Startup's ConfigureServices method
Problem:
While running integration tests in Jenkins I've found that exception is being thrown while trying to connect to the Db:
[19:49:34 ERR] An error occurred using the connection to database 'FooDb' on server 'tcp://localhost:5432'.
[19:49:34 INF] A transient exception has been encountered during execution and the operation will be retried after 0ms.
Npgsql.NpgsqlException (0x80004005): Exception while connecting
---> System.Net.Sockets.SocketException (99): Cannot assign requested address
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state, Boolean flowContext)
at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.ConnectAsync(EndPoint remoteEP)
at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
This issue is limited to integration tests run, e.g. the service works fine in other scenarios.
What have I tried so far?
As per MSDN suggestion I've moved the registration of my cache reading service to Program.cs CreateHostBuilder method;
Refactored cache retrieval to IStartupFilter implementation
none of these steps helped.
Also, I've removed the cache reading service's registration to confirm that its invocation is causing the issue. Indeed, everything works fine if I don't add the cache reading service.

System.Net.HttpListenerException: Failed to listen on prefix 'http://localhost:8080

I am running the following code from Scott Allen's ASP.Net Fundamentals course
using System;
using Microsoft.Owin.Hosting;
using Owin;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uri = "http://localhost:8080";
using (WebApp.Start<Startup>(uri))
{
Console.WriteLine("Started!");
Console.ReadKey();
Console.WriteLine("Stopping!");
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseWelcomePage();
//app.Run(
// ctx => ctx.Response.WriteAsync("Hello Owin!"));
}
}
}
However when I run the console app I get a message
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.HttpListenerExceptio
n: Failed to listen on prefix 'http://localhost:8080/' because it conflicts with
an existing registration on the machine.
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener liste
ner, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 logge
rFactory)
at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDic
tionary`2 properties)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
t[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
Attr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuild
er builder)
at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext conte
xt)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions opt
ions)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider service
s, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
at ConsoleApplication1.Program.Main(String[] args) in e:\EShared\Dev2015\WebA
ppScottAllen\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
Press any key to continue . . .
I ran the Resource Monitor from the Task Manager Performance Tab and can see that there are 2 entries on Listening Ports for 8080.
Both have Image=System, PID=4, IPv6 unspecified, Protocol TCP, Firewall Status Not allowed, not restricted
I am new to Listening Ports, how do I get the code working?
When faced with error: "Failed to listen on prefix 'http://someURL:somePortNo/' because it conflicts with an existing registration on the machine." It is not really necessary that there is an application actively listening on that port - thus output of Netstat -abno may not always help. If the already registered application is running it can help you narrow down to which application is causing the issue by looking at the info Netstat provides.
However, you will get this error even after the application in question is stopped since the error indicates a registration. The correct diagnostic command therefore is:
netsh http show urlacl
We need to examine the output and check whether any of the listed reserved URLs is configured to listen on the specific port your application is trying to use. You need to note the value of the "Reserved URL" field for that specific application. You will need it later for deleting the registration which is causing the error.
Uninstalling that specific application - assuming their uninstall procedure does include an un-registration - may resolve the problem. Alternatively you could take a more direct and precise approach of using the command for deleting a URL reservation:
(Note that if the conflict is legitimate, it may be better to reconfigure your application to listen on a different port instead.)
netsh http delete urlacl url=<value of "Reserved URL" in the output of netsh http show urlacl>
When the command works you will see output: URL reservation successfully deleted.
Upon running netsh http show urlacl a second time you will now see that the url registration is indeed gone. And now running your application should not result in the error you were seeing earlier.
I was able to solve the problem by uninstalling several programs.
Unfortunately I did not test after each, so I don't know which one it was.
They included Dropbox, Goto Assist, Goto Meeting and a winforms application
I had the same issue, and it was a silly fix. I had other console apps open that was using the same port number, so after I have closed all the console apps, I was able to run and did not get this error.
I had the same error in Visual Studio which was kind enough to tell me which port was wrong. I then ran this command in an Administrator Command Prompt:
netsh http delete urlacl url=http://+:44308/
Note : It is important to remember to final slash. Otherwise you will get an error.

How can I propagate an identity from an asp.net mvc application in order to access a tfs server?

I am developing an asp.net mvc application to extract some data from a TFS server.
Right now I am having problems with authentication on the TFS server. When I run the app from my local machine everything works fine, since it propagates my windows identity to the server, but when I deploy the app to my IIS8 server, since there's no user logged on, it won't work.
I would like to avoid using windows authentication on the IIS8 server, since I do not want to maintain the user control with windows groups. Instead I would like only to authenticate the user on my AD, store the identity info and propagate it to the TFS server, but I am clueless on how to do that.
Can you guys help me out? Right now my asp.net mvc app has no authentication and I get the following message:
[UnauthorizedAccessException: Access to the registry key 'HKEY_CURRENT_USER\Software\Microsoft\VSCommon\12.0\ClientServices\TokenStorage\VisualStudio' is denied.]
Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) +4325774
Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions) +10872754
Microsoft.Win32.RegistryKey.CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options) +14
Microsoft.VisualStudio.Services.Common.TokenStorage.RegistryTokenStorageHelper.GetRootKey(String subkeyName) +50
Microsoft.VisualStudio.Services.Common.TokenStorage.RegistryTokenStorage.RetrieveToken(VssTokenKey tokenKey) +57
Microsoft.VisualStudio.Services.Common.TokenStorage.VssTokenStorage.Retrieve(VssTokenKey tokenKey) +15
Microsoft.TeamFoundation.Client.TfsClientCredentialStorage.RetrieveToken(Uri serverUrl, VssCredentialsType credentialType) +58
Microsoft.TeamFoundation.Client.CookieCredential.OnCreateTokenProvider(Uri serverUrl, HttpWebResponse response) +127
Microsoft.TeamFoundation.Client.IssuedTokenCredential.CreateTokenProvider(Uri serverUrl, HttpWebResponse response, IssuedToken failedToken) +45
Microsoft.TeamFoundation.Client.TfsClientCredentials.TryGetTokenProvider(Uri serverUrl, IssuedTokenProvider& provider) +95
Microsoft.TeamFoundation.Client.Channels.TfsHttpRequestHelpers.PrepareWebRequest(HttpWebRequest webRequest, Guid sessionId, String operationName, CultureInfo cultureInfo, TfsRequestSettings settings, TfsClientCredentials credentials, IdentityDescriptor impersonate, IssuedToken& currentToken, IssuedTokenProvider& tokenProvider) +136
Microsoft.TeamFoundation.Client.Channels.TfsHttpRequestHelpers.CreateSoapRequest(Uri requestUri, Guid sessionId, String soapAction, String operationName, CultureInfo cultureInfo, TfsRequestSettings settings, TfsClientCredentials credentials, IdentityDescriptor impersonate, IssuedToken& currentToken, IssuedTokenProvider& tokenProvider) +106
Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.CreateWebRequest() +154
Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.SendRequest() +599
Microsoft.TeamFoundation.Client.Channels.TfsHttpRequestChannel.Request(TfsMessage message, TimeSpan timeout) +243
Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, TimeSpan timeout, Object[]& outputs) +91
Microsoft.TeamFoundation.Framework.Client.LocationWebService.Connect(Int32 connectOptions, Int32 lastChangeId, Int32 features) +175
Microsoft.TeamFoundation.Framework.Client.FrameworkServerDataProvider.Connect(ConnectOptions connectOptions) +92
Microsoft.TeamFoundation.Client.TfsConnection.EnsureProviderConnected() +723
Microsoft.TeamFoundation.Client.TfsConnection.EnsureAuthenticated() +25
Your first issue is that your need to make the account that the website is running under an administrator on your web server. Current permissions are not going to cut the mustered.
Additionally you are going to hit a double hop authentication issue with Kerberos ( security is a pain) and you need to configure an SPN for the account to show it to proxy Kerberos authentication tokens to the TFS server. User SetSPN to configure it, and you will likely need the help of a domain admin.

No Fedauth cookie are sent back as SAML token after reaching STS seems to miss XML tags. Happens only on Firefox

I am scratching my head over a peculiar problem that seems to work on IE and Chrome.
We have a custom passive STS which serves a RP. All is well till i authenticate via my custom authentication service and then STS returns token which i can see in my temp folder. The POST operation which then sends the SAML 1.0 token hangs and silently dies instead of getting back the FedAuth cookie which would normally redirect me the RP
Note : RP and IP are hosted on web server that is behind a reverse proxy server (Nginx). Reverse proxy is hosted over SSL and all traffic to and fro proxy server and webserver is non SSL
The following get logged on the webserver
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 12/11/2013 5:16:33 PM
Event time (UTC): 12/11/2013 5:16:33 PM
Event ID: eef80ad2bffe425780dd46e5f28c0306
Event sequence: 2
Event occurrence: 1
Event detail code: 0
Exception information:
Exception type: XmlException
Exception message: **Unexpected end of file. Following elements are not closed: RequestedUnattachedReference, RequestSecurityTokenResponse,** RequestSecurityTokenResponseCollection. Line 1, position 5852.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
at System.Xml.XmlBufferReader.GetByteHard()
at System.Xml.XmlBufferReader.GetByte()
at System.Xml.XmlUTF8TextReader.ReadStartElement()
at System.Xml.XmlUTF8TextReader.Read()
at System.Xml.XmlBaseReader.ReadEndElement()
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.ReadRSTRXml(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.CreateResponse(XmlReader reader, WSTrustSerializationContext context, WSTrustResponseSerializer responseSerializer, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXml(XmlReader reader, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSFederation.WSFederationSerializer.CreateResponse(WSFederationMessage message, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I dont understand why just for FF i get this problem. Is there a limitation on the size of the content that is sent in the header for FF?
Another question is : I have installed two different certificates one at proxy server (SSL)and one at webserver(STS) to signing the token. Can i use the same certificate? Should i?
According to the top voted answer on the question Can HTTP headers be too big for a browser, Firefox does have the lowest individual header-size (or at least did back in FF3.6). The accepted answer may help you though as you've mentioned you're behind a proxy.

Uploading xml with Monotouch fails on the device

I am trying to send an XML via web client on Monotouch. Although everything is working on the iOS simulator I get an exception when the app is running on the device. Here is the code.
try
{
Byte[] sendData = System.Text.Encoding.UTF8.GetBytes(someXML) ;
WebClient client = new WebClient();
Byte[] forResp;
client.Headers.Add("Content-Type","text/xml");
bresp = wc.UploadData(URL, sendData);
string resp = System.Text.Encoding.ASCII.GetString(forResp);
XmlDocument xresp = new XmlDocument();
xresp.LoadXml(resp);
return xresp;
}
catch
{
// error
}
I tried the WebClient because I had the same issue with the HttpWebRequest.
Exception:
The request timed out
System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:830
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:836
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:1433
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:866
at System.Net.WebClient.UploadDataCore (System.Uri address, System.String method, System.Byte[] data, System.Object userToken) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:462
at System.Net.WebClient.UploadData (System.Uri address, System.String method, System.Byte[] data) [0x00035] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:441
The stacktrace tells us that the timeout occurs when WebClient tries to get a response from the server (and not when uploading the data to the server). That means access to the server is not the issue (and why stacktraces are very useful ;-)
The next steps depends if you have control, or not, of the server. If you control the server then check it's logs to find the request and see how it was handled. If possible also ensure you received/decoded the data identically between the simulator and device.
If you do not control the server then it's harder to know what's going on inside it. E.g. maybe it did not like the request (i.e. the server code can decide not to answer based on any condition, including the user-agent).
In such case using a tool, like wireshark, is often your best bet. Compare the session from the iOS simulator and from the device.
Is the request identical ? e.g. the data you uploaded could be different due to something else;
Is the server answering for the device ? with the same status code ? in the same time frame ?
If everything is identical then you might have found a bug. Please report it (along with the above informations and files) to http://bugzilla.xamarin.com
Otherwise you should have more precise clues to debug the issue and/or update the question to be more specific :-)

Resources