Making a connection to IRC through SSL - c#

Could someone please show me an example of how to make an SSL connection to an IRC server?
I have tried reading about SslStreams but I just don't get it. I am able to connect to IRC without SSL using this:
sock.Connect(server, port);
if (!sock.Connected) {
Console.WriteLine("Failed to connect!");
return;
}
input = new System.IO.StreamReader(sock.GetStream());
output = new System.IO.StreamWriter(sock.GetStream());
output.Write("USER " + nick + " 0 * :" + owner + "\r\n" + "NICK " + nick + "\r\n");
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine()) {
//Display received irc message
//Console.WriteLine(buf);
if (buf.Split(' ')[1] == "332") {
Console.WriteLine(buf.Split(new char[] { ' ' }, 5)[4]);
}
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) {
output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush();
}
if (buf[0] != ':') continue;
if (buf.Split(' ')[1] == "001") {
output.Write(
"MODE " + nick + " \r\n" +
"JOIN " + chan + "\r\n"
);
output.Flush();
}
}
}
}

Try this:
conn, err = tls.Dial("tcp", HOST+":"+PORT, &tls.Config{InsecureSkipVerify: true})

Related

MailKit receive emails doesn't show message.Body

I'm receiving emails OK, except that message.TextBody is showing a blank when there is a message present.
message.HtmlBody shows the body text amongst a whole lot of html stuff, obviously, but I'm looking for message.TextBody.
message.TextBody.ToString() shows an error
Object reference not set to an instance of an object
I'm using the following code:
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
client.Connect("pop.gmail.com", 995, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("aaaa#gmail.com", "ssss");
gstrEmailMessages = gstrEmailMessages + client.Count + "\n";
//Fetch emails:
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
gstrEmailMessages = gstrEmailMessages + "Subject: " + message.Subject + "\n";
gstrEmailMessages = gstrEmailMessages + "TextBody: " + message.TextBody + "\n";
gstrEmailMessages = gstrEmailMessages + "HtmlBody: " + message.HtmlBody + "\n";
}
//Disconnect connection:
client.Disconnect(true);
Why does message.TextBody show a blank?
Not all messages will have both an HTML and a plain-text body. In fact, it's possible for some messages to have neither.
In general, though, most messages will have at least 1 of those.

Tcp client in Xamarin.Android

I've created a simple server in raspberry pi 3 running Windows 10 IOT Core with uwp(Universal Windows Platform) with this class>
using System;
using System.Diagnostics;
using System.Text;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace UWP_Server
{
public class StreamSocketManager
{
private StreamSocket ConnectionSocket;
public static bool IsServer { get; set; }
private string ServerPort = "8590";
public void Open()
{
StreamSocketListener DataListener = new StreamSocketListener();
DataListener.ConnectionReceived += ConnectionReceived;
DataListener.BindServiceNameAsync(ServerPort).AsTask().Wait();
}
private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader;
StringBuilder sb;
string receivedData = null;
using (reader = new DataReader(args.Socket.InputStream))
{
sb = new StringBuilder();
reader.InputStreamOptions = InputStreamOptions.Partial;
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
sb.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);
}
reader.DetachStream();
receivedData = sb.ToString();
}
if (receivedData != null)
{
if (IsServer)
{
MainPage.Current.Show("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName);
Debug.WriteLine("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
SentResponse(args.Socket.Information.RemoteAddress, "Hello " + args.Socket.Information.RemoteHostName);
}
else
{
Debug.WriteLine("[CLIENT] I've received " + receivedData + " from "
+ args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
}
}
else
Debug.WriteLine("Received data was empty. Check if you sent data.");
}
public async void SentResponse(HostName address, string message)
{
try
{
Debug.WriteLine("Connecting to " + address + Environment.NewLine);
ConnectionSocket = new StreamSocket();
await ConnectionSocket.ConnectAsync(address, ServerPort);
DataWriter SentResponse_Writer = new DataWriter(ConnectionSocket.OutputStream);
string content = message;
byte[] data = Encoding.UTF8.GetBytes(content);
SentResponse_Writer.WriteBytes(data);
await SentResponse_Writer.StoreAsync();
SentResponse_Writer.DetachStream();
SentResponse_Writer.Dispose();
Debug.WriteLine("Connection has been made and your message " + message + " has been sent." + Environment.NewLine);
ConnectionSocket.Dispose();
ConnectionSocket = new StreamSocket();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to connect ");
ex.Exception("SentResponse");
ConnectionSocket.Dispose();
ConnectionSocket = null;
}
}
}
}
everything seems OK and It's worked in as Server.
I run this code in my Windows 10 mobile (as client) and I can received and send messages between my raspberry pi and windows mobile.
Now I want to send and receive message from my android phone.
I tested a-lot of codes but none of them worked to connect android to raspberry pi.
for android I used this nuget package >
https://github.com/rdavisau/sockets-for-pcl
here is my code:
void Send()
{
var client = new TcpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("Ramtin"), 8590);
try
{
client.Connect(ipEndPoint);
if (client.Connected)
{
Debug.WriteLine("Connected to server" + "\n");
var reader = new StreamReader(client.GetStream());
var writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
WriteLine("Connected: " + client.Connected);
if (client.Connected)
{
writer.WriteLine("HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEy");
}
else
{
Debug.WriteLine("send failed !");
}
}
}
catch (Exception ex)
{
ex.Exception("Send");
}
}
"Ramtin" is my raspberry pi host name.
How can I solve this?
Thanks.
Note: I tried to create android as Server and other phones as clients and it's works fine(sending/receiving message). but I don't want android as a server!

Add pause to Alexa without using SSML

Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.

Pinging using ARP always return host offline

I'm trying to check if computer on the net is online by using code which supposedly to check it by using ARP packets.
I am always getting message that host is offline even when I'm sure that it's online. I have checked on my localhost IP and on some always working IPs such as google.
That could be wrong with this code?
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(IPAddress DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
private byte[] macAddr = new byte[6];
private uint macAddrLen;
private void Ping(IPAddress address)
{
if (SendARP(address, 0, new byte[6], ref macAddrLen) == 0)
{
open++;
txtDisplay.AppendText("Host " + address + " is open." + Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed." + Environment.NewLine);
}
}
By using previous code I'm basically trying to do something like following code. But the problem with this code is that when host is closed that it takes like 2 seconds to get the respond which I want to eliminate. Someone suggested to use ARP ping:
private void Ping(IPAddress address)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
if (cbDontFragment.Checked) options.DontFragment = true;
else options.DontFragment = false;
string dataa = string.Empty;
int dataCounter = 0;
options.Ttl = (int)nudTTL.Value;
for (int i = 0; i < nudData.Value; i++)
{
dataCounter++;
if (dataCounter == 10) dataCounter = 0;
dataa += dataCounter.ToString();
}
byte[] buffer = Encoding.ASCII.GetBytes(dataa);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(address, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
open++;
txtDisplay.AppendText("Host " + address + " is open. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
txtDisplay.SelectedText += Environment.NewLine + ex.Message;
}
}
ARP cannot be used for what you are trying to do. It only works over a local network.
It's purpose is to resolve an IP address (which is routed) to a MAC address (which is not). It is never sent beyond a network segment (a lan)

C# issue with a json string if value is null

I'm using the following code:
if (e.Data.MessageArray[0] == "!streams")
{
try
{
WebClient webclient = new WebClient();
var data = webclient.DownloadString("http://api.justin.tv/api/stream/list.json?channel=dotademon");
JArray ja = JArray.Parse(data);
WebClient webclient2 = new WebClient();
var data2 = webclient2.DownloadString("http://api.justin.tv/api/stream/list.json?channel=trixilulz");
JArray ja2 = JArray.Parse(data2);
WebClient webclient3 = new WebClient();
var data3 = webclient3.DownloadString("http://api.justin.tv/api/stream/list.json?channel=thepremierleague");
JArray ja3 = JArray.Parse(data3);
string streamingString = "Live right now: ";
streamingString += (char)3 + "03EG.Demon" + (char)15 + " - " + "Viewers: " + ja[0]["channel_count"] + " - " + "http://www.justin.tv/dotademon" + (char)3 + "03 Mouz.Trixi" + (char)15 + " - " + "Viewers: " + ja2[0]["channel_count"] + " - " + "http://www.justin.tv/trixilulz" + (char)3 + "03 The Premier League" + (char)15 + " - " + "Viewers: " + ja3[0]["channel_count"] + " - " + "http://www.justin.tv/thepremierleague";
irc.SendMessage(SendType.Message, e.Data.Channel, streamingString);
Console.WriteLine("EG.Demon is " + ja[0]["format"]);
Console.WriteLine("Mouz.Trixi is " + ja[2]["format"]);
Console.WriteLine("The Premier League is " + ja[3]["format"]);
}
catch (ArgumentOutOfRangeException)
{
//catch something
}
}
However, if one of the streams aren't online, then it doesn't output that string at all. Even if 2 are online and 1 is offline and vice versa. However, if they're all online, then it outputs it correctly like:
Live right now: EG.Demon - Viewers: 164 - http://www.justin.tv/dotademon Mouz.Trixi - Viewers: 49 - http://www.justin.tv/trixilulz The Premier League - Viewers: 2992 - http://www.justin.tv/thepremierleague
To demonstrate it with outputting to console, here is that code, it essentially does the same thing as the above code, but sends it to the console, same issue though obviously:
using System;
using System.Net;
using Newtonsoft.Json.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
try
{
WebClient webclient = new WebClient();
var data = webclient.DownloadString("http://api.justin.tv/api/stream/list.json?channel=dotademon");
JArray ja = JArray.Parse(data);
WebClient webclient2 = new WebClient();
var data2 = webclient2.DownloadString("http://api.justin.tv/api/stream/list.json?channel=trixilulz");
JArray ja2 = JArray.Parse(data2);
WebClient webclient3 = new WebClient();
var data3 = webclient3.DownloadString("http://api.justin.tv/api/stream/list.json?channel=thepremierleague");
JArray ja3 = JArray.Parse(data3);
string streamingString = "Live right now: ";
streamingString += (char)3 + "03EG.Demon" + (char)15 + " - " + "Viewers: " + ja[0]["channel_count"] + " - " + "http://www.justin.tv/dotademon" + (char)3 + "03 Mouz.Trixi" + (char)15 + " - " + "Viewers: " + ja2[0]["channel_count"] + " - " + "http://www.justin.tv/trixilulz" + (char)3 + "03 The Premier League" + (char)15 + " - " + "Viewers: " + ja3[0]["channel_count"] + " - " + "http://www.justin.tv/thepremierleague";
Console.WriteLine(streamingString);
}
catch (ArgumentOutOfRangeException)
{
//do something
}
}
}
}
Live right now: EG.Demon - Viewers: 164 - http://www.justin.tv/dotademon Mouz.Trixi - Viewers: 49 - http://www.justin.tv/trixilulz The Premier League - Viewers: 2992 - http://www.justin.tv/thepremierleague
My question is, how can I use this as a string but output it still if it's online and not output the rest if it's offline. When at least one of them are offline, then it doesn't output it at all. It checks if it's online if it finds channel_count in the json, because if it's offline, the json file contains nothing, just []. It's the only approach I know of to check if it's online/offline. I'm using JSON.Net by the way.
You can check ja.Count to see if you got a response.
var sb = new StringBuilder("Live right now: ");
if (ja.Count > 0)
sb.Append(string.Format("EG.Demon - Viewers: {0} - http://www.justin.tv/dotademon", ja[0]["channel_count"]));
if (ja2.Count > 0)
//...
if (ja3.Count > 0)
//...
irc.SendMessage(SendType.Message, e.Data.Channel, sb.ToString());

Categories