Pop3 Authentication Using Proxy - c#

i keep getting authentication failed error after i provide proxy information to Pop3Client. Connection is fine but authentication part gives the following error:
ProxySettings ProxySetting = new ProxySettings
{
Name = "asaf",
Host = "192.168.3.55",
Port = 808,
Auth = new Authorization
{
Type = AuthenticationMethodConstants.Ntlm,
User = "User-001",
Password = "Deneme123"
}
};
using (var client = new Pop3Client())
{
client.Timeout = 120000;
if (ProxySetting != null)
{
client.ProxyClient = ProxySetting.CreateHttpProxyClient();
Console.WriteLine("Current proxy: " + client.ProxyClient.ProxyHost + ":" + client.ProxyClient.ProxyPort);
}
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("outlook.office365.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate("mcs234#lenfs.onmicrosoft.com", "phtfg456!");
Interesting thing is that I just tried the same code with ImapClient with port 993 and it worked just fine. It seems problem is only for Pop3 protocol.

Related

EWS exception while trying to read email from exchange

I am facing an issue while reading emails from my exchange email account using EWS Microsoft API.
Please help me with a solution if anybody has.
Used below code
public static void Main(string[] args)
{
string UserName = "**";
string Password = "**";
string EXCHANGEMAILURL = # "<Exchange Webservice URL>";
ExchangeService service = new ExchangeService();
service.Timeout = 500000;
service.Credentials = new NetworkCredential(UserName, Password);
service.Url = new Uri(EXCHANGEMAILURL);
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
FindFoldersResults folderSearchResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(int.MaxValue));
Folder xChangeSourceFolder = folderSearchResults.Folders.ToList().Find(
f => f.DisplayName.Equals("Inbox", StringComparison.CurrentCultureIgnoreCase));
ItemView itemView = new ItemView(50);
FindItemsResults<Item> findIncomingMails = service.FindItems(xChangeSourceFolder.Id, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
new ItemView(50));
Item item = findIncomingMails.First();
EmailMessage messageHTML = (EmailMessage) item;
messageHTML.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments, ItemSchema.Body) {
RequestedBodyType = BodyType.HTML
});
string htmlString = messageHTML.Body.Text.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred: " + ex);
}
}
The exception
Unable to connect to the remote server :
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.
It was working before, but since last 1-2 weeks, it stopped working.

Why frontend and server cannot connect through websocket after deployment

After I deployed my app to amazon the connection between my frontend and server via websocket doesn't work. To be more precise, when I open the frontend form the amazon link and run the server on my computer it works, but when someone else tries to use the app from a different ip, messages don't come to the server.
Below, I put fragments of code that establish the connection.
Here is how I connect to the server in the frontend (Angular):
public openWebSocket(port : number){
this.webSocket = new WebSocket('ws://192.168.0.16:' + port.toString());
this.webSocket.onopen = (event) => {
//console.log('Open: ', event);
}
this.webSocket.onmessage = (event) => {
//console.log('Received message: ', event);
const msg : Message = JSON.parse(event.data);
switch(msg.Type){ ...
and here is how I establsh a websocket on the server (C# console app):
public Server(int port)
{
//setup websocket
_port = port;
_webSocket = new WebSocketServer();
RootConfig r = new RootConfig();
ServerConfig s = new ServerConfig();
s.Name = "SuperWebSocket";
s.Ip = "Any";
s.Port = port;
s.Mode = SocketMode.Tcp;
SuperSocket.SocketEngine.SocketServerFactory f = new SuperSocket.SocketEngine.SocketServerFactory();
_webSocket.Setup(r, s, f);
_webSocket.Listeners[0].EndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.16"),port);
_webSocket.NewSessionConnected += Connect;
_webSocket.NewDataReceived += DataReceived;
_webSocket.NewMessageReceived += MessageReceived;
_webSocket.SessionClosed += SessionClosed; ...

C# - Why does BrowserMob.GetHar() only return 1 entry?

I am writing some simple C# code to try automatically getting HAR file from Chrome browser. I am using browser-mob-proxy and there is a function: GetHar() which is supposed to return some different entries of URL, request and response time, etc. However, it always return me only 1 entry which is the original URL I am negativing to: www.google.com
I've tried to use dr.Navigate().Refresh() to make sure the page is reloaded so there are some activities on chrome DevTool Network section.
server.Start();
Thread.Sleep(1000);
Client client = server.CreateProxy();
client.NewHar("google");
var chromeOptions = new ChromeOptions();
var seleniumProxy = new Proxy { HttpProxy = client.SeleniumProxy };
chromeOptions.Proxy = seleniumProxy;
var dr = new ChromeDriver(chromeOptions);
dr.Navigate().GoToUrl("http://www.google.com");
dr.FindElementByClassName("gb_e").Click();
Thread.Sleep(3500);
dr.Navigate().Refresh();
// Get the performance stats
HarResult harData = client.GetHar();
Log log = harData.Log;
Entry[] entries = log.Entries;
foreach (var e in entries)
{
Request request = e.Request;
Response response = e.Response;
var url = request.Url;
var time = e.Time;
var status = response.Status;
var testStr = "Url: " + url + " - Time: " + time + " Response: " + status;
}
I expected GetHar() function will return more entries instead of only 1.
Not sure why, but the issue has been resolved by adding SSL proxy:
var seleniumProxy = new Proxy { HttpProxy = client.SeleniumProxy , SslProxy = client.SeleniumProxy };

MQTTnet client can't connect server certificate

I'm using MQTTnet library to connect to my MQTT server that needs a server certificate. The client one is not needed.
I already installed the certificate inside my PC as i found in other post and created the .pfx file to create the certificate but the program doesn't give me any error..it simply doesn't connect to the topic.
This is my example code
//Create a new MQTT client
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var caCert = new X509Certificate(#"C:\caserverroot.pfx", "mypsw");
var url = "mymqtt.com";
var username = "user";
var psw = "user";
var port = 8885;
var options = new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer(url, port)
.WithCredentials(username, psw)
.WithTls(new MqttClientOptionsBuilderTlsParameters()
{
AllowUntrustedCertificates = true,
UseTls = true,
Certificates = new List<byte[]> { new X509Certificate2(caCert).Export(X509ContentType.Cert) },
CertificateValidationCallback = delegate { return true; },
IgnoreCertificateChainErrors = false,
IgnoreCertificateRevocationErrors = false
})
.WithCleanSession()
.WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311)
.Build();
// Connecting
var result = await mqttClient.ConnectAsync(options);
// Subscribe to a topic
mqttClient.Connected += async (s, e) =>
{
Console.WriteLine("### CONNECTED WITH SERVER ###");
await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("/mytopic").Build());
Console.WriteLine("### SUBSCRIBED ###");
};
With all the orther events that i found here: https://github.com/chkr1011/MQTTnet/wiki/Client
Any of you had experience about this library? How to debug it and find the error?
Thanks
So, I don't know why i was wrong but using the ManagedMqttClient saved my situation.
This is the code that works like a charm
//Create a new MQTT client
var mqttClient = new MqttFactory().CreateManagedMqttClient();
var caCert = new X509Certificate(#"C:\cert.pfx", "psw");
var url = "myurl.com";
var username = "user";
var psw = "user";
var port = 8885;
var options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(30))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer(url, port)
.WithCredentials(username, psw)
.WithTls(new MqttClientOptionsBuilderTlsParameters()
{
AllowUntrustedCertificates = false,
UseTls = true,
Certificates = new List<byte[]> { new X509Certificate2(caCert).Export(X509ContentType.Cert) },
CertificateValidationCallback = delegate { return true; },
IgnoreCertificateChainErrors = false,
IgnoreCertificateRevocationErrors = false
})
.WithCleanSession()
.WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311)
.Build())
.Build();
// Connecting
await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("$share:mygroup:/mytopic").Build());
await mqttClient.StartAsync(options);

Adaptive Payments giving Exception on Web Server in c#

I am working on Delayed Chained Payments Module in Adaptive Payments in Paypal. I am Using AdaptivePaymentsCoreSdk for it and it is working fine on LocalHost as well as one web Server. All working is going Fine. But when I Deploy my application on another Server than On Service.Pay I am Getting an Exception. Exception is as Follows:-
PayPal.Exception.ConnectionException: Invalid HTTP response The underlying connection was closed: An unexpected error occurred on a receive.
at PayPal.HttpConnection.Execute(String payLoad, HttpWebRequest httpRequest)
at PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest, String apiUserName)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest)
at Payme101.Controllers.HomeController.Order_Pay(Order_Pay single) in d:\Completed\Payme10\Payme101\Payme101\Controllers\HomeController.cs:line 2404
My Code is As Follows:-
PayRequest request = new PayRequest();
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
ReceiverList receiverList = new ReceiverList();
request.requestEnvelope = requestEnvelope;
Receiver receiver1 = new Receiver();
receiver1.amount = 10;
receiver1.email = "Primary Email ID";
receiver1.primary = true;
receiver1.invoiceId = str;
Receiver receiver2 = new Receiver();
receiver2.amount = 8;
receiver2.email = SellerMail;
receiver2.primary = false;
receiver2.invoiceId = str;
receiverList.receiver.Add(receiver1);
receiverList.receiver.Add(receiver2);
request.receiverList = receiverList;
request.actionType = "PAY_PRIMARY";
request.currencyCode = "USD";
request.returnUrl = "http://ServerIP/Home/complete/?payKey=${payKey}";
request.cancelUrl = "http://ServerIP/Home/cancel?payKey=${payKey}";
//request.returnUrl = "http://localhost:1735/Home/complete/?payKey=${payKey}";
//request.cancelUrl = "http://localhost:1735/Home/cancel?payKey=${payKey}";
AdaptivePaymentsService service = null;
PayResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Pay(request);
}
catch (Exception ex)
{
//Here I am getting Exception.
return RedirectToAction("Order_Pay2", "Home", new { id = ex.ToString() });
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_ap-payment&paykey=" + response.payKey;
return Redirect(redirectUrl);
}
Can Anybody tell me what I am doing wrong and What should i change to Remove this Exception And Make Payment Successfull.
Thanks in Advance...

Categories