Retrieve sent message with EWS Managed API - vb.net

I'm trying to send a message using EWS Managed API, and I need to confirm message was sent and register some info (ex. the date & time it was sent). However, I get an exception as shown below. My question is: how can I retrieve the EmailMessage object for the sent message, after it was sent?
Thank you very much!
Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
Dim em As New EmailMessage(serviceClient.Service)
em.Subject = "Test"
em.Body = "This is a test."
em.ToRecipients.Add("mytestmail#test.com")
em.SendAndSaveCopy(WellKnownFolderName.SentItems)
em.Load() 'Exception: System.InvalidOperationException: This operation can't be performed because this service object doesn't have an Id.
MsgBox(em.DateTimeSent)
End Sub

Apparently, all it takes is to save a draft before sending:
Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
Dim em As New EmailMessage(serviceClient.Service)
em.Subject = "Test"
em.Body = "This is a test."
em.ToRecipients.Add("mytestmail#test.com")
em.Save(WellKnownFolderName.Drafts) '<--- added this
em.SendAndSaveCopy(WellKnownFolderName.SentItems)
em.Load() 'no exception now
MsgBox(em.DateTimeSent)
End Sub

Related

Trigger richtextbox textchanged event until it detects certain text

I am working on serialport that can send and received certain commands. I would like to implement a retry feature which will allow me (the client) to resend data until the device (server) received and send a response to me.
Because of that I created a simple code that can illustrate this kind of function.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.AppendText(Environment.NewLine & "Sample")
End Sub
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Console.WriteLine("Trigger textchanged")
Dim totalLines As Integer = Me.RichTextBox1.Lines.Length
Dim lastLine As String = Me.RichTextBox1.Lines(totalLines - 1)
Dim CSTAT_Check As Boolean = lastLine Like "*Sample*"
If CSTAT_Check = True Then
RichTextBox1.AppendText(Environment.NewLine & "Sample")
End If
End Sub
End Class
The way it works is like this, I will clicked the button to append a sample string to richtextbox then the richtextbox textchange_event will be triggered causing it to resend the sample string to itself and will causes it to trigger another textchange_event and so on and so forth until the device received the sample string which in return the device (server) will send a sample_accepted string to my device (client) and because the textchanged_event doesnt detect the sample string in the last line of richtextbox it will no longer send another sample string to richtextbox.
It's little hard to understand so I will create a simple diagram
Client (Me) Server (Device)
Send sample string Doesn't detected
Send sample string again Doesn't detected again
Send sample string again Doesn't detected again
Send sample string again Doesn't detected again
Send sample string again Detected sample will send sample_accepted
Client Will no longer send sample string because the server detected it already.
The problem in my code is it seems like it doesn't trigger the textchanged_event again after its first trigger.
???If you change a property inside the code that responds to that property being changed, another changed event will not fire.??? You need to manually trigger the textchanged event after you make the changes.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.AppendText(Environment.NewLine & "Sample")
End Sub
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Console.WriteLine("Trigger textchanged")
Dim totalLines As Integer = Me.RichTextBox1.Lines.Length
Dim lastLine As String = Me.RichTextBox1.Lines(totalLines - 1)
Dim CSTAT_Check As Boolean = lastLine Like "*Sample*"
If CSTAT_Check = True Then
RichTextBox1.AppendText(Environment.NewLine & "Sample")
RichTextBox1_TextChanged(sender, New EventArgs())
End If
End Sub
End Class

how to send data to remote device over udp?

i am trying to establish connection between calamp lmu (gps tracking device) and my server.
i am using following code to send and receive data.
i am using timer1 to receive data from device
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(remoteEP)
Dim returnData As String = BitConverter.ToString(receiveBytes)
txtLog.Text &= returnData.ToString & vbCrLf
Dim rep As New IPEndPoint(remoteEP.Address, C_DEVICE_LISTNING_PORT)
sktSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
sktSocket.Connect(remoteEP.Address, 20510)
sktSocket.SendTimeout = 100
'Dim udc As New UdpClient
'udc.Send(sendBytes, sendBytes.Length, rep)
'receivingUdpClient.Client.Send(sendBytes)
Catch ex As Exception
End Try
End Sub
following two variables are class level:
Dim remoteEP As New IPEndPoint(IPAddress.Any, 0)
Dim sktSocket As Socket
i am using following code to send data to device:
Private Sub butSend_Click(sender As Object, e As EventArgs) Handles butSend.Click
Dim sendBytes() As Byte = Encoding.ASCII.GetBytes(txtCommand.Text)
sktSocket.Send(sendBytes)
End Sub
my code to receive data works fine. when device sends data timer1 displays it in a textbox. But when i send data to the ip address returned by receivingUdpClient.Receive, it does not reach to the device. however wireshark shows that data has been sent.
any help will be appriciated.
i solved my problem myself. actually nothing was wrong in the code. actually i was connecting the device using forwarded port. it was hindering inward traffic from device to my system. Assigning static ip direct to my system solved the problem.

Error: "Reference to a non-shared member requires an object reference"

I am building a small app that is pulling script from within an object. I'm down to the portion where my code is pulling back the field from the object that has the script and I'm getting this error.
"reference to a non-shared member requires an object reference"
I'm not sure what to change or how to get around this. Does anyone out there have any suggestions?
Here is the code that i have so far. It's a simple app that has a combobox that you choose the company from and on button click it will get the script and show it in the textbox.
Here is my code:
Imports System.IO
Public Class Form1
Public M3System As MILLSYSTEMLib.System
Public M3Script As MILLCOMPANYLib.CScripting
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'On Error Resume Next
Try
Dim Approved As Integer
' Create a Millennium system obects
M3System = CreateObject("MillSystem.System")
M3System.Load("Millennium")
'run login script
Dim User As Object = M3System.Login()
' See if login worked
If User Is Nothing Then
'MsgBox("Login failed!")
Approved = 0
Else
'MsgBox("Login successful")
'if approved=1 then the user is able to access M3
Approved = 1
End If
'populate combo box
For Each Company In M3System.Companies
cb_COID.Items.Add(Company.Field("co").ToString)
Next
Catch ex As Exception
Me.Close()
End Try
End Sub
Public Sub btn_LoadScript_Click(sender As Object, e As EventArgs) Handles btn_LoadScript.Click
Dim CoCode As String = cb_COID.SelectedItem
Dim script As String = M3Script.vbscript
If IsNothing(cb_COID) Then
MessageBox.Show("Select a Company Code")
End If
For Each CoCode In M3Script.co
tb_Script.Text = script
Next
End Sub
I'm guessing that the line you are failing on is Dim script As String = M3Script.vbscript
If that is the case, it's because you are declaring the M3Script, but you are not creating an instance of it.
Try setting the object somewhere by adding M3Script = new MILLCOMPANYLib.CScripting to your code, or however you would load it (perhaps M3Script = CreateObject("MillSystem.Script")?)

Visual Basic UDPClient Server/Client model?

So I'm trying to make a very simple system to send messages from a client to a server (and later on from server to client as well, but baby steps first). I'm not sure exactly how to use UDPClient to send and receive messages (especially to receive them), mostly because I don't have anything triggering the ReceiveMessage() function and I'm not sure what would.
Source Code is at this link, go to File>Download. It is already built if you want to just run the exe.
So my question is basically: How can I easily use UDPClient, how can I get this system to work and what are some tips for executing this kind of connection? Anything I should watch out for (threading, issues with code,etc)?
Source.
You need first need to set up two UdpClients. One client for listening and the other for sending data. (You'll also need to pick a free/unused port number and know the IP address of your target - the machine you want to send data to.)
To set up the receiver,
Instantiate your UdpClient variable with the port number you chose earlier,
Create a new thread to avoid blocking while receiving data,
Loop over the client's receive method for as long as you want to receive data (the loop's execution should be within the new thread),
When you receive one lot of data (called a "packet") you may need to convert the byte array to something more meaningful,
Create a way to exit the loop when you want to finish receiving data.
To set up the sender,
Instantiate your UdpClient variable with the port number you chose earlier (you may want to enable the ability to send broadcast packets. This allows you to send data to all listeners on your LAN),
When you need to transmit data, convert the data to a byte array and then call Send().
I'd suggest that you have a quick skim read through this.
Here's some code to get you started off...
'''''''''''''''''''''''Set up variables''''''''''''''''''''
Private Const port As Integer = 9653 'Port number to send/recieve data on
Private Const broadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
Private receivingClient As UdpClient 'Client for handling incoming data
Private sendingClient As UdpClient 'Client for sending data
Private receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Private closing As Boolean = False 'Used to close clients if form is closing
''''''''''''''''''''Initialize listening & sending subs'''''''''''''''''
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
InitializeSender() 'Initializes startup of sender client
InitializeReceiver() 'Starts listening for incoming data
End Sub
''''''''''''''''''''Setup sender client'''''''''''''''''
Private Sub InitializeSender()
sendingClient = New UdpClient(broadcastAddress, port)
sendingClient.EnableBroadcast = True
End Sub
'''''''''''''''''''''Setup receiving client'''''''''''''
Private Sub InitializeReceiver()
receivingClient = New UdpClient(port)
Dim start As ThreadStart = New ThreadStart(AddressOf Receiver)
receivingThread = New Thread(start)
receivingThread.IsBackground = True
receivingThread.Start()
End Sub
'''''''''''''''''''Send data if send button is clicked'''''''''''''''''''
Private Sub sendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendBut.Click
Dim toSend As String = tbSend.Text 'tbSend is a textbox, replace it with whatever you want to send as a string
Dim data() As Byte = Encoding.ASCII.GetBytes(toSend)'Convert string to bytes
sendingClient.Send(data, data.Length) 'Send bytes
End Sub
'''''''''''''''''''''Start receiving loop'''''''''''''''''''''''
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port (I personally select 9653)
While (True) 'Setup an infinite loop
Dim data() As Byte 'Buffer for storing incoming bytes
data = receivingClient.Receive(endPoint) 'Receive incoming bytes
Dim message As String = Encoding.ASCII.GetString(data) 'Convert bytes back to string
If closing = True Then 'Exit sub if form is closing
Exit Sub
End If
End While
End Sub
'''''''''''''''''''Close clients if form closes''''''''''''''''''
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
closing = True 'Tells receiving loop to close
receivingClient.Close()
sendingClient.Close()
End Sub
Here are a few other exmples: Here, here, here and here.
Imports System.Threading
Shared client As UdpClient
Shared receivePoint As IPEndPoint
client = New UdpClient(2828) 'Port
receivePoint = New IPEndPoint(New IPAddress(0), 0)
Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))
readThread.Start()
Public Shared Sub WaitForPackets()
While True
Dim data As Byte() = client.Receive(receivePoint)
Console.WriteLine("=" + System.Text.Encoding.ASCII.GetString(data))
End While
End Sub

Issues Sending messages with TCPClient in vb.net

I'm realizing a .NET chat application but i still have that error:
I can send only a message per connection.
For example. With the code below, i can send only one message that can be received correctly by the other peer, but if i send another message message, on the same connection,it won't be received by the remote PC.
Here is the code:
Dim client_TCP As New TcpClient
Private Sub send_obj(ByVal obj As Object)
Dim bf As New BinaryFormatter
Dim tosend As Packet
tosend.data = obj
bf.Serialize(client_TCP.GetStream(), tosend)
client_TCP.GetStream.Flush()
End Sub
Private Sub connect_to_port()
Try
client_TCP = New TcpClient(client_data.getIP(), client_data.getPort())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub disconnect_from_port()
client_TCP.Close()
End Sub
And here is the listener:
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer.Tick
If client_TCP_listener.Pending = True Then
....
End If
End Sub
So, to send a message I always need to do this (example):
Dim b As Byte
b = 1
disconnect_from_port()
connect_to_port()
client_TCP.GetStream().WriteByte(b)
client_TCP.GetStream().Flush()
I tried to put\remove the flush from both the code. Nothing happened.
Have you got any ideas?!
How do you know that it is not received? Did you try emulating remote host with your own code?
TCP is a stream protocol that means that you can send two bytes doing two separate calls to client_TCP.GetStream().WriteByte(b) and the remote party can receive those 2 bytes using one Receive call. You should not make any assumptions on the I/O API call patterns (number of writes and number of receives) but analyze the data you're sending receiving via stream connection.
So to send messages using stream protocol you have to introduce the notion of the application protocol. For instance [2bytes-size][size-bytes of message] - which means that if we want to send "hello" message we at first will send 2 bytes containing the size of the "hello" string and then the string itself.
make sure that receiving end is also using .net BinaryFormatter for deserlizing the object.