CSharp - IMAP Connection TCP error - c#

I wanted to access over IMAP to my gmail account bsed on this example:
http://code.msdn.microsoft.com/windowsdesktop/Simple-IMAP-CLIENT-b249d2e6
When I start to debug the code, I get always an error at the codeline:
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
It gives me the error:
"The requested service provider could not be loaded or initialized"
My search on Internet give me as result, that I need to repair the Window Socket.
But, when I run directkly the compiled .exe file, then I don't get this error at all.
This makes no sense to me.
Does anybody have an idea, whats wrong here?
The code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace IMAP
{
class Program
{
static System.Net.Sockets.TcpClient tcpc = null;
static System.Net.Security.SslStream ssl = null;
static string username, password;
static void Main(string[] args)
{
username = "(username)";
password = "(password)";
SSLAuthenticate = "imap.gmail.com";
try
{
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
...
I am thankful for any help.

Related

DirectoryEntry giving com exception when trying to connect ldap server using secure port

Exception snapshot
enter image description here
STEP A=>Validating the proper certificate configuration
I have a window service via which i am trying to connect the LDAP server from secure port 636 (SSL), all the certificate are properly
configured and i have verified this using the tool ldap.exe and also check the portqry tool to check if the port 636 is listening or not
and was successful in doing that.
STEP B=>Code Snippet Which is not working for secure port 636(For SSL) but working correctly with non secure port (389) A strange
observation the Below code works well when i run it as console based
application even with port 636 but fails when run as window service.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace SampleLDAPWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TestDirectoryEntryWay();
}
protected override void OnStop()
{
}
}
public DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = null;
ldapConnection = new DirectoryEntry("LDAP://abc.domain.com:636", "DomainAdmin", "DomainAdmin123", AuthenticationTypes.SecureSocketsLayer);
return ldapConnection;
}
public void TestDirectoryEntryWay()
{
DirectorySearcher _searcher = null;
SearchResult result_user = null;
DirectoryEntry de = createDirectoryEntry();
try
{
object o = de.SchemaEntry;//Getting a com exception as the SchemaEntry is null not sure why as the same is working properly in port 389
_searcher = new DirectorySearcher(de, "(&(objectClass=user)(SAMAccountName=" + "demouser1" + "))");
if (_searcher != null)
{
result_user = _searcher.FindOne();
}
}
catch (Exception ex)
{
//Getting a com exception
}
}
}
}
STEP C=>Code which is working in both port 636 and port 389 in window service
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace SampleLDAPWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
// TestDirectoryEntryWay();
var isLogged2 = SignInLDAP2("DomainAdmin", "DomainAdmin123", ""LDAP://abc.domain.com:636"", "abc.domain.com", true);
}
protected override void OnStop()
{
}
public bool SignInLDAP2(string user, string psw, string ldapPath, string domain = null, bool useSSL = false)
{
// LdapConnection ldapConnection = new LdapConnection(ldapPath);
var ldapDirectoryIdentifier = new LdapDirectoryIdentifier("abc.domain.com", 636, true, false);
LdapConnection ldapConnection = new LdapConnection(ldapDirectoryIdentifier);
if (useSSL)
{
ldapConnection.SessionOptions.SecureSocketLayer = true;
ldapConnection.AuthType = AuthType.Negotiate;
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
}
//var networkCredential = new NetworkCredential("Hey", "There", "Guy");
var networkCredential = new NetworkCredential(user, psw, domain);
try
{
ldapConnection.Bind(networkCredential);
bool exists = UserExists("demouser1");
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool UserExists(string username)
{
// create your domain context
using (PrincipalContext domain = new PrincipalContext(ContextType.Domain, "abc.domain.com", "DomainAdmin", "DomainAdmin123"))
{
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
}
}
}
}
QUESTION Here is
Is there a problem when working with Secure port with DirectoryEntry, as LdapConnection & networkCredential works smoothly with both the ports(636 &389),
i have a legacy code which uses DirectoryEntry and i want it work for secure port as well can some one please help me, how to make the STEP B working for secure port
also.
Thanks in Advance for all the Support & guidance.
It's likely that the SSL certificate isn't trusted by the computer you're running this on.
I use Chrome to test this. Run Chrome like this (adjust for the path your Chrome is in):
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=636
Then in Chrome, go to https://abc.domain.com:636. If the certificate is trusted, you'll see a "cannot connect" kind of message. But if it is not trusted, Chrome will give you a big red warning and you know that's the problem.
To trust the cert, you need to get the root certificate (as a file, likely *.cer or *.crt) and install it on every machine that will be running your code. Here are instructions for installing a root cert in Windows: https://www.thewindowsclub.com/manage-trusted-root-certificates-windows

TestStack.White and CCleaner

I've very new to the TestStack (White) UI Automation library and I'm having a bit of an issue in terms of "hooking" the process. I'm trying to hook CCleaner, but I keep getting
An unhandled exception of type 'TestStack.White.AutomationException'
occurred in TestStack.White.dll
Additional information: Couldn't find window with title Piriform
CCleaner in process 1156, after waiting for 30 seconds:
My current code is:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TestStack.White;
using TestStack.White.Factory;
using TestStack.White.UIItems.Finders;
using TestStack.White.InputDevices;
using TestStack.White.UIItems.WindowItems;
namespace NightWipe
{
class Program
{
private const string ExeSourceFile = #"C:\Program Files\CCleaner\CCleaner.exe";
private static TestStack.White.Application _application;
private static TestStack.White.UIItems.WindowItems.Window _mainWindow;
static void Main(string[] args)
{
clean();
}
public static string clean()
{
var psi = new ProcessStartInfo(ExeSourceFile);
_application = TestStack.White.Application.AttachOrLaunch(psi);
_mainWindow = _application.GetWindow("Piriform CCleaner");
_mainWindow.WaitWhileBusy();
return "";
}
}
}
I thought that maybe it was the name of the process since CCleaner starts another process (not CCleaner.exe) but CCleaner64.exe as seen here, which I can assume is for 64 bit operating systems maybe? Anyway I tried names including: "CCleaner", "CCleaner64"; but this threw the same exact exception.
I'm using Inspect by Microsoft and this is what it pulls for me (large image):
Inspect's information. Any idea what I'm doing wrong here?
The problem is that CCleaner is visible as WIN32 app. So GetWindow() doesn't work. You can try this code:
public void CCleanerSample()
{
var application = Application.AttachOrLaunch(new ProcessStartInfo(#"C:\Program Files\CCleaner\CCleaner.exe"));
AutomationElement ccleanerAutomationElement = null;
Console.Write("Waiting till WIN32 app is launching");
while (ccleanerAutomationElement == null)
{
ccleanerAutomationElement = AutomationElement.RootElement.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "Piriform CCleaner"));
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine(" Done");
var mainWindow = new Win32Window(ccleanerAutomationElement, WindowFactory.Desktop, InitializeOption.NoCache,
new WindowSession(application.ApplicationSession, InitializeOption.NoCache));
}

Why can't I connect to an online MS Team Foundation project with C#

I have looked at various examples, and there are few/none connecting to an online TFS account, connecting to a TFS project. Below is the last attempted code, that also didn't work. Yes, I am a neophyte to VS .Net (C#). Any direction is greatly appreciated:
using System;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
namespace TfsApplication
{
class Program
{
static void Main(String[] args)
{
Uri collectionUri = new Uri("https://drmpractice.visualstudio.com");
TfsTeamProjectCollection collection =
new TfsTeamProjectCollection(
collectionUri,
new System.Net.NetworkCredential(#"myEmail#hotmail.com", "MyPassword"));
WorkItemStore workItemStore = collection.GetService<WorkItemStore>();
}
}
}
The returned error returned: "password, port, or project name is wrong".

C# MailMessage Display email instead of Send

I have been following the example below to send email using C# code with success:
MSDN Mail Message
However, I would like the code to display the composed email message on user machine, so that user can have a final check before hitting send button on outlook.
In the VBA world, I can use mail.Display in place of mail.Send.
Can anyone provide some advice to achieve that in C#?
Thanks.
How about this...
private void btnEmail_Click(object sender, EventArgs e)
{
string command = "mailto:somebody#domain.com?subject=The Subject&bcc=another#codegaim.com&body=Hi,I found this website and thought you might like it http://www.geocities.com/wowhtml/";
Process.Start(command);
}
Found a great solution to my problem i.e. to use Microsoft Office Interop Outlook instead of System.Net.MailMessage
followed this:
How to send a mail using Microsoft.Office.Interop.Outlook.MailItem by specifying the From Address
//using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Outlook;
namespace ConsoleApplication1
{
using Outlook = Microsoft.Office.Interop.Outlook;
public static class Program
{
static void Main(string[] args)
{
SendUsingAccountExample();
}
private static void SendUsingAccountExample()
{
var application = new Application();
var mail = (_MailItem)application.CreateItem(OlItemType.olMailItem);
mail.Body = "Hello";
mail.Subject = "Good Bye";
mail.To = "hello#google.com";
// Next 2 lines are optional. if not specified, the default account will be used
Outlook.Account account = Application.Session.Accounts["MyOtherAccount"];
mail.SendUsingAccount = account;
mail.Display(false); // To Display
//mail.Send(); // To Send
}
}
}

how to fix Webexception unhandle

i want to make console c# program to download and execute a program.exe file from web.
so i get a "Webexception unhandle" error when i run this program.can any one help me. thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.IO;
namespace Downloader{
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://www.pendrivelinux.com/downloads/Universal-USB-Installer/Universal-USB-Installer-1.9.5.1.exe");
string filename = #"C:\bootable.exe";
using (var wc = new WebClient())
{
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Headers.Add(HttpRequestHeader.UserAgent, "anything");
wc.DownloadFile(uri, filename);
}
}
}
}
can any one help me.
I'm guessing your WebException occurs on the last line (please in future include that in your question - we can't really help you based on guesswork).
wc.DownloadFile(uri, filename);
From the documentation on this method call, it will throw a WebException if one of the following is true:
The URI formed by combining BaseAddress and address is invalid.
filename is null or Empty.
The file does not exist.
An error occurred while downloading data.
We can rule out #2 immediately, as you've set that. To find out which of these situations you've got, try looking at the exception's message property (or the message property of the inner exception if there is one).

Categories