Receive Whatsapp Message using WhastApp API 1.2.2 (Nuget) in C# - c#

I use visual studio 2012 and I use whatsap api in my project (downloaded from Nuget), I already develop some code to send whatsapp message to another number,
but I want to know how can i receive message from other numbers?
which event should i use? and how to keep my application always listen to incoming messages.
my code to send is:
static string from = "9********";
static WhatsApp wa = new WhatsApp(from, "*******w=", "Az", false, true);
private void button1_Click(object sender, EventArgs e)
{
try
{
string to = txt_To.Text.Trim();
string msg = txt_Message.Text.Trim();
wa.OnConnectSuccess += () =>
{
MessageBox.Show("Connected Successfully");
wa.OnLoginSuccess += (phoneNumber, data) =>
{
wa.SendMessage(to, msg);
MessageBox.Show("Message Sent ...");
};
wa.OnLoginFailed += (data) =>
{
MessageBox.Show("Login Faild ...");
};
wa.Login();
};
wa.OnConnectFailed += (ex) =>
{
MessageBox.Show("Connected Faild ...");
};
wa.Connect();
wa.Login();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
My application is wondows application
any one can help me?

Related

Connecting to Web Socket

I am new to C# sockets.
I am trying to connect to Web Socket, but I am neither getting connected message nor error message and no Exception.
What I need to do to connect with web socket? How can I trace whether it is trying to connect to socket?
My Code:
private WebSocket client;
const string host = "wss://stream.binance.com:9443";
private void button2_Click(object sender, EventArgs e)
{
client = new WebSocket(host);
client.OnOpen += (ss, ee) =>
MessageBox.Show("Concceted");
client.OnError += (SetStyle, ee) =>
MessageBox.Show("error");
client.Connect();
}
I guess you use WebSocketSharp. The following console test program tries to connect to the same url from your question:
using System;
using WebSocketSharp;
namespace Example
{
public class Program
{
public static void Main(string[] args)
{
using (var ws = new WebSocket("wss://stream.binance.com:9443"))
{
ws.OnMessage += (sender, e) =>
Console.WriteLine("Message received" + e.Data);
ws.OnError += (sender, e) =>
Console.WriteLine("Error: " + e.Message);
ws.Connect();
Console.ReadKey(true);
}
}
}
}
When I run it i get the following console output:
Fatal|WebSocket.doHandshake|Not a WebSocket handshake response.
According to the binance websocket stream documentation you need to change your url to e.g.
wss://stream.binance.com:9443/ws/bnbbtc#ticker
I recommend that you print the content of the error message (in this case e.Message) if possible because it can give you valuable hints to what might be the cause of the error.

BluetoothLE In Universal Windows

Everyone!!!
I am studying BluetoothLE. Can you give me some advice if you can’t help me?
Studying the example source of BluetoothLE in Windows 10 Universal Windows:Character_ValueChanged () does not respond to the Characteristic function. In the example source, the value change is called a function recall, but it does not respond to WinForm.
Please….
private GattCharacteristic registeredCharacteristic;
Hi.
I am studying BluetoothLE. And then I looked at the data and then I saw the blog. Can you give me some advice if you can’t help me?
Studying the example source of BluetoothLE in Windows 10 Universal Windows:Character_ValueChanged () does not respond to the Characteristic function. In the example source, the value change is called a function recall, but it does not respond to WinForm.
Please….
private GattCharacteristic registeredCharacteristic;
.
.
private async void BTN_Change_SubscribeToggle_Click(object sender, EventArgs e)
{
if (!subscribedForNotifications)
{
// initialize status
GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
var cccdValue = GattClientCharacteristicConfigurationDescriptorValue.None;
if (selectedCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
{
cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
}
else if (selectedCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
{
cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
}
Debug.WriteLine("[ cccdValue = {0} ]", cccdValue);
try
{
// BT_Code: Must write the CCCD in order for server to send indications.
// We receive them in the ValueChanged event handler.
status = await selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);
Debug.WriteLine("[ status = {0} ]", status);
if (status == GattCommunicationStatus.Success)
{
AddValueChangedHandler();
Notify_User("Successfully subscribed for value changes", NotifyType.StatusMessage);
}
else
{
Notify_User("Error registering for value changes : " + status.ToString(), NotifyType.ErrorMessage);
}
}
catch (UnauthorizedAccessException ex)
{
// This usually happens when a device reports that it support indicate, but it actually doesn't.
Notify_User(ex.Message, NotifyType.ErrorMessage);
}
} // if(!subscribedForNotifications)
else
{
try
{
// BT_Code: Must write the CCCD in order for server to send notifications.
// We receive them in the ValueChanged event handler.
// Note that this sample configures either Indicate or Notify, but not both.
var result = await
selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.None);
Debug.WriteLine("[ result = {0} ]", result);
if (result == GattCommunicationStatus.Success)
{
subscribedForNotifications = false;
RemoveValueChangedHandler();
Notify_User("Successfully un-registered for notifications", NotifyType.StatusMessage);
}
else
{
Notify_User("Error un-registered for notifications : " + result, NotifyType.ErrorMessage);
}
}
catch (UnauthorizedAccessException ex)
{
Notify_User(ex.Message, NotifyType.ErrorMessage);
}
} // else
}
private void AddValueChangedHandler()
{
Debug.WriteLine("[ AddValueChangedHandler() ]");
Debug.WriteLine("[ subscribedForNotifications = {0} ]", subscribedForNotifications);
BTN_Change_SubscribeToggle.Text = "Unsubscribe from value changes";
if (!subscribedForNotifications)
{
registeredCharacteristic = selectedCharacteristic;
registeredCharacteristic.ValueChanged += Characteristic_ValueChanged;
subscribedForNotifications = true;
CTR_Update_Visible(LB_Value, true);
CTR_Update_Msg(LB_Value, "test");
}
}
private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
// BT_Code: An Indicate or Notify reported that the value has changed.
// Display the new value with a timestamp.
//var reader = DataReader.FromBuffer(args.CharacteristicValue);
Debug.WriteLine("[ Characteristic_ValueChanged ]");
var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat);
var message = string.Format("Value at {0} : \r\n\t {1}", DateTime.Now.ToString("HH:mm:ss.FFF"), newValue);
}
All I could understand is this:
the value change is called a function recall, but it does not respond to WinForm.
To fix it try removing the Async from the button click:
private async void BTN_Change_SubscribeToggle_Click(object sender, EventArgs e)
{

Multithreading in C# giving error with Invoke method

I'm facing a bit of problem, it's giving error "Cross-thread operation not valid" even though I'm using Invoke method.
Here's the code snipit.
Method to update log box
private void updateStatus(String msg)
{
if (logBox.InvokeRequired)
logBox.Invoke((MethodInvoker)delegate()
{
logBox.SelectionStart = logBox.Text.Length;
logBox.Text += "\n";
logBox.Text += msg;
});
else
logBox.SelectionStart = logBox.Text.Length;
logBox.Text += "\n";
logBox.Text += msg;
}
And this Run method is being run by a thread.
private void Run()
{
int port;
try
{
port = Int32.Parse(broadcastPortTextBox.Text);
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message);
return;
}
updateStatus("Starting server at port: " + port.ToString());
server = new HTTPServer.HTTPServer(port);
server.Start();
} //function
It runs fine for the first time but when I click stop, it gives an exception.
private void stopButton_Click(object sender, EventArgs e)
{
updateStatus("Stoping server");
th.Abort();
updateStatus("Server stoped!");
}
I would try using the direct cast for the invoke. There's no need to check whether the invoke is required or not. If you invoke something it should always happen (in your context). Just remove the updateStatus(String msg) method so and try to cast your update like this:
void Run() {
// stuff
broadcastPortTextBox.Invoke(() => {
port = Int32.Parse(broadcastPortTextBox.Text);
});
// stuff..
logBox.Invoke(() => {
logBox.SelectionStart = logBox.Text.Length;
logBox.Text += string.Format("{0}{1}", Environment.NewLine, "Your message text..");
});
// stuff..
}
Note: If you manipulate any non thread owned element use the invoke method. Otherwise you'll end up with exceptions (see 'broadcastPortTextBox');
Edit: Accidently saved before I was done.

Struggling using SignalR in WP8

I have a Windows Phone 8 client.
I am using SignalR to communicate with my server.
I need my UI to update with messages from my server.
I know the server part is correct as I have set break points and have used a HTML5 client.
The issue is with WP8
I have never used WP8 before so I am not sure if I am doing it correctly.
I have this:
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
//not important for now LogIn();
}
});
connection.Received += data =>
{
UpdateConnectionState(data);
};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
My UI initially states a connection has been made.
It is now receiving messages from the Server that I am stuck at. I have also tried this:
private async void UpdateTime(string data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtInfo.Text = data;
});
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
proxy.On<string>("internetUpTime", UpdateTime);
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
}
});
//connection.Received += data =>
//{
// UpdateConnectionState(data);
//};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
Which way is the correct way and what is wrong with my code?
thanks
To handle calls from the server, use the following syntax:
proxy.On<PckType>("broadcastMessage", msg => {});
Where PckType is the type that is the equivalent to the type server sent with the following code:
Clients.Caller.broadcastMessage(pck);
SignalR acts as a RPC service which means methods called from the client must exist on the server and vice versa. Of course, this is only true for the Hub approach.

How to communicate between a c# server (WinRT/Metro) and android client?

I am looking for a way to communicate either over TCP or HTTP between android and C# 2012. Here is what I have so far
JAVA CLIENT:
package com.example.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)this.findViewById(R.id.button1);
tc = (TextView) this.findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Thread th = new Thread(new Runnable() {
public void run() {
connect();
}
});
th.start();
}
});
}
private void connect() {
InetAddress[] server;
try {
server = InetAddress.getAllByName("192.168.1.100");
Socket socket = new Socket(server[0], 3975);
if (socket.isConnected()){
Log.d("connected", "connected");
}
PrintWriter w = null;
BufferedReader r = null;
w = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
w.println("test");
/*String m = null;
while ((m=r.readLine())!= null) {
w.write(m,0,m.length());
w.flush();
}*/
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
C# SERVER:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
public async void ServiceButtonClick(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
try
{
await listener.BindServiceNameAsync("3975");
lblMessage.Text = "We are listening for connections...";
}
catch (Exception ee)
{
lblMessage.Text = "Unable to bind service.. " + ee.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "We are connected to the client";
});
try
{
while (true)
{
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 1";
});
return;
}
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringlength);
if (stringLength != actualStringLength)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 2";
});
return;
}
string temp;
temp = reader.ReadString(actualStringLength);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "Client said - " + reader.ReadString(3);
});
}
}
catch (Exception e)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "ERROR: " + e.Message + " - " + e.Source + " - " + e.StackTrace;
});
}
}
}
Now when I click the button on the client, the socket is connected, but when I send data to the C# server from my phone, nothing shows up on the server. Is there anything I am doing wrong on the receiving or sending end? I am just trying to send basic strings over TCP.

Categories

Resources