Web API Exchange.WebServices Library - c#

I am trying to get an MVC4 WebApi to use the Microsoft.Exchange.WebServices library, but for some reason it is not connecting to the remote server, instead it looks like it's connecting to the loopback address.
The weird thing is that the exact same code works if used in a console application.
I encapsulated the problem in this simple block of code:
Folder exchangeFolder = null;
ExchangeService service = new ExchangeService();
service.Timeout = 600000;
service.Url = new Uri("https://HOSTNAME/exchange.asmx");
service.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "DOMAIN");
FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(int.MaxValue));
foreach (Folder folder in findFolderResults)
{
if ("inbox".Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase))
{
exchangeFolder = folder;
break;
}
}
int inboxItemCount = exchangeFolder.TotalCount;
The innermost exception gives me the following details:
{"No connection could be made because the target machine actively refused it 127.0.0.1:6699"}
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
The code fails with the same exception in both, ASP.NET applications and MVC4 WebApi applications, but works on Console applications.
Is it possible for those types of applications to use the Microsoft.Exchange.WebServices library?
If so, what else needs to be configured to get it working?

you need the reference using Microsoft.Exchange.WebServices.Data;
it can be installed by the nuget package Microsoft exchange webserivices
make sure the dll deploys with your code to the host server

Related

unable to know what is blocking to my application to communicate to Web service

Recently we were facing an issue in client place is that we were unable to communicate to web service even we checked that there is no system proxy set in that system, to overcome this we had given a dummy proxy (localhost:port) and its started working well but after some days with dummy proxy it was unable to communicate to service if we remove dummy proxy then it started working well. i am not able to understand what is blocking me to communicate to service. what may be the issue and how can we overcome this problem. This issue is happening only on some system.
Actually it has to go and hit this URL http://********-tech.in:8080/******dp/ClientVersion but suddenly it started hitting this one 125.21.244.38:8080 why i am not able to conclude.
2017-05-05 00:19:44,721 ERROR [Heartbeat Service ] - Exception while sending heartbeat to manager.
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 125.21.244.38:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
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 System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at HeartbeatWSImplService.heartbeat(String probeUid, heartbeatRequest heartbeatRequest)
at ProHance.ProbeHeartBeat.HeartBeat.timer_Elapsed(Object sender, ElapsedEventArgs e)
Please read this post here they are telling to set the default proxy for the webservice request, they are trying to the proxy details while connecting to google. If there is no proxy configured you can try the method mentioned there. Set the default proxy.

C# + VisualStudio + Multiple WebDriver instances = SocketExceptions

The WebDriver-based tests for our web application requires multiple browser windows open at once: one opens the consumer-facing portal, the other opens the administrator portal (to ensure changes in one are seen in the other). This is done by creating two seperate WebDriver objects: eg
IWebDriver driver1 = DriverFactory.NewChromeDriver();
IWebDriver driver2 = DriverFactory.NewChromeDriver();
The test can access both WebDrivers as desired. Our tests are specified in SpecFlow and implemented as MSTest cases. The tests are developed in VisualStudio 2013 Premium, and the drivers simply use the local machine's ChromeDriver instance. All well and good.
When a test performs some actions in Driver2 (say, logging in) and then moves back to Driver1, I end up with a SocketException being thrown because localhost actively refused the connection. Windows Firewall has been told to permit the application on all ports, the factory sets up the proxy correctly. The precise stack trace is:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:50467
Result StackTrace:
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
Firefox opens one browser and then gives up. IE can't even FIND the browser when multiple windows are open.
(I never had this problem until I installed the latest update for VS2013....)
Any ideas? Thanks team.
It transpires that Selenium may indeed throw a WebDriver exception if an element is not present in the DOM. In the end, I had to wrap my accessing code within a try-catch: if the WebDriver exception wraps a WebException that wraps a SocketException, and the SocketException's SocketErrorCode is ConnectionRefused, that means the element is indeed absent from the DOM.

SocketException when calling WCF service from MVC on same server

I have a Windows 2008 Server with IIS 7.5 and one IP. There are two Application under the root, /web and /service. /web is a MVC4 application, and /service is a WCF 4.0 service.
When I consume the service from MVC, I use the following code:
// Create the web request
HttpWebRequest request = WebRequest.Create(TripServiceUrl + id) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
tripJson = reader.ReadToEnd();
}
I get the following SocketException:
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.243.6.43:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +273
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +584
However, I can see 10.243.6.43:80 (an internal address) from a browser on the server and successfully call the service. The IP is not publicly accessible.
What configuration should I have to do to make a self referential call like that work?
It's probably a loopback problem (security issue). See http://support.microsoft.com/kb/896861.
To summarize:
In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
Right-click Lsa, point to New, and then click DWORD Value.
Type DisableLoopbackCheck, and then press ENTER.
Right-click DisableLoopbackCheck, and then click Modify.
In the Value data box, type 1, and then click OK.
Don't follow the step about DisableStrictNameChecking.
You'll also find a lot of reasons not to do this (you are, after all, disabling a security check), followed by a lot of people saying it's the only way to get SharePoint to work properly. In any event, it will help you determine if this is the problem.

Webservice SocketException - Only Breaks On One Application

I have a few applications which use a single Web Service which resides on the same server as the applications.
Why would only one of the applications have a problem connecting to a web service? And is there a way I can better diagnose exactly what the problem is with the connection?
It won't even connect to a web service the application itself is hosting
I have tried running it from my local machine and it works fine (updated the web ref url and the connection string to point to the liver server), which should rule out that the code itself is the problem.
I have tried setting up a different virtual directory to point to the application; and later copying the entrie app to another location on the same server and setting it up there. No luck.
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.xx:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream() +5321194
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
...
Found it... the proxy was the cause of the issue and it is the only application where I specify proxy different from the default:
Since I only need the proxy locally I disabled it on the live web.config with enabled="false"
<defaultProxy enabled="false">
<proxy
autoDetect="False"
bypassonlocal="True"
scriptLocation="http://www.proxy.something"
proxyaddress="http://proxy.com" />
</defaultProxy>

sending mail works on server but not on my local machine

i have the following code below (i have stuck in xxx to not publish the real name). this code works fine when i upload to the server and will send out emails perfectly.
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmailAddress_);
msg.To.Add(new MailAddress(toEmailAddress_));
msg.Subject = subject_;
msg.Body = body_;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("xxx#xxxx.org", "password");
try
{
SmtpClient c = new SmtpClient("mail.xxx.org");
c.UseDefaultCredentials = false;
c.Credentials = basicAuthenticationInfo;
c.Send(msg);
}
catch (Exception ex)
{
throw ex;
Console.Write(ex.Message.ToString());
}
but when i test locally on my machine in visual studio, i get an error:
[SocketException (0x274d): No connection could be made because the target machine actively refused it 66.226.21.251:25]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332
System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159
any suggestions of why this wouldn't work
The first thing I'd do to run this down is to see whether the target machine is, as the error message says, actually refusing the connections. I can connect to port 25 on that IP address from here, so it's possible that your error message is misleading. These are all possible causes of a failure to connect:
there's some problem in your code
there's some problem in the library you're using
you have a local firewall preventing outbound mail from strange programs
your ISP does not permit outbound SMTP connections except to their own servers
some intermediate network is blocking things
the mail server's ISP is blocking SMTP connections from your network
the mail server really is rejecting you, perhaps because you're on a blocklist
To get more detail, download and install Wireshark. It's like a debugger for networks. Start a capture between your system and the target network and then run your code. Interpreting the captured packets takes some experience, so if you get stuck feel free to post more data here.
Relay restrictions are most likely preventing you from sending mail from outside an allowed set of IPs. If the SMTP Server is configured on a web/application server, it's probably set up to allow mail to be sent via the 127.0.0.1 only.
You can configure a local SMTP Server via the IIS Manager. If you go down this path, make sure port 25 is opened up on your local machine. Often times anti-virus type software block/monitor this port and it mucks with email delivery.
I think you are not using the port no in your code. Use these lines, Then mail should be gone on local also.
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Timeout = 60000;
smtp.Port = 25;
This is working on my system. I hope it will work also on your local system.
The provider has probably firewalled off their mail server so that it is only accepting mail from their hosting environment.
Change it to use your local mail server when you're testing it locally.
You asked for an XP Mail Server. Try hMailServer
Have a look to see if your antivirus is going crazy, i've have seen this problem a few times with people running mcafee.
Hope this helps.

Categories

Resources