Read Gmail Email Attachment And Move To Any Folder In My Computer Using Console Application in c# Only..I tried POp3Client,TCpclient & Smtp..they all are working in web application..But I only need console application in c#
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
namespace FetchEmailFromGmail
{
class Program
{
static void Main(string[] args)
{
// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();
tcpclient.Connect("pop.gmail.com", 995);
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
sslstream.AuthenticateAsClient("pop.gmail.com");
StreamWriter sw = new StreamWriter(sslstream);
System.IO.StreamReader reader = new StreamReader(sslstream);
sw.WriteLine("USER someaccount#gmail.com"); sw.Flush();
sw.WriteLine("PASS somepass"); sw.Flush();
//sw.WriteLine("RETR 1");
//sw.WriteLine("STAT ");
sw.WriteLine("LIST ");
sw.Flush();
sw.WriteLine("Quit ");
sw.Flush();
string str = string.Empty;
string strTemp = string.Empty;
while ((strTemp = reader.ReadLine()) != null)
{
if (".".Equals(strTemp))
{
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
Console.Write(str);
reader.Close();
sw.Close();
tcpclient.Close(); // close the connection
Console.ReadLine();
}
}
}
Related
I tried to fetch the discussion items from the discussion form available on the SharePoint using client side code CSOM and I am connected successfully but unable to fetch the discussions...
Here is the link of the sharePoint :--
https:///sites//GlobalDiscussion/SitePages/Community%20Home.aspx
Below is my code :------
using System.Security;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using MongoDB.Driver;
using MongoDB.Bson;
using Microsoft.SharePoint;
namespace ConnectToSPO
{
class Program
{
static void Main(string[] args)
{
string webSPOUrl = "";
string userName = "";
SecureString password = new NetworkCredential("", "").SecurePassword;
try
{
using (var context = new ClientContext(webSPOUrl))
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
context.AuthenticationMode = ClientAuthenticationMode.Anonymous;
context.Credentials = new SharePointOnlineCredentials(userName, password);
Web web = context.Web;
context.ExecuteQuery();
Console.WriteLine(web.ServerRelativeUrl);
var filePath = web.ServerRelativeUrl + "/GlobalDiscussion/SitePages/Community%20Home.aspx";
Console.WriteLine(filePath);
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, filePath);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error is: " + ex.Message);
}
}
}
}
It will be great if anyone can help me out ...
Thank you...
Take a look at the following two programs:
//Server
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MyServerProgram
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 2000;
TcpListener listener = new TcpListener(ip, port);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream netStream = client.GetStream();
BinaryReader br = new BinaryReader(netStream);
try
{
while (client.Client.Connected)
{
string str = br.ReadString();
Console.WriteLine(str);
}
}
catch
{
br.Close();
netStream.Close();
client.Close();
listener.Stop();
}
}
}
}
//Client
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MyClientProgram
{
class Program
{
static void Main(string[] args)
{
int port = 2000;
TcpClient client = new TcpClient("localhost", port);
NetworkStream netStream = client.GetStream();
BinaryWriter br = new BinaryWriter(netStream);
try
{
int i=1;
while (client.Client.Connected)
{
br.Write(i.ToString());
br.Flush();
i++;
int milliseconds = 2000;
System.Threading.Thread.Sleep(milliseconds);
}
}
catch
{
br.Close();
netStream.Close();
client.Close();
}
}
}
}
These programs are working fine.
Suppose, at this point of this program, I need the server to print a message on the screen as soon as a client gets connected to it, and, also when the client is disconnected.
How can I do that?
AcceptTcpClient blocks execution and starts waiting for connection. So right after it you can write message that client connected. Also you could write connected client address. Just for information, but sometimes it could be helpful.
TcpClient client = listener.AcceptTcpClient();
ShowMessage("Connected " + ((IPEndPoint)client.Client.RemoteEndPoint).Address);
For detect client disconnect you could catch exceptions. Change your catch like this:
catch (Exception ex) {
var inner = ex.InnerException as SocketException;
if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
ShowMessage("Disconnected");
else
ShowMessage(ex.Message);
...
EDIT
With all great functionality that NetworkCommsDotNet offers, it looks like this library is not actively supported anymore. I am changing direction to accept Eser's response as answer. I tested the provided code and it worked. Thanks for your help.
Below is my code of simple TCP client-server, based on NetworkCommsDotNet library. The client periodically sends changing positions of an "object" to the server, and the server displays them. This works fine, however, what I want to achieve is exactly the opposite: I want the client to only connect to the server, and once the server detects a connection, then it starts periodically sending some X and Y coordinates back to the client. I could not have this done with NetworkCommsDotNet, any help is appreciated.
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections.TCP;
namespace ObjectPositionClient
{
class Program
{
static void Main(string[] args)
{
try {
var conn = TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 50747));
System.Timers.Timer tmer;
tmer = new System.Timers.Timer(3000);
tmer.Elapsed += (sender, e) => TimerElapsed(sender, e, conn);
tmer.Enabled = true;
Console.WriteLine("Press any key to exit client.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
catch (Exception e)
{
Console.WriteLine(e.InnerException + "\n" + e.Message);
}
}
static public void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e, TCPConnection conn)
{
Random rnd = new Random();
int X = rnd.Next(1, 101);
int Y = rnd.Next(1, 51);
conn.SendObject("Message", "X=" + X + "; Y=" + Y);
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
namespace ObjectPositionServer
{
class Program
{
static void Main(string[] args)
{
try
{
var con = Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 50747));
NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", PrintIncomingMessage);
Console.WriteLine("Server ready. Press any key to shutdown.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
catch (Exception e)
{
Console.WriteLine(e.InnerException + "\n" + e.Message);
}
}
private static void PrintIncomingMessage(PacketHeader header, Connection
connection, string message)
{
Console.WriteLine(message + "\n");
}
}
}
Here is a TCP based, basic, client/server sample. Whenever a client connects to server, server sends 10 strings to client and then close the connection. I think this is similar to your case.
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
public class TCPTest
{
public static void StartAll()
{
Task.Run(() => StartServer());
Task.Run(() => StartClient());
}
static void StartServer()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server Started");
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine("A new client is connected");
ThreadPool.QueueUserWorkItem(ServerTask,client);
}
}
static void ServerTask(object o)
{
using (var tcpClient = (TcpClient)o)
{
var stream = tcpClient.GetStream();
var writer = new StreamWriter(stream);
for (int i = 0; i < 10; i++)
{
writer.WriteLine($"packet #{i + 1}");
writer.Flush();
Thread.Sleep(1000);
}
Console.WriteLine("Server session ended..");
}
}
static void StartClient()
{
TcpClient client = new TcpClient();
client.Connect("localhost", 12345);
var stream = client.GetStream();
var reader = new StreamReader(stream);
string line = "";
while((line = reader.ReadLine()) != null)
{
Console.WriteLine("Client received: "+ line);
}
Console.WriteLine("Client detected end of the session");
}
}
Use TCPTest.StartAll(); to start the test.
You can even telnet to this server. telnet localhost 12345
EDIT
Since you have commented, you want to transfer objects between client and server, I modified to code to show how it can be done (using Json.Net). This time, server sends 10 User objects to client.
I will post it as a new code, in case someone wants to see the minor differences.
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
public class TCPTest
{
//Sample class to transfer between server and client
public class User
{
public string Name { get; set; }
public int Id { get; set; }
public DateTime BirthDate { set; get; }
}
public static void StartAll()
{
Task.Run(() => StartServer());
Task.Run(() => StartClient());
}
static void StartServer()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server Started");
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine("A new client is connected");
ThreadPool.QueueUserWorkItem(ServerTask, client);
}
}
static void ServerTask(object o)
{
using (var tcpClient = (TcpClient)o)
{
var stream = tcpClient.GetStream();
var writer = new StreamWriter(stream);
for (int i = 0; i < 10; i++)
{
var user = new User() { Name = $"Joe{i}", Id = i , BirthDate = DateTime.Now.AddDays(-10000)};
var json = JsonConvert.SerializeObject(user);
writer.WriteLine(json);
writer.Flush();
Thread.Sleep(1000);
}
Console.WriteLine("Server session ended..");
}
}
static void StartClient()
{
TcpClient client = new TcpClient();
client.Connect("localhost", 12345);
var stream = client.GetStream();
var reader = new StreamReader(stream);
string json = "";
while ((json = reader.ReadLine()) != null)
{
var user = JsonConvert.DeserializeObject<User>(json);
Console.WriteLine($"Client received: Name={user.Name} Id={user.Id} BirthDate={user.BirthDate}");
}
Console.WriteLine("Client detected end of the session");
}
}
I am creating a server-client application where the server and client can talk to each other.
When I call the start method on the server, i get an error saying this:
Only one usage of each socket address (protocol/network address/port) is normally permitted
Here is Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace NetworkingTest {
class Program {
static void Main(string[] args) {
bool readLine = true;
string input = "";
while (true) {
if (readLine == true) {
input = Console.ReadLine();
}
if (input == "server") {
Server server = new Server(IPAddress.Any, 12346);
readLine = false;
}
if (input == "client") {
Client client = new Client(IPAddress.Parse("myipv4"), 12346);
readLine = false;
}
}
}
}
}
Here is Server.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetworkingTest {
class Server {
public TcpListener server;
public Server (IPAddress ip, int port) {
server = new TcpListener(ip, port);
server.Start();
Thread serverRunThread = new Thread(new ThreadStart(RunServer));
serverRunThread.Start();
}
void RunServer () {
while (true) {
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected!");
Thread serverHandlerThread = new Thread(new ParameterizedThreadStart(HandleClient));
serverHandlerThread.Start(client);
}
}
void HandleClient(object c) {
TcpClient client = (TcpClient)c;
NetworkStream stream = client.GetStream();
int i;
string data = null;
byte[] bytes = new byte[256];
while((i = stream.Read(bytes, 0, bytes.Length)) != 0) {
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: " + data);
}
stream.Close();
client.Close();
}
}
}
And here is Client.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetworkingTest {
class Client {
public TcpClient client;
public Client (IPAddress ip, int port) {
client = new TcpClient();
client.Connect(ip, port);
Thread thread = new Thread(new ThreadStart(ConnectToServer));
thread.Start();
}
void ConnectToServer () {
while (true) {
string input = Console.ReadLine();
if (input == "exit" || input == "quit" || input == "close") {
break;
} else {
SendMessageToServer(input);
}
}
}
void SendMessageToServer (string message) {
NetworkStream stream = client.GetStream();
byte[] bytes = Encoding.ASCII.GetBytes(message);
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
}
}
EDIT:
There was a problem in Program.cs, fixed while loop:
while (readLine == true) {
input = Console.ReadLine();
if (input == "server") {
Server server = new Server(IPAddress.Any, 12346);
readLine = false;
}
if (input == "client") {
Client client = new Client(IPAddress.Parse("10.0.0.5"), 12346);
readLine = false;
}
}
That happens because of the error in your while(true) loop. First you ask user for a line with Console.ReadLine(). If input is "server" you start your server, BUT then you go to the beginning of your while loop and your readLine variable is false, and input is still "server", so it creates second server (basically you have infinite loop). Since you already have one sever on this port - second try fails with the error you see.
To fix, remove while loop, or do it more correctly, like this:
static void Main(string[] args) {
while (true) {
Console.WriteLine("Type \"server\" to start server, type \"client\" to start client, type \"exit\" to exit");
string input = Console.ReadLine();
if (input == "server") {
Server server = new Server(IPAddress.Any, 12346);
}
else if (input == "client") {
Client client = new Client(IPAddress.Parse("myipv4"), 12346);
}
else if (input == "exit")
return;
}
}
I am building a bare bones program that simple delivers a message from server to client.
Now i am successfully able to establish connection between the server and client, however the client program is unable to read from the stream. Here's my code.
Code for server program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console
{
class Program
{
static TcpListener listener;
static void Main(string[] args)
{
string name = Dns.GetHostName();
IPAddress[] address = Dns.GetHostAddresses(name);
/*
foreach(IPAddress addr in address)
{
Console.WriteLine(addr);
}*/
Console.WriteLine(address[1].ToString());
listener = new TcpListener(address[1], 2055);
listener.Start();
Socket soc = listener.AcceptSocket();
Console.WriteLine("Connection successful");
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.Write("A test message");
Console.WriteLine("Test message delivered. Now ending the program");
/*
string name = Dns.GetHostName();
Console.WriteLine(name);
//IPHostEntry ip = Dns.GetHostEntry(name);
//Console.WriteLine(ip.AddressList[0].ToString());
IPAddress[] adr=Dns.GetHostAddresses(name);
foreach (IPAddress adress in adr)
{
Console.WriteLine(adress);
}
*/
Console.ReadLine();
}
}
}
and here's the code from the client program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console_client
{
class Program
{
static void Main(string[] args)
{
string display;
TcpClient client = new TcpClient("localhost", 2055);
Stream s = client.GetStream();
Console.WriteLine("Connection successfully received");
StreamWriter sw = new StreamWriter(s);
StreamReader sr = new StreamReader(s);
sw.AutoFlush = true;
while (true)
{
display = sr.ReadLine();
Console.WriteLine("Reading stream");
if (display == "")
{
Console.WriteLine("breaking stream");
break;
}
}
Console.WriteLine(display);
}
}
}
now i am successfully able to establish connection between the programs as indicated by various check messages. The server program is also successfully able to send the data into the stream.
However the client program is unable to read data from the stream. It seems to be stuck at readline() function.
Now i have been banging my head against the wall on this problem for hours now and would be greatly thankful if somebody is able to help me.
Look at your server:
sw.AutoFlush = true;
sw.Write("A test message");
You're never writing a line break, which is what the client is waiting to see.