C# TwitchBot won't connect to chat - c#

I tried to create a simple twitchBot using Visual Studio C#, but it won't show up in chat. I could connect with mIRC manually without problems.
I don't recieve any error messages, so it's hard for me to pinpoint the problem.
Any ideas are appreciated.
class Program
{
static void Main(string[] args)
{
IrcClient irc = new IrcClient("irc.chat.twitch.tv", 6667, "gruhlumbot", "oauth:g49tpwj1czs200RETAINED");
irc.joinRoom("gruhlumbot");
while(true)
{
string message = irc.readMessage();
if (message.Contains("!test"))
{
irc.sentChatMessage("response");
}
}
}
}
class IrcClient
{
private string userName;
private string channel;
private TcpClient tcpClient;
private StreamReader inputStream;
private StreamWriter outputStream;
public IrcClient(string ip, int port, string userName, string password)
{
this.userName = userName;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.WriteLine("PASS " + password);
outputStream.WriteLine("NICK " + userName);
outputStream.WriteLine("USER " + userName + " 8 * :" + userName);
outputStream.Flush();
}
public void joinRoom(string channel)
{
this.channel = channel;
outputStream.WriteLine("JOIN #" + channel);
outputStream.Flush();
}
public void sentChatMessage(string message)
{
sendIrcMessage(":" + userName + "!" + userName + "#" + userName + ".tmi.twitch.tv PRIVMSG #" + channel + " :" + message);
}
public string readMessage()
{
string message = inputStream.ReadLine();
return message;
}
}

Can you try adding the character "/" before the command join?
As I remember when I was using Irc all commands where using the "/" character before the command.
Something like this.
outputStream.WriteLine("/JOIN #" + channel);
Share with us the results. Thanks.

Related

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!

SSH connection remained open after debug error

So i am making an application which can open connections to remote devices and execute different commands. So yesterday before i left work i was debugging when i got an error. But as my application ignored it and proceeded and having not enough time to fix it immedietly i decided to do it today. When i wanted to make connection with my program again it said it couldn't authenticate (note* the parameters did not change).
So i did some checks to determine the problem, after logging in on the server and running netstat i found out that there was an active connection to port 22, which originated from my application.
Somehow the connection did not show up in my SSH manager until i rebooted it TWICE.
So to prevent things like this in a production environment, how do i prevent things like this.
my Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
my executeCommand class:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand )
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
and my class where i make conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
Note* i have not included my XMLParser class because it is not relevant to the question, nor does it have any connections regarding SSH in general.
EDIT
i found out i had compiled the application and it was running in the commandline. Turns out there is no error with the code

Check for System DSN and create System DSN if NOT Existing (iSeries Access ODBC Driver)

can someone please help me with this?
i need to check through the System DSN for my ODBC connection to the AS400 servier and create a System DSN if a particular one does not exist.
i've tried googling and have not been able to find anything good for me.
btw, i am quite new to programming. any help will be much appreciated.
thank you
After going through the few less complicated examples available online, this is what i managed to come up with (and it works fine for me).
using System;
using System.Runtime.InteropServices;
public class ODBC_Manager
{
[DllImport("ODBCCP32.dll")]
public static extern bool SQLConfigDataSource(IntPtr parent, int request, string driver, string attributes);
[DllImport("ODBCCP32.dll")]
public static extern int SQLGetPrivateProfileString(string lpszSection, string lpszEntry, string lpszDefault, string #RetBuffer, int cbRetBuffer, string lpszFilename);
private const short ODBC_ADD_DSN = 1;
private const short ODBC_CONFIG_DSN = 2;
private const short ODBC_REMOVE_DSN = 3;
private const short ODBC_ADD_SYS_DSN = 4;
private const short ODBC_CONFIG_SYS_DSN = 5;
private const short ODBC_REMOVE_SYS_DSN = 6;
private const int vbAPINull = 0;
public void CreateDSN(string strDSNName)
{
string strDriver;
string strAttributes;
try
{
string strDSN = "";
string _server = //ip address of the server
string _user = //username
string _pass = //password
string _description = //not required. give a description if you want to
strDriver = "iSeries Access ODBC Driver";
strAttributes = "DSN=" + strDSNName + "\0";
strAttributes += "SYSTEM=" + _server + "\0";
strAttributes += "UID=" + _user + "\0";
strAttributes += "PWD=" + _pass + "\0";
strDSN = strDSN + "System = " + _server + "\n";
strDSN = strDSN + "Description = " + _description + "\n";
if (SQLConfigDataSource((IntPtr)vbAPINull, ODBC_ADD_SYS_DSN, strDriver, strAttributes))
{
Console.WriteLine("DSN was created successfully");
}
else
{
Console.WriteLine("DSN creation failed...");
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.ToString());
}
else
{
Console.WriteLine(ex.Message.ToString());
}
}
}
public int CheckForDSN(string strDSNName)
{
int iData;
string strRetBuff = "";
iData = SQLGetPrivateProfileString("ODBC Data Sources", strDSNName, "", strRetBuff, 200, "odbc.ini");
return iData;
}
}
... and then call the methods from your application.
static void Main(string[] args)
{
ODBC_Manager odbc = new ODBC_Manager();
string dsnName = //Name of the DSN connection here
if (odbc.CheckForDSN(dsnName) > 0)
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " already exists on the system");
}
else
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " does not exist on the system");
Console.WriteLine("\n\nPress 'Y' to create the connection?");
string cont = Console.ReadLine();
if (cont == "Y" || cont == "y")
{
odbc.CreateDSN(dsnName);
Environment.Exit(1);
}
else
{
Environment.Exit(1);
}
}
}

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)

Sending/Fowarding Emails with duplicate subject line using WebDav in C#

I have some code that uses the WEBDAV 'SEARCH' method to retrieve emails from an an Exchange Mailboxs 'Inbox' folder - my code takes the the innerXML of the HTTPWebRquests WEBresponse.
Using 'selectingSingleNode' on these namsspaces:
'urn:schemas:httpmail' & urn:schemas:mailheader
Alows me to extract the elements:
f:textdescription
d:fromd:subject
f:datareceived...and so on
I then create a collection of these details in a list and using the 'Subject' along with the URI use the 'PUT' method to recreate these messages in the 'draft's folder before using the 'MOVE' to send the mails (puts them in the sent items using '/##DavMailSubmissionURI##/"' statement.
The problem i have is the nature of the emails i am dealing with tend to come in with the same subject line so it gets confused with which emails have been sent/or not.
Does anyone know of a way around this, I dont know why the 'PUT' relies on the Subject line for the URI to the mail resource rather than say the HREF tag which is unique. Any ideas:
Code is below:
public class EmailReaderWebDav
{
public enum enmHTTPType
{
HTTP,
HTTPS,
}
private String strServer { get; set; } //"mail1" ------ Exchange server name
public String strPassword { get; set; } //"password" ------ Account Domain Password
public String strDomain { get; set; } //"mydocmian" ------ Domain
public String strMailBox { get; set; } //"mymailbox" ------ UserName
public String mailFolder { get; set; } //"inbox" ------ Mail Folder
private String httpProtocol { get; set; } //http:// ? or https://
private String mailboxURI { get; set; } //httpprotocol// + strserver + "/exhange/" + strmailbox
public List<MailStruct > ListOfEmailDetails { get; private set; }
private String strQuerySearch { get; set; }
public EmailReaderWebDav(String serverName, String domain, String mailBox, String password, String mailmailFolder,enmHTTPType HTTPType)
{
strServer = serverName;
strDomain = domain;
strMailBox = mailBox;
strPassword = password;
mailFolder = mailmailFolder;
httpProtocol = (HTTPType == enmHTTPType.HTTPS) ? "https://" : "http://";
mailboxURI = httpProtocol + strServer + "/exchange/" + strMailBox + "/inbox/";
}
public void forwardEmails(List<MailStruct> emailsToSend)
{
emailsToSend.ForEach(x => SendEmail(x,enmHTTPType.HTTP ));
}
public void MakeListofEmailsToForward()
{
String tmpQuery =
"<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" >"
+ "<D:sql>"
+ " SELECT "
+ "\"urn:schemas:mailheader:to\","
+ "\"urn:schemas:mailheader:from\","
+ "\"urn:schemas:mailheader:subject\","
+ "\"urn:schemas:httpmail:datereceived\","
+ "\"urn:schemas:httpmail:textdescription\""
+ " FROM \"" + mailboxURI + "\""
+ " WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
+ "</D:sql>"
+ "</D:searchrequest>";
// Search Request to get emails from target folder.
HttpWebRequest SearchRequest = MakeWebRequest("SEARCH", "text/xml", mailboxURI);
Byte[] bytes = Encoding.UTF8.GetBytes((String)tmpQuery);
SearchRequest.ContentLength = bytes.Length;
Stream SearchRequestStream = SearchRequest.GetRequestStream();
SearchRequestStream.Write(bytes, 0, bytes.Length);
SearchRequestStream.Close();
// get the webresponse from the searchrequest.
WebResponse SearchResponse = MakeWebResponse(SearchRequest);
String EmailsInXML = extractXMLFromWebResponse(SearchResponse);
ListOfEmailDetails = extractMailPropertiesFromXMLString(EmailsInXML);
}
public void SendEmail(MailStruct mailToForward, enmHTTPType HTTPType)
{
String submissionUri = httpProtocol + strServer + "/" + "exchange" + "/" + strMailBox + "/##DavMailSubmissionURI##/";
String draftsUri = httpProtocol + strServer + "/" +"exchange" + "/" + strMailBox + "/Drafts/" + mailToForward.Subject + ".eml";
String message = "To: " + mailToForward.To + "\n"
+ "Subject: " + mailToForward.Subject + "\n"
+ "Date: " + mailToForward.Received
+ "X-Mailer: mailer" + "\n"
+ "MIME-Version: 1.0" + "\n"
+ "Content-Type: text/plain;" + "\n"
+ "Charset = \"iso-8859-1\"" + "\n"
+ "Content-Transfer-Encoding: 7bit" + "\n"
+ "\n" + mailToForward.MailBody;
// Request to put an email the drafts folder.
HttpWebRequest putRequest = MakeWebRequest("PUT", "message/rfc822",draftsUri );
Byte[] bytes = Encoding.UTF8.GetBytes((String)message);
putRequest.Headers.Add("Translate", "f");
putRequest.Timeout = 300000;
putRequest.ContentLength = bytes.Length;
Stream putRequestStream = putRequest.GetRequestStream();
putRequestStream.Write(bytes, 0, bytes.Length);
putRequestStream.Close();
// Put the message in the Drafts folder of the sender's mailbox.
HttpWebResponse putResponse = MakeWebResponse(putRequest);
putResponse.Close();
// Request to move the email from the drafts to the mail submission Uri.
HttpWebRequest moveRequest = MakeWebRequest("MOVE", "text/xml", draftsUri);
moveRequest.Headers.Add("Destination", submissionUri);
// Put the message in the mail submission folder.
HttpWebResponse moveResponse = MakeWebResponse(moveRequest);
moveResponse.Close();
}
private CredentialCache getCredentials(String URI)
{
CredentialCache tmpCreds = new CredentialCache();
tmpCreds.Add(new Uri(URI), "NTLM", new NetworkCredential(strMailBox, strPassword,strDomain ));
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
return tmpCreds;
}
private HttpWebRequest MakeWebRequest(String method,String contentType,String URI)
{
HttpWebRequest tmpWebRequest;
tmpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URI);
tmpWebRequest.Credentials = getCredentials (URI);
tmpWebRequest.Method = method;
tmpWebRequest.ContentType = contentType ;
return tmpWebRequest ;
}
private HttpWebResponse MakeWebResponse(HttpWebRequest webRequest)
{
HttpWebResponse tmpWebresponse = (HttpWebResponse)webRequest.GetResponse();
return tmpWebresponse;
}
WebResponse getMailsFromWebRequest(String strRootURI, String strQuerySearch)
{
HttpWebRequest SEARCHRequest;
WebResponse SEARCHResponse;
CredentialCache MyCredentialCache;
Byte[] bytes = null;
Stream SEARCHRequestStream = null;
try
{
MyCredentialCache = new CredentialCache();
MyCredentialCache.Add(new Uri(strRootURI ), "NTLM", new NetworkCredential(strMailBox.ToLower(), strPassword, strDomain));
SEARCHRequest = (HttpWebRequest)HttpWebRequest.Create(strRootURI );
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
SEARCHRequest.Credentials = MyCredentialCache;
SEARCHRequest.Method = "SEARCH";
SEARCHRequest.ContentType = "text/xml";
bytes = Encoding.UTF8.GetBytes((string)strQuerySearch);
SEARCHRequest.ContentLength = bytes.Length;
SEARCHRequestStream = SEARCHRequest.GetRequestStream();
SEARCHRequestStream.Write(bytes, 0, bytes.Length);
SEARCHResponse =(HttpWebResponse ) SEARCHRequest.GetResponse();
SEARCHRequestStream.Close();
SEARCHRequest.Timeout = 300000;
System.Text.Encoding enc = System.Text.Encoding.Default;
if (SEARCHResponse == null)
{
Console.WriteLine("Response returned NULL!");
}
else
{
Console.WriteLine(SEARCHResponse.ContentLength);
}
return SEARCHResponse;
}
catch (Exception ex)
{
Console.WriteLine("Problem: {0}", ex.Message);
return null;
}
}
private String extractXMLFromWebResponse(WebResponse SearchResponse)
{
String tmpStream;
using(StreamReader strmReader = new StreamReader(SearchResponse.GetResponseStream(), System.Text.Encoding.ASCII))
{
tmpStream = strmReader.ReadToEnd();
strmReader.Close();
}
return tmpStream;
}
private List<MailStruct > extractMailPropertiesFromXMLString(String strXmlStream)
{
List<MailStruct> tmpListOfMailProperties = new List<MailStruct>();
XmlDocument doc = new XmlDocument();
doc.InnerXml = strXmlStream ;
XmlNamespaceManager xmlNameSpaces = new XmlNamespaceManager(doc.NameTable);
xmlNameSpaces.AddNamespace("a", "DAV:");
xmlNameSpaces.AddNamespace("f", "urn:schemas:httpmail:");
xmlNameSpaces.AddNamespace("d", "urn:schemas:mailheader:");
XmlNodeList mailNodes = doc.SelectNodes("//a:propstat[a:status='HTTP/1.1 200 OK']/a:prop", xmlNameSpaces);
foreach (XmlElement node in mailNodes)
{
tmpListOfMailProperties.Add(new MailStruct()
{
MailBody = node.SelectSingleNode("//f:textdescription",xmlNameSpaces ).InnerText ,
from = node.SelectSingleNode ("//d:from",xmlNameSpaces ).InnerText ,
To = "dfoster#liquidcapital.com",
Subject = node.SelectSingleNode("//d:subject",xmlNameSpaces ).InnerText.ToString () ,
Received = node.SelectSingleNode ("//f:datereceived",xmlNameSpaces ).InnerText.ToString ()
}
);
}
return tmpListOfMailProperties;
}
public struct MailStruct
{
public String To { get; set; }
public String from { get; set; }
public String Subject { get; set; }
public String Received { get; set; }
public String MailBody { get; set; }
}
}
}
Using just the subject to identify email is, indeed, not a good way. If I remember it's correct, there are no automatic / obvious email id for exchange / webdav?
If you parse the subject to pick message, I would also pick more information of the email envelope - Like it size, length to create my own id. The best step should be that you create some sort of hash (check Cryptography) out of the whole message body OR i.e. first character of first xx word in the email body (heavier processing though). That will end up in same hash value everytime you call it on same email envelope. Of until the email content is leaved unchanged.
Looks like you're working with Exchange 2003. Be aware that WebDAV is no longer supported in Exchange Version 2010... and with 2007 and newer you can use a WSDL to do everything you need. All you need is an Exchange 2007 CAS to do this.
What I mentioned is a better longer term approach and has less headaches than parsing unsupported WEBDAV XML
To answer your question, there is a property that is unique per message. Use MFCMapi (on codeplex) to look for it. The property will be named "MessageURL" or something like that. Use that property in the URL for your webdav calls.

Categories