I'm trying to send a letter with a picture to the mail, my code works with html files, pictures are sent, but when opened, it gives an error. I'm doing my lab work and on assignment I can't use MailMessage for example. I set the sending address from my windows forms.
using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
namespace NetworksNeLaba2
{
public class Program
{
private const string AddressFrom = "MYGM";
private const string PasswordFrom = "MYPS";
private static readonly Emailbox _emailbox = new Emailbox(AddressFrom, PasswordFrom);
private const string HostName = "smtp.gmail.com";
private const int Port = 465;
private static readonly ConnectionInstaller _connectionInstaller = new ConnectionInstaller(HostName, Port);
public static void Main(string[] args)
{
}
public void InitializeComponents(string address, string subject)
{
var direction = new MessageDirection(_emailbox.Address, address);
var commands = new []
{
$"EHLO {HostName}",
"AUTH LOGIN",
_emailbox.Address,
_emailbox.Password,
$"MAIL FROM:<{direction.From}>",
$"RCPT TO:<{direction.To}>",
"DATA"
};
var fileName = "cat.jpeg";
var ct = new ContentType();
ct.MediaType = MediaTypeNames.Image.Jpeg;
var data = new Attachment(fileName, ct.MediaType);
var s = data.ContentStream;
var reader = new StreamReader(s);
var letterContent = new []
{
$"Subject:{subject}\r\n",
$"From:Roma {AddressFrom}\r\n",
$"To:{address}\r\n",
$"Content-Type:{data.ContentType}\r\n",
$"Content-Disposition:{data.ContentDisposition}\r\n",
$"Content:{reader.ReadToEnd()}\r\n",
//$"Date:{DateTime.Now}\r\n",
".\r\n"
};
var letter = String.Concat(letterContent);
_connectionInstaller.SendMessage(commands, letter);
}
}
}
The first part of the code is what commands and the content of the letter I set, below I attached the code that processes the commands.
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace NetworksNeLaba2
{
public class ConnectionInstaller
{
private readonly TcpClient _tcpClient = new TcpClient();
private readonly SslStream _sslStream;
private readonly byte[] _buffer = new byte[512];
public ConnectionInstaller(string hostName, int port)
{
_tcpClient.Connect(hostName, port);
_sslStream = new SslStream(_tcpClient.GetStream());
_sslStream.AuthenticateAsClient(hostName);
}
public void SendMessage(string[] commands,string letterContent)
{
foreach (var command in commands)
{
WriteBuffer(command + "\r\n");
}
WriteBuffer(letterContent);
}
private void WriteBuffer(string str)
{
_sslStream.Write(Encoding.ASCII.GetBytes(str));
_sslStream.Read(_buffer, 0, _buffer.Length);
Console.WriteLine(Encoding.ASCII.GetString(_buffer));
Array.Clear(_buffer, 0, _buffer.Length);
}
}
}
I am having an issue while trying to add data to a listbox from my main form, I am trying to add data to that list from a new class in my project, I need that new class to be able to add data to my listbox without errors, I am trying to use a invoke and I am getting the following error (System.InvalidOperationException: 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.') I have seen that error in other questions in stack overflow but similar to my issue, I will be adding both classes of my code here, one is the main class and the other a second class I created that will need to add data to the listbox. the data is coming from a telnet tcp/ip and port 23 that connection is working fine, the problem is adding that data to my listbox.
Main class calling the functions from my other class
namespace BarcodeReceivingApp
{
//TelnetConnection stopConnection = new TelnetConnection();
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
const string Hostname = "myip";
private const int Port = 23;
public BarcodeReceivingForm()
{
InitializeComponent();
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
//var connection = new TelnetConnection(Hostname, Port);
// connection.CloseConnection();
}
}
}
class that will change the data of my listbox from the main class.
namespace BarcodeReceivingApp
{
public class TelnetConnection
{
public BarcodeReceivingForm BcForm = new BarcodeReceivingForm();
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port)
{
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
//Assign networkstream
_networkStream = _client.GetStream();
//start socket read/write thread
_readWriteThread = new Thread(ReadWrite);
_readWriteThread.Start();
}
public void ReadWrite()
{
//Set up connection loop
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
BcForm.lst_BarcodeScan.Invoke(new Action (() => BcForm.lst_BarcodeScan.Items.Add(received)));
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
the final results like I said is my ReadWrite method when running the loop will add the data to my listbox from my main form class
here the image where I get the error
Image of Error
Write your second class like this
using System;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp {
public class TelnetConnection {
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private Form foo;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port,Form f)
{
this.foo = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite());
_readWriteThread.Start();
}
public void ReadWrite()
{
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
if (foo.lst_BarcodeScan.InvokeRequired)
{
foo.lst_BarcodeScan.Invoke(new MethodInvoker(delegate {foo.lst_BarcodeScan.Items.Add(received);}));
}
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
Then use it like this from your main class:
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port, this);
}
Please see my first Persistent Subscription below:
namespace PersistentSubscription
{
internal class Program
{
private static void Main()
{
var subscription = new PersistentSubscriptionClient();
subscription.Start();
}
}
public class PersistentSubscriptionClient
{
private IEventStoreConnection _conn;
private const string STREAM = "$ce-customer";
private const string GROUP = "a_test_group";
private const int DEFAULTPORT = 1113;
private static readonly UserCredentials User = new UserCredentials("admin", "changeit");
private EventStorePersistentSubscriptionBase _subscription;
public void Start()
{
var settings = ConnectionSettings.Create();
using (_conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
_conn.ConnectAsync().Wait();
CreateSubscription();
ConnectToSubscription();
Console.WriteLine("waiting for events. press enter to exit");
Console.ReadLine();
}
}
private void ConnectToSubscription()
{
var bufferSize = 10;
var autoAck = true;
Action<EventStorePersistentSubscriptionBase, ResolvedEvent> eventAppeared = EventAppeared;
_subscription = _conn.ConnectToPersistentSubscription(STREAM, GROUP, eventAppeared, SubscriptionDropped, User, bufferSize, autoAck);
}
private void SubscriptionDropped(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
SubscriptionDropReason subscriptionDropReason, Exception ex)
{
ConnectToSubscription();
}
private static void EventAppeared(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
ResolvedEvent resolvedEvent)
{
MemoryStream stream = new MemoryStream(resolvedEvent.Event.Data);
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
try
{
CustomerCreated customerCreated = (CustomerCreated)formatter.Deserialize(stream);
Console.WriteLine(customerCreated);
}
catch (Exception e)
{
var test = "test";
}
}
private void CreateSubscription()
{
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
try
{
_conn.CreatePersistentSubscriptionAsync(STREAM, GROUP, settings, User).Wait();
}
catch (AggregateException ex)
{
if (ex.InnerException.GetType() != typeof(InvalidOperationException)
&& ex.InnerException?.Message != $"Subscription group {GROUP} on stream {STREAM} already exists")
{
throw;
}
}
}
}
}
and my first client below:
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using EventStore.ClientAPI;
namespace WritingEvents
{
class Program
{
static void Main(string[] args)
{
const int DEFAULTPORT = 1113;
var settings = ConnectionSettings.Create();
using (var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
conn.ConnectAsync().Wait();
CustomerCreated c1 = new CustomerCreated { Id = Guid.NewGuid(), Name = "Maria" };
EventData customerCreated1 = GetEventDataFor(c1);
conn.AppendToStreamAsync("customer-100", ExpectedVersion.Any, customerCreated1).Wait();
}
}
private static EventData GetEventDataFor(CustomerCreated customerCreated)
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, customerCreated);
byte[] customerCreatedEventByteArray = stream.ToArray();
return new EventData(
Guid.NewGuid(),
"eventType",
true,
customerCreatedEventByteArray,
null
);
}
}
[Serializable]
public class CustomerCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
I run the server and then then the client. I see an error when deserializing the CustomerCreated event on the server side. The error is: "End of stream was encountered before parsing was completed".
If I change this line:
private const string STREAM = "$ce-customer";
to this:
private const string STREAM = "customer-100";
Then deserialization works correctly on the server side.
How do I handle all customer events - not just customer 100?
I have --run-projections=all when starting Event Store. I have also enabled all projections:
This question helped me: Using the Event Store Client API (.NET), how to I write to a stream and link one event to another?
I simply had to change this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos() //Specifically this line
.StartFromCurrent();
to this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.ResolveLinkTos() //Specifically this line
.StartFromCurrent();
DoNotResolveLinkTos gets a link to the original event, whereas ResolveLinkTos gets the actual event itself. Therefore I was trying to deserialize the link object, which was causing the exception.
I'm making an application as follows: I have a webservice running on a local server, this webservice returns json like this:
[{"Id":1,"Titulo":"Live to win","Link":"https://www.youtube.com/embed/DPHlGVe8wxI","BandaId":1,"BandaNome":"Paul Stanley","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":false},{"Id":2,"Titulo":"Welcome to the jungle","Link":null,"BandaId":2,"BandaNome":"Guns n´ roses","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":3,"Titulo":"Something just like this","Link":null,"BandaId":3,"BandaNome":"The Chainsmokers","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":4,"Titulo":"Beliver","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":5,"Titulo":"Radioactive","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":6,"Titulo":"Friends - Original Mix","Link":null,"BandaId":5,"BandaNome":"Steener","GeneroId":2,"GeneroNome":"EDM","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":7,"Titulo":"Amanheceu","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":8,"Titulo":"Sonhador II","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":9,"Titulo":"Amianto","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":10,"Titulo":"Monstros","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":11,"Titulo":"Piloto Automático","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":12,"Titulo":"Eutanásia","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":13,"Titulo":"Shots - Broiler Remix","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-24T16:55:46","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true}]
But now I need to create a Windows Services that communicates with this WebService and what it receives in a database, I spent all day doing this webservice in several ways, but I did not find anything about good practices with webservices or etc. I'll show you what I did, but I'd like some tips on windows services, thank you
Here is my code
Service:
private Timer _worker;
private readonly int _interval = Convert.ToInt32(ConfigurationManager.AppSettings["timer"]);
private readonly string _connection = ConfigurationManager.AppSettings["connection"];
//private readonly Connector _usuarioConnector;
private readonly Connector _bandaConnector;
//private readonly Connector _generoConnector;
private readonly Connector _musicaConnector;
private SqlConnection conn;
public Service1()
{
//_usuarioConnector = new Connector("UsuarioBase");
_bandaConnector = new Connector("BandaBase");
//_generoConnector = new Connector("GeneroBase");
_musicaConnector = new Connector("MusicaBase");
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_worker = new Timer((Update), null, 0, _interval);
}
protected override void OnStop()
{
}
private void Update(Object state)
{
using (SqlConnection connection = new SqlConnection(
_connection))
{
SqlCommand command = new SqlCommand("insert into Genero(nome, descricao, dtcriacao, criadorid, ativo) values('teste', 'teste', getdate(), 1, 1)", connection);
command.Connection.Open();
command.ExecuteNonQuery();
EventLog.WriteEntry("Query executada", EventLogEntryType.Warning);
}
}
Loader
public class Loader
{
public static List<Usuario> LoadUsuarios(Connector usuarioConnector)
{
return (List<Usuario>)Newtonsoft.Json.JsonConvert.DeserializeObject(usuarioConnector.GetData(), typeof(List<Usuario>));
}
public static List<Banda> LoadBandas(Connector bandaConnector)
{
var bandasDtos = (List<BandaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(bandaConnector.GetData(), typeof(List<BandaDto>));
return bandasDtos.Select(dto => dto.ConvertToBanda()).ToList();
}
//public static List<Genero> LoadGeneros(Connector generoConnector)
//{
//var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
//return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
//}
public static List<Musica> LoadMusicas(Connector musicaConnector)
{
var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
}
}
Connector
private string Host { get; }
private WebRequest _request;
public WebResponse Response;
public string ConnectionStatus;
private Stream _dataStream;
private StreamReader _reader;
public Connector(string config)
{
Host = ConfigurationManager.AppSettings[config];
}
public string GetData()
{
StartConnection();
_dataStream = Response.GetResponseStream();
_reader = new StreamReader(_dataStream);
var toReturn = _reader.ReadToEnd();
EndConnection();
return toReturn;
}
private void StartConnection()
{
_request = WebRequest.Create(Host);
_request.Credentials = CredentialCache.DefaultCredentials;
Response = _request.GetResponse();
ConnectionStatus = (((HttpWebResponse)Response).StatusDescription);
}
private void EndConnection()
{
_reader.Close();
Response.Close();
}
Edit1 In the current code it is doing a select, however in what I intend to do it will do inserts
I discovered, unfortunately the timer was not working, so I just changed it to a thread.
I have two nearly identical blocks of code in two separate projects; the second project was created to use the same ConnectClass as the first.
However, in the new project (the second code block shown below), the compiler gives the following error message regarding the error handler static void client_ErrorEvents(object sender, a.b.c.ErrorEventArgs e):
The call is ambiguous between the following methods or properties: 'ProjectName.ConnectClass.client_ErrorEvents(object, a.b.c.ErrorEventArgs)' and 'ProjectName.ConnectClass.client_ErrorEvents(object, a.b.c.ErrorEventArgs)'
HERE IS THE FIRST CODE BLOCK (IN RELEVANT PART)
public partial class ConnectClass
{
public static a.b.c.Client client = new a.b.c.Client();
public static string DriveLetter;
public static string CurrentDate;
//_____________________
public static void StoreVars(Form1 frm)
{
DriveLetter = frm.textBox4.Text;
CurrentDate = frm.textBox5.Text;
}
public static string Connect(Form1 frm, int Call)
{
string host = "127.0.0.1";
int port = 7496;
int clientId = 0;
string Result = "Connected";
try
{
client.Connect(host, port, clientId);
}
catch (SocketException e)
{
Result = e.ToString();
}
//if (Call == 0)
client.Error += new EventHandler<a.b.c.ErrorEventArgs>(client_ErrorEvents);
return Result;
}
static void client_ErrorEvents(object sender, a.b.c.ErrorEventArgs e)
{
int ErrorCode;
string path = DriveLetter + "/ThisPath/File.txt";
FileStream ThisFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(ThisFile);
DateTime dtNow = DateTime.Now;
ErrorCode = (int)e.ErrorCode;
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.Write(dtNow);
sw.Write(" ");
sw.Write(e.ErrorCode);
sw.Write(" ");
sw.Write(e.ErrorMsg);
sw.Write(sw.NewLine);
sw.Close();
ThisFile.Close();
}
HERE IS SECOND CODE BLOCK (IN RELEVANT PART)
public partial class ConnectClass
{
public static a.b.c.Client client = new a.b.c.Client();
public static string DriveLetter;
public static string CurrentDate;
//_____________________
public static void StoreVars(Form1 frm)
{
DriveLetter = frm.TBx_Drive.Text;
CurrentDate = frm.TBx_Date.Text;
}
public static string Connect(Form1 frm)
{
string host = "127.0.0.1";
int port = 7496;
int clientId = 10;
string Result = "Connected";
try
{
client.Connect(host, port, clientId);
}
catch (SocketException e)
{
Result = e.ToString();
}
client.Error += new EventHandler<a.b.c.ErrorEventArgs>(client_ErrorEvents);
return Result;
}
// THIS IS WHERE THE COMPILER SIGNALS AN ERROR:
static void client_ErrorEvents(object sender, a.b.c.ErrorEventArgs e)
{
string path = DriveLetter + "/ThisPath/File.txt";
FileStream ThisFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(ThisFile);
DateTime dtNow = DateTime.Now;
ErrorCode = (int)e.ErrorCode;
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.Write(dtNow);
sw.Write(" ");
sw.Write(e.ErrorCode);
sw.Write(" ");
sw.Write(e.ErrorMsg);
sw.Write(sw.NewLine);
sw.Close();
ThisFile.Close();
}
Any ideas?
Thanks very much.
You have single class split between 2 files (partial) and both implement the same function.
Either make them non-partial (you'll probably have name conflict on classes), or don't have duplicate methods in the same class.
See details about using partial in Partial Classes and Methods in C# article on MSDN.