here is my FULL code below,Please need help, I have been trying to send email via gmail, I get this error "530-5.5.1 Authentication required", the exception occurs in the method called "Send()" on this line here: (see full code below), I am not using the c# library for some reason, so I need to get this to work, thanks.
//EXCEPTION OCCURS HERE, SEE THE SEND METHOD BELOW FOR FULL CODE
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
}
//CONSTRUCTOR
public Smtp()
{
Port =465 ;
Host = "smtp.gmail.com";
Email = "email#gmail.com";
Password = "xxxxxxx";
to = new List<String>() { "reciever#gmail.com"};
from = "sender#gmail.com";
}
//FULLE CODE
public void Connect()
{
if (Client == null)
Client = new TcpClient();
if (!Client.Connected)
Client.Connect(Host, Port);
//if (IsSecure)
//{
SslStream secureStream =
new SslStream(Client.GetStream());
secureStream.AuthenticateAsClient(Host);
ClientStream = secureStream;
secureStream = null;
Console.WriteLine("secure");
//}
//else
//{
// ClientStream = Client.GetStream();
// Console.WriteLine("non secure");
//}
Writer = new StreamWriter(ClientStream);
Reader = new StreamReader(ClientStream);
string c= ReadLine();
Console.WriteLine(c);
string message = "EHLO me";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
// throw new SmtpException(response);
}
Send();
}
// public void
public void Send()
{
string message = "MAIL FROM:<" + Email + ">";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
string x = ReadLine();
Console.WriteLine(x);
**//EXCEPTION OCCURS HERE**
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
catch (SmtpException e)
{
System.Console.WriteLine("{ 0}", e.Message);
}
}
message = "DATA\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "354")
{
throw new SmtpException(response);
}
message = "Subject: " + subject + "\r\n";
foreach (string address in to)
{
message += "To: " + address + "\r\n";
}
foreach (string address in cc)
{
message += "Cc: " + address + "\r\n";
}
message += "From: " + from + "\r\n";
if (bodyHtml.Length > 0)
{
message += "MIME-Version: 1.0\r\n"
+ " Content-Type: text/ html;\r\n"
+ " charset=\" iso-8859-1\"\r\n";
message += "\r\n" + bodyHtml;
}
else
{
message += "\r\n" + bodyText;
};
message += "\r\n.\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
message = "QUIT\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.IndexOf(" 221") == -1)
{
throw new SmtpException(response);
}
}
public void Close()
{
if (Client != null)
{
if (Client.Connected)
Logout();
Client.Close();
Client = null;
}
if (ClientStream != null)
{
ClientStream.Close();
ClientStream = null;
}
if (Writer != null)
{
Writer.Close();
Writer = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
disposed = true;
}
public void Dispose()
{
if (!disposed)
Close();
}
protected void Login()
{
if (!IsResponseOk(SendCommand("USER " + Email)) ||
!IsResponseOk(SendCommand("PASS " + Password)))
throw new Exception("User/password not accepted");
}
protected void Logout()
{
SendCommand("RSET");
//SendCommand("QUIT");
}
protected string SendCommand(string cmdtext)
{
Writer.WriteLine(cmdtext);
Writer.Flush();
return ReadLine();
}
protected string ReadLine()
{
return Reader.ReadLine() + "\r\n";
}
protected string ReadLines()
{
StringBuilder b = new StringBuilder();
while (true)
{
string temp = ReadLine();
if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
break;
b.Append(temp);
}
return b.ToString();
}
protected static bool IsResponseOk(string response)
{
if (response.StartsWith("+OK"))
return true;
if (response.StartsWith("-ERR"))
return false;
throw new Exception("Cannot understand server response: " +
response);
}
Clearly the SMTP server requires authentication before accepting mail to send. This is commonplace as spammers and scammers used to use 'open relays' to peddle their wares.
Check the rules for the server to see what authentication they will accept. The Wikipedia reference at http://en.wikipedia.org/wiki/SMTP_Authentication might be useful.
Related
I use the following code for reading new messages from Telegram chat:
public async Task GatherChatHistory(string channelName, string ch_id, string mid, int offset = 0, int minId = 0, int maxId = -1, int limit = 100)
{
Log.Info(Tag, "In GatherChatHistory Start");
TelegramClient client = CreateClient();
await InitializeAndAuthenticateClient(client);
int maximal = Convert.ToInt32(mid);
Log.Info(Tag, "In GatherChatHistory Before GetUserDialogAsync");
try
{
var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
var chat = dialogs.chats.lists
.OfType<TLChat>()
.FirstOrDefault(c => c.title == channelName);
Log.Info(Tag, "In GatherChatHistory After GetUserDialogAsync " + (chat != null));
if (chat != null)
{
Log.Info(Tag, "Chat != null, " + channelName);
try
{
var tlAbsMessages =
await client.GetHistoryAsync(
new TLInputPeerChat { chat_id = chat.id }, offset,
minId, maxId, limit);
Log.Info(Tag, "After GetHistoryAsync");
var tlChannelMessages = (TLMessages)tlAbsMessages;
Log.Info(Tag, "GatherChatHistory Messages count = " + (tlChannelMessages.messages.lists.Count - 1));
for (var index = 0; index < tlChannelMessages.messages.lists.Count - 1; index++)
{
var tlAbsMessage = tlChannelMessages.messages.lists[index];
Log.Info(Tag, "Message Type = " + tlAbsMessage.GetType());
if (tlAbsMessage.GetType().ToString().Equals("TeleSharp.TL.TLMessageService"))
continue;
var message = (TLMessage)tlAbsMessage;
if (message.id == maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " maximal was reached");
break;
}
if (message.id <= maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " message.id = " + message.id + " maxid = " + maximal);
continue;
}
if (message.media == null)
{
Log.Info(Tag, "Message ID = " + message.id);
Log.Info(Tag, "Chat ID = " + chat.id);
Log.Info(Tag, "Content = " + message.message);
await AddNewMessageToDatabase(channelName, ch_id, message.message, null, message.from_id.GetValueOrDefault(), message.id);
}
else
{
switch (message.media.GetType().ToString())
{
case "TeleSharp.TL.TLMessageMediaPhoto":
var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.media;
var photo = (TLPhoto)tLMessageMediaPhoto.photo;
var photoSize = photo.sizes.lists.OfType<TLPhotoSize>().Last();
TLFileLocation tf = (TLFileLocation)photoSize.location;
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
using (var ms = new MemoryStream(resFile.bytes))
{
byte[] byteArr = ms.ToArray();
string base64image = Convert.ToBase64String(byteArr);
Log.Info(Tag, "Caption = " + tLMessageMediaPhoto.caption);
Log.Info(Tag, "Base64 Image = " + base64image);
await AddNewMessageToDatabase(channelName, ch_id, tLMessageMediaPhoto.caption, base64image, message.from_id.GetValueOrDefault(), message.id);
}
break;
case "TeleSharp.TL.TLMessageMediaDocument":
var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;
break;
case "TeleSharp.TL.TLMessageMediaWebPage":
var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
string url = string.Empty;
if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
{
var webPage = (TLWebPage)tLMessageMediaWebPage.webpage;
url = webPage.url;
}
break;
}
}
}
}
catch (Exception e)
{
Logger.Error("Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History StackTrace = " + e.ToString());
}
}
else
Log.Info(Tag, "Chat == null");
}
catch (Exception e)
{
Log.Error(Tag, "ReadUserAsync Error : " + e.Message);
}
}
I check chat for new messages one time per minute. I don't have any problems with text messages, all of them I read without any problem. Also I can read one photo, but only one per time. If in chat there are more than one photo or photo and text messages after reading photo TLSharp throws exception:
[MessagingService:TelegramBridge] Telegram Chat History exception: msg_seqno
too low (the server has already received a message with a lower msg_id but
with either a higher or an equal and odd seqno)
[MessagingService:TelegramBridge] Telegram Chat History StackTrace =
System.InvalidOperationException: msg_seqno too low (the server has already
received a message with a lower msg_id but with either a higher or an equal
and odd seqno)
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.HandleBadMsgNotification (System.UInt64
messageId, System.Int32 sequence, System.IO.BinaryReader messageReader)
[0x0009f] in <24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.processMessage (System.UInt64 messageId,
System.Int32 sequence, System.IO.BinaryReader messageReader,
TeleSharp.TL.TLMethod request) [0x00182] in
<24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at TLSharp.Core.Network.MtProtoSender+
<Receive>d__9.MoveNext () [0x000bb] in <24dee86ac15149c89ccf3cac229b439d>:0
Can anybody help me with this problem?
UPD
I localize the place of the error:
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
but I still don't know what to do...
UPD
This is main function:
async Task<int> WriteMessagesFromChannels()
{
Log.Info(Tag, "In WriteMessagesFromChannels");
var url = "http://" + MainActivity.Host + ":" + MainActivity.Port + MainActivity.Url + "/groups?page=1&pageSize=10000";
Log.Info(Tag, "URL = " + url);
var json = FetchServerData(url);
if (json == null)
{
Log.Info(Tag, "In WriteMessagesFromChannels: JSON = NULL");
return -1;
}
var obj = JObject.Parse(json);
var groups = JsonConvert.DeserializeObject<TelegramChannel[]>(obj["data"]["items"].ToString());
Log.Info(Tag, "In WriteMessagesFromChannels: size = " + groups.Length);
if (groups != null)
{
foreach (var gr in groups)
{
Log.Info(Tag, "Group name = " + gr.name + ", monitor = " + gr.monitor);
if (gr.ischannel == true || gr.monitor == false)
continue;
string maxid = ReadMaxId(gr.id);
if (maxid == "")
continue;
Log.Info(Tag, "In WriteMessagesFromChannels: MAXID = " + maxid);
await ReadMessagesFromChat(gr.name, gr.id, maxid);
Thread.Sleep(3000);
}
Log.Info(Tag, "In WriteMesasagesFromChannels: CYCLE IS FINISHED");
}
else
{
Log.Info(Tag, "In WriteMessagesFromChannels: GROUPS = NULL");
}
return 1;
}
async Task<int> ReadMessagesFromChat(string name, string ch_id, string maxid)
{
Log.Info(Tag, "In ReadMessagesFromChat");
//await bridge.GetPhotoFromChannel(name);
await bridge.GatherChatHistory(name, ch_id, maxid);
return 1;
}
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
and
if(closeRequest == true) responseFile.Close();
So now my problem:
If i try to download a file, it does so, closes the response. All good.
However, if I type wrong URL (with 404 returned or smth), I can't close the response because it gives me nullreference error. So I close it only when I get a response.
However, after providing wrong URL and not closing response, further tries to download anything result in timeout (even if URL is correct).
Why is that happening and can I resolve it somehow?
EDIT: Full code of class:
public void DownloadAndReplace(string webFile, string sourceFile)
{
var requestFile = (HttpWebRequest)WebRequest.Create(webFile);
var requestMD5 = (HttpWebRequest)WebRequest.Create(webFile + ".md5");
var requestSHA = (HttpWebRequest)WebRequest.Create(webFile + ".sha");
bool closeRequest = true;
_location = sourceFile + "\\" + OriginalFileName(webFile);
requestFile.Method = "HEAD";
requestFile.Timeout = 2000;
HttpWebResponse responseFile = null;
HttpWebResponse responseMD5 = null;
HttpWebResponse responseSHA = null;
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
if (!File.Exists(_location) || responseFile.LastModified > File.GetLastWriteTime(_location))
{
downloadFile(webFile, _location);
if (_controlsRef.chooseMD5.Checked)
{
try
{
responseMD5 = (HttpWebResponse)requestMD5.GetResponse();
downloadFile(webFile + ".md5", _location);
responseMD5.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".md5");
}
}
else if (_controlsRef.chooseSHA1.Checked)
{
try
{
responseSHA = (HttpWebResponse)requestSHA.GetResponse();
downloadFile(webFile + ".sha", _location);
responseSHA.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".sha");
}
}
}
else MessageBox.Show("Newest version");
if(closeRequest == true) responseFile.Close();
public void downloadFile(string urlAddress, string location)
{
_fileHasher = new HashFile(_controlsRef);
using (var downloadClient = new WebClient())
{
downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = new Uri(urlAddress);
if (location == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
location = location + "\\" + OriginalFileName(urlAddress);
this._location = location;
}
else location = _location;
_downloadStopWatch.Start();
if (File.Exists(location))
{
File.Delete(location);
}
if (_isFile == true)
{
try
{
downloadClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_isFile = false;
}
}
}
}
private string OriginalFileName(string urlAddress)
{
var requestFile = (HttpWebRequest)WebRequest.Create(urlAddress);
requestFile.Method = "HEAD";
HttpWebResponse responseFile = null;
string originalFileName = "";
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exResponse)
{
MessageBox.Show(exResponse.Message);
_isFile = false;
}
if (_isFile == true)
{
int segmentLenght = responseFile.ResponseUri.Segments.Length;
originalFileName = responseFile.ResponseUri.Segments[segmentLenght - 1];
responseFile.Close();
}
return originalFileName;
}
To further clarify:
I provide URL for existing file 1. All is ok.
I provide URL for existing file 2. All is ok.
I provide URL for non-exisitng file 3. It throws me an 404 error.
I provide URL for existing file 4. I get program hangup and timeout.
Wrap your HttpWebResponse inside a using statement so that the object can be disposed correctly.
Something like this:
try
{
using(responseFile = (HttpWebResponse)requestFile.GetResponse())
{
...your code...
}
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
"using" reference: https://msdn.microsoft.com/en-us/library/yh598w02.aspx
I am using visual studio 2010 professional on windows 7 (32 bit) to connect to RFID reader LRU3000 and i encounterd this exception
Method not found: 'IntPtr
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(!!0)
kindly download the sample from the following link.
I searched the web much but i failed to know what is wrong.
Thanks In advance
NotificationSample.zip
and this is the code of the sample
this is the code of the sample :
the exception occurs at the line of code :
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
public partial class NotificationSample : Form,FedmTaskListener
{
FedmIscReader reader;
FedmTaskOption taskOpt;
long count=1;
//declaration from delegatetyp
public delegate void DelegateDisplayRecSets(int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip);
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NotificationSample());
}
//Constructor
public NotificationSample()
{
InitializeComponent();
try
{
reader = new FedmIscReader();
reader.SetTableSize(FedmIscReaderConst.BRM_TABLE, 255); // max 255 tag with each notification
taskOpt = new FedmTaskOption();
}
catch(FedmException ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
//Actualy Time propertie
private string Time
{
get
{
DateTime d;
d = DateTime.Now;
string t;
// Get the Date
if (d.Month.ToString().Trim().Length == 1)
{
t = "0" + d.Month.ToString().Trim() + "/";
}
else
{
t = d.Month.ToString().Trim() + "/";
}
if (d.Day.ToString().Trim().Length == 1)
{
t += "0" + d.Day.ToString().Trim() + "/";
}
else
{
t += d.Day.ToString().Trim() + "/";
}
t += d.Year.ToString().Trim() + " ";
// Get the time
if (d.Hour.ToString().Trim().Length == 1)
{
t += "0" + d.Hour.ToString().Trim() + ":";
}
else
{
t += d.Hour.ToString().Trim() + ":";
}
if (d.Minute.ToString().Trim().Length == 1)
{
t += "0" + d.Minute.ToString().Trim() + ":";
}
else
{
t += d.Minute.ToString().Trim() + ":";
}
if (d.Second.ToString().Trim().Length == 1)
{
t += "0" + d.Second.ToString().Trim() + ".";
}
else
{
t += d.Second.ToString().Trim() + ".";
}
if (d.Millisecond.ToString().Trim().Length == 1)
{
t += "00" + d.Millisecond.ToString().Trim() + ".";
}
else if (d.Millisecond.ToString().Trim().Length == 2)
{
t += "0" + d.Millisecond.ToString().Trim() + ".";
}
else
{
t += d.Millisecond.ToString().Trim() + ".";
}
return t;
}
}
/*****************************Methods from interface FedmTaskListener*******************/
public void OnNewNotification(int iError,string IP,uint PortNr)
{
int i;
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
//declaration from delegateobject
DelegateDisplayRecSets DisplayRecSetMethod = new DelegateDisplayRecSets(DisplayRecSets);
object[] obj = new object[11];
IAsyncResult result;
if(brmItems == null)
{
return;
}
string[] serialnumber = new string[brmItems.Length];
string[] dataBlock = new string[brmItems.Length];
string[] date = new string[brmItems.Length];
string[] time = new string[brmItems.Length];
byte[] type = new byte[brmItems.Length];
byte[] antennaNr = new byte[brmItems.Length];
byte[] input = new byte[brmItems.Length];
byte[] state = new byte[brmItems.Length];
byte[] dbsize = new byte[brmItems.Length];
Dictionary<byte, FedmIscRssiItem>[] dicRSSI = new Dictionary<byte, FedmIscRssiItem>[brmItems.Length];
long dbn;
byte dbadr;
string db;
for (i = 0; i < brmItems.Length; i++)
{ // serial number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_SNR, out serialnumber[i]);
}
// data blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_DBN, out dbn);
brmItems[i].GetData(FedmIscReaderConst.DATA_DB_ADR, out dbadr);
int j;
for (j = dbadr; j < dbn; j++)
{
brmItems[i].GetData(FedmIscReaderConst.DATA_RxDB, j, out db);
dataBlock[i] = dataBlock[i] + db + "\r\n"+"\t\t";
}
}
// Transponder Type
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TRTYPE))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_TRTYPE, out type[i]);
}
// Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
date[i] = brmItems[i].GetReaderTime().GetDate();
}
// Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
time[i] = brmItems[i].GetReaderTime().GetTime();
}
// Antenna number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_ANT_NR, out antennaNr[i]);
}
// RSSI value
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_RSSI))
{
dicRSSI[i] = brmItems[i].GetRSSI();
}
else
{
dicRSSI[i] = new Dictionary<byte, FedmIscRssiItem>();
}
// Input
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_INPUT, out input[i]);
brmItems[i].GetData(FedmIscReaderConst.DATA_STATE, out state[i]);
}
}
obj[0] = brmItems.Length;
obj[1] = type;
obj[2] = serialnumber;
obj[3] = dataBlock;
obj[4] = date;
obj[5] = time;
obj[6] = antennaNr;
obj[7] = dicRSSI;
obj[8] = input;
obj[9] = state;
obj[10] = IP;
result = (IAsyncResult)Invoke(DisplayRecSetMethod, obj);
}
public void OnNewApduResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewQueueResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewSAMResponse(int iError, byte[] responseData)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewReaderDiagnostic(int iError,string IP,uint PortNr)
{
}
public int OnNewMaxAccessEvent(int iError, string maxEvent, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public int OnNewMaxKeepAliveEvent(int iError, uint uiErrorFlags, uint TableSize, uint uiTableLength, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewTag(int iError)
{
}
public void onNewPeopleCounterEvent(uint counter1, uint counter2, uint counter3, uint counter4, string ip, uint portNr, uint busAddress)
{
throw new Exception("The method or operation is not implemented.");
}
/************************************ENDE***********************************************/
/******************************************************Asynchrone method*****************************************************************************************************/
public void DisplayRecSets( int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip)
{
Dictionary<byte, FedmIscRssiItem> RSSIval;
FedmIscRssiItem RSSIitem;
int i;
bool bcheck;
byte antNo;
string dr;
string tr = "";
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
tr += "-----------------------------------------------------------------" + "\r\n";
tr += "DATE/TIME: " + Time.ToString() + "\r\n";
tr += "-----------------------------------------------------------------" + "\r\n";
count = 1;
for (i = 0; i < recSets; i++)
{
tr += (count).ToString().Trim() + "." + " TRANSPONDER" + "\r\n";
count = count + 1;
if (type[i] >= 0)
{
//just the two last bit
dr = "0x" + FeHexConvert.IntegerToHexString(type[i]).Substring(FeHexConvert.IntegerToHexString(type[i]).Length - 2, 2);
tr += "TR-TYPE:" + "\t" + dr.ToString() + "\r\n";
}
// Output SeriaNo.
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
if (serialNumber[i] != null)
{
tr += "SNR:" + "\t\t" + serialNumber[i].ToString() + "\r\n";
}
}
// Output Data Blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
if (dataBlock[i] != null)
{
tr += "DB:" + "\t\t" + dataBlock[i].ToString() + "\r\n";
}
}
// Output Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER) || brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
if (date[i] != null)
{
tr += "DATE:" + "\t\t" + date[i].ToString() + "\r\n";
}
}
// Output Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
if (time[i] != null)
{
tr += "TIME:" + "\t\t" + time[i].ToString() + "\r\n";
}
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output ANT_NR
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
tr += "ANT. NR:"+"\t\t" + (antennaNr[i].ToString()).Trim() + "\r\n";
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output RSSI
if (dicRSSI.Length > 0)
{
if (dicRSSI[i] != null)
{
RSSIval = dicRSSI[i];
for(antNo = 1; antNo<FedmBrmTableItem.TABLE_MAX_ANTENNA; antNo++)
{
bcheck = RSSIval.TryGetValue(antNo, out RSSIitem);
if (!bcheck)
continue;
tr += "RSSI of AntNr. " + "\t" + antNo.ToString() + " is " + "-" + RSSIitem.RSSI.ToString() + "dBm" + "\r\n";
}
}
}
// Output INPUT
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
tr += "INPUT:" + "\t\t" + (input[i].ToString()).Trim() + "\r\n";
tr += "STATE:" + "\t\t" + (state[i].ToString()).Trim() + "\r\n";
}
// Output IP where notification data comes from
tr += "FROM:" + "\t\t" + ip + "\r\n";
tr += "" + "\r\n";
tr += "" + "\r\n";
}
this.textBoxData.AppendText(tr);
tr = "";
}
/**********************************************************ENDE***************************************************************************************************************/
/**************************************************Buttons**********************************************/
private void buttonListen_Click(object sender, EventArgs e)
{
if(this.buttonListen.Text == "Listen")
{
this.buttonListen.Text = "Cancel";
taskOpt.IPPort = Convert.ToInt16(this.textBoxPortNr.Text);
if(this.checkBoxAkn.Checked)
{
taskOpt.NotifyWithAck = 1;
}
else
{
taskOpt.NotifyWithAck = 0;
}
//Start from intern Thread
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
this.buttonListen.Text = "Listen";
//End from intern thread
int val;
reader.ResetTable(FedmIscReaderConst.BRM_TABLE);
val=reader.CancelAsyncTask();
//case Deadlocks ->-4084
if (val < 0)
{
reader.CancelAsyncTask();
}
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
this.textBoxData.Clear();
count = 1;
}
/***********************************************************Ende******************************************/
private void NotificationSample_FormClosing(object sender, FormClosingEventArgs e)
{
reader.CancelAsyncTask();
Application.Exit();
}
}
I am developing wp8 app. My question is that, The app is getting an error when I click on the registration button and the following exception occurred and the code is not going below string post data
An exception of type System.UnauthorizedAccessException occurred in System.Windows.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely continue
namespace docapp
{
public partial class registration : PhoneApplicationPage
{
public static string DeviceIDAsString;
public registration()
{
InitializeComponent();
//selction.Items.Add("india");
//selction.Items.Add("pakistan");
//selction.Items.Add("china");
//selction.Items.Add("USA");
String[] name = { "india", "china", "pakistan" };
String[] uname = { "Delhi", "Bijing", "Karachi" };
String[] university = { "AIIMS", "MDU", "PGI" };
String[] yeardate = { "2011", "2012", "2013" };
string[] question = { "what is your pet name", "what is your childhood name", "what is your mother name" };
this.country.ItemsSource = name;
this.city.ItemsSource = uname;
this.university.ItemsSource = university;
this.year.ItemsSource = yeardate;
this.question.ItemsSource = question;
}
private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (txtusername.Text == "")
{
MessageBox.Show("enter the name");
}
else if (txtid.Text == "")
{
MessageBox.Show("enter valid id");
}
else if (txtpassword.Password == "")
{
MessageBox.Show("enter the password");
}
else if (txtconfirm.Password == "")
{
MessageBox.Show("enter the same password again ");
}
else if (txtemail.Text == "")
{
MessageBox.Show("enter the valid email id ");
}
else if (txtmobileno.Text == "")
{
MessageBox.Show("enter the valid 10 digit mobile no ");
}
if (txtpassword.Password != txtconfirm.Password)
{
MessageBox.Show("password doesnot match please enter same password");
}
SendPost();
//getDeviceId();
}
//private static String getDeviceId()
//{
// //byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
// //return BitConverter.ToString(id).Replace("-", string.Empty);
// // get the unique device id for the publisher per device
//}
void SendPost()
{
byte[] myDeviceID = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
DeviceIDAsString = Convert.ToBase64String(myDeviceID);
Uri url = new Uri(" http://www.mobileoid2.co/docbase/index.php?methodname=createuser");
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Headers["username"] = txtusername.Text;
webRequest.Headers["userid"] = txtid.Text;
webRequest.Headers["password"] = txtpassword.Password;
webRequest.Headers["confirmpaswword"] = txtconfirm.Password;
webRequest.Headers["email"] = txtemail.Text;
webRequest.Headers["mobileno"] = txtmobileno.Text;
webRequest.Headers["country"] = country.SelectedItem.ToString();
webRequest.Headers["city"] = city.SelectedItem.ToString();
webRequest.Headers["university"] = university.SelectedItem.ToString();
webRequest.Headers["year"] = year.SelectedItem.ToString();
webRequest.Headers["question"] = question.SelectedItem.ToString();
webRequest.Headers["uniqueid"] = DeviceIDAsString;
webRequest.ContentType = "application/json;charset=utf-8";
//"text/json";//
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "username" + txtusername.Text + ".userid" + txtid.Text + "." + ".password" + txtpassword.Password + "." + ".confirmpassword" + txtconfirm.Password + "." + ".email" + txtemail.Text + "." + ".mobileno" + txtmobileno.Text + "." + "." + ".country" + country.SelectedItem.ToString() + "." + "." + ".city" + city.SelectedItem.ToString() + "." + "." + ".university" + university.SelectedItem.ToString() + "." + "." + ".year" + year.SelectedItem.ToString() + "." + ".question" + question.SelectedItem.ToString() + "." + ".uniqueid" + DeviceIDAsString +".";
var input = JsonConvert.SerializeObject(postData);
byte[] byteArray = Encoding.UTF8.GetBytes(input);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
//outputbox.Text = Response.ToString();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/docapp;component/login.xaml", UriKind.RelativeOrAbsolute));
}
}
}
Not sure why, but this error is generally thrown when the access is not allowed. Maybe the credentials you are trying to use are not allowed!
The issue is that the OS is denying the request due to I/O error, where the credentials are required, or you either don't have permission to read/write there, or the server needs a username/password match to allow you. Something like that. Try catching it using
try {
// code here to try..
} catch (System.UnauthorizedAccessException e) {
// error e.Message
}
Here is a Remark from the MSDN blog post:
An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property.
For More: http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception(v=vs.110).aspx
Hi i am new to programing and cant see what is wrong with this code
i have a textbox that i will add a host name to and then the S1 string will be add and then pinged all i want the code to do is to list what is the correct host name so if i enter the name Computer in the text box it will ping the following
ComputerDT
ComputerLT
computerTB
computerR0
only one will have the correct host name and i want to list it in list box one its all working fine apart from the last if statement
if (host1 != "")
listBox1.Items.Add(host1);
and i get host1 not in local context i cant see why this is wrong
can anyone help please
public partial class Form1 : Form
{
public string S1 = "DT";
public string S2 = "LT";
public string S3 = "R0";
public string S4 = "TB";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
update();
}
static string Ping(string host)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
string errMessage = string.Empty;
string returnMessage;
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(host, timeout, buffer, options);
if (!(reply == null))
{
switch (reply.Status)
{
case IPStatus.Success:
returnMessage = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
break;
case IPStatus.TimedOut:
returnMessage = "Connection has timed out...";
break;
default:
returnMessage = string.Format("Ping failed: {0}", reply.Status.ToString());
break;
}
}
else
returnMessage = "Connection failed for an unknown reason...";
}
catch (PingException ex)
{
returnMessage = string.Format("");
}
catch (SocketException ex)
{
returnMessage = string.Format("");
}
return returnMessage;
}
public void update()
{
string[] lines = textBox1.Lines;
List<string> myCollection = new List<string>();
string host1;
foreach (string line in lines)
{
if (line.Contains(""))
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
}
myCollection.ToArray();
{
foreach (string val in myCollection)
host1 = Ping(val);
if (host1 != "")
listBox1.Items.Add(host1);
}
}
}
}
avoid using the following constructs
if(condition)
expression;
foreach(condition)
expression;
instead always use braces - you will then spot the problem
You need to wrap your foreach loop in braces:
foreach (string val in myCollection)
{
host1 = Ping(val);
if (host1 != "")
listBox1.Items.Add(host1);
}
otherwise is will only loop the first line. (which is why host1 is no longer in scope)
the if statement above it looks iffy {chuckle} as well:
if (line.Contains(""))
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
should be
if (line.Contains("")) // this will always be true. Need to use a proper check here
{
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
}