I want to make call with sip using Ozeki library.
But this library throws me state excepton.
I use asteriks telephony in the server.
My code is below:
class Program
{
static ISoftPhone softphone; // softphone object
static IPhoneLine phoneLine; // phoneline object
static IPhoneCall call;
static Microphone microphone;
static Speaker speaker;
static MediaConnector connector;
static PhoneCallAudioSender mediaSender;
static PhoneCallAudioReceiver mediaReceiver;
public static void Main(string[] args)
{
// Create a softphone object with RTP port range 5000-10000
softphone = SoftPhoneFactory.CreateSoftPhone(1, 10000);
// SIP account registration data, (supplied by your VoIP service provider)
var registrationRequired = true;
var userName = "111";
var displayName = "111";
var authenticationId = "111";
var registerPassword = "pin111";
var domainHost = "localhost";
var domainPort = 5038;
var account = new SIPAccount(registrationRequired, displayName, userName, authenticationId, registerPassword, domainHost, domainPort);
// Send SIP regitration request
RegisterAccount(account);
microphone = Microphone.GetDefaultDevice();
speaker = Speaker.GetDefaultDevice();
mediaSender = new PhoneCallAudioSender();
mediaReceiver = new PhoneCallAudioReceiver();
connector = new MediaConnector();
// Prevents the termination of the application
Console.WriteLine("\nDone");
Console.ReadLine();
}
static void RegisterAccount(SIPAccount account)
{
try
{
phoneLine = softphone.CreatePhoneLine(account);
phoneLine.RegistrationStateChanged += line_RegStateChanged;
softphone.RegisterPhoneLine(phoneLine);
}
catch (Exception ex)
{
Console.WriteLine("Error during SIP registration: " + ex);
}
}
static void line_RegStateChanged(object sender, RegistrationStateChangedArgs e)
{
if (e.State == RegState.NotRegistered || e.State == RegState.Error)
Console.WriteLine("Registration failed!");
if (e.State == RegState.RegistrationSucceeded)
{
Console.WriteLine("Registration succeeded - Online!");
CreateCall();
}
}
private static void CreateCall()
{
var numberToDial = "00994122000020";
call = softphone.CreateCallObject(phoneLine, numberToDial);
call.CallStateChanged += call_CallStateChanged;
call.Start();
}
private static void SetupDevices()
{
connector.Connect(microphone, mediaSender);
connector.Connect(mediaReceiver, speaker);
mediaSender.AttachToCall(call);
mediaReceiver.AttachToCall(call);
microphone.Start();
speaker.Start();
}
static void call_CallStateChanged(object sender, CallStateChangedArgs e)
{
Console.WriteLine("Call state: {0}.", e.State);
if (e.State == CallState.Answered)
SetupDevices();
}
}
This code show me this error message:
Registration succeeded - Online!
Call state: Setup.
Call state: Error.
What is the problem? What must I chane for working this code?
P.S Please, If you know the better library for making call with asteriks you can tell me.
Related
I'm working on a Project (Console-Application .NET Framework 4.7.2 c#) to find nearby BLE devices and it's working well, the device(The device is just an Arduino with a BLE shield.) is discovered and i was able to read values from it. so the problem is that i wanted to do the same but on another PC (Same Code, Conditions, everything the same). it showed me that the pc is with the device connected but unreachable here on this place of the code :
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
So i tried again and again on 3 different PCs and Laptops but it didn't work.
On the pc first i got connected to, it works well without problems. Can someone pls help me and say what is the matter. Here is my Code:
namespace QuickBlueToothLE
{
class Program
{
static public readonly Dictionary<string, DeviceInformation> mDiscoveredDevices = new Dictionary<string, DeviceInformation>();
static DeviceInformation device = null;
public static string HEG_Service_ID = "00001826-0000-1000-8000-00805f9b34fb";
public static DeviceWatcher deviceWatcher = null;
// Abfrage nach zusätzlichen Eigenschaften, die zurückgegeben werden sollen
public static string[] requestedProperties =
{
"System.Devices.Aep.DeviceAddress",
"System.Devices.Aep.IsConnected",
"System.Devices.Aep.Bluetooth.Le.IsConnectable"
};
static async Task Main(string[] args)
{
deviceWatcher = DeviceInformation.CreateWatcher
(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompletedAsync;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
while (true)
{
if (device == null)
Thread.Sleep(2000);
else
{
Console.WriteLine("Press Any Key to connect to HEG-900725");
Console.ReadKey();
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
Console.WriteLine("Attempting to connect with device");
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
var services = result.Services;
if (result.Status == GattCommunicationStatus.Success)
{
Console.WriteLine("Connection succeeded" + " "+ bluetoothLeDevice.DeviceInformation.Pairing.IsPaired);
Console.WriteLine(device.Id);
foreach (var service in services)
{
if (service.Uuid.ToString() == HEG_Service_ID)
{
Console.WriteLine("Found Heg Service");
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
Console.WriteLine("---------------");
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
Console.WriteLine("CharactesticHandle:"+characteristic.AttributeHandle +"\r\n"+"UUID"+characteristic.Uuid);
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
Console.WriteLine("Notify poroperty found");
GattCommunicationStatus status =
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += Characteristic_ValueChanged;
// Server has been informed of clients interest.
}
}
}
}
}
}
}
Console.WriteLine("Press Any Key to Exit application");
Console.WriteLine("\r\n" + "Values" + "\r\n");
Console.ReadKey();
foreach (var service in services)
{
service.Dispose();
}
bluetoothLeDevice.Dispose();
bluetoothLeDevice = null;
device = null;
Console.WriteLine(mDiscoveredDevices);
Console.WriteLine(mDiscoveredDevices.Count());
break;
}
}
Console.ReadKey();
deviceWatcher.Stop();
deviceWatcher = null;
}
private static void TXCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
byte[] buffer = args.CharacteristicValue.ToArray();
}
private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
var reader = DataReader.FromBuffer(args.CharacteristicValue);
var flags = reader.ReadByte();
var value = reader.ReadByte();
Console.WriteLine($"{flags} - {value}");
}
private static void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_EnumerationCompletedAsync(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
}
private static void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
//throw new NotImplementedException();
}
private static void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Console.WriteLine(args.Name);
if (args.Name == "HEG_100053" || args.Name =="Arduino")
{
Console.WriteLine("Found: " + args.Name);
device = args;
bool keyExists = mDiscoveredDevices.ContainsKey(device.Id);
if (!keyExists)
{
mDiscoveredDevices.Add(device.Id, device);
}
}
}
//900725
//|| args.Name == "HEG_100053"
}
}
I have a C# Class Library, that reads Bluetooth LE Characteristics. I want to use this DLL to get the read values in my VB6 app.
My Problem is: I need the complete code to get the result. That means i have to call the main function from my VB6 program, but i have no idea what parameters i have to use and how i can get the right return value.
My Dll:
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;
using System.Runtime.InteropServices;
namespace BleSirLo
{
public class Program
{
public byte[] ret = new byte[6];
static void Main(string[] args)
{
Task t = MainAsync(args);
t.Wait();
// or, if you want to avoid exceptions being wrapped into AggregateException:
// MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
Program p = new Program();
p.StartBleDeviceWatcher();
}
private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();
private List<DeviceInformation> _knownDevices = new List<DeviceInformation>();
private IReadOnlyList<GattCharacteristic> characteristics;
private IReadOnlyList<GattDeviceService> services;
private GattDeviceService currentSelectedService = null;
private GattCharacteristic currentSelectedCharacteristic = null;
private DeviceWatcher deviceWatcher;
public bool done = false;
private void StartBleDeviceWatcher()
{
// Additional properties we would like about the device.
// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
// BT_Code: Example showing paired and non-paired in a single query.
string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
DeviceInformation.CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start over with an empty collection.
_knownDevices.Clear();
//deviceWatcher.Stop();
deviceWatcher.Start();
while(true)
if (done == true)
break;
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
//Debug.WriteLine(String.Format("Device Found!" + Environment.NewLine + "ID:{0}" + Environment.NewLine + "Name:{1}", deviceInfo.Id, deviceInfo.Name));
//notify user for every device that is found
if (sender == deviceWatcher)
{
if ((deviceInfo.Name == "Ei Gude, wie?") || (deviceInfo.Name == "Ei Gude, Wie?"))
{
sender.Stop();
ConnectDevice(deviceInfo);
}
}
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfo)
{
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfo)
{
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
}
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
}
//trigger StartBleDeviceWatcher() to start bluetoothLe Operation
private void Scan()
{
//empty devices list
_knownDevices.Clear();
UnknownDevices.Clear();
//finally, start scanning
StartBleDeviceWatcher();
}
private async void ConnectDevice(DeviceInformation deviceInfo)
{
//get bluetooth device information
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
//Respond(bluetoothLeDevice.ConnectionStatus.ToString());
//get its services
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
//verify if getting success
if (result.Status == GattCommunicationStatus.Success)
{
//store device services to list
services = result.Services;
//loop each services in list
foreach (var serv in services)
{
//get serviceName by converting the service UUID
string ServiceName = Utilities.ConvertUuidToShortId(serv.Uuid).ToString();
//if current servicename matches the input service name
if (ServiceName == "65520") //ServiceTxtBox.Text)
{
//store the current service
currentSelectedService = serv;
//get the current service characteristics
GattCharacteristicsResult resultCharacterics = await serv.GetCharacteristicsAsync();
//verify if getting characteristics is success
if (resultCharacterics.Status == GattCommunicationStatus.Success)
{
//store device services to list
characteristics = resultCharacterics.Characteristics;
//loop through its characteristics
foreach (var chara in characteristics)
{
//get CharacteristicName by converting the current characteristic UUID
string CharacteristicName = Utilities.ConvertUuidToShortId(chara.Uuid).ToString();
//if current CharacteristicName matches the input characteristic name
if (CharacteristicName == "65524")//CharacteristicsTxtBox.Text)
{
//store the current characteristic
currentSelectedCharacteristic = chara;
//stop method execution
readBuffer();
return;
}
}
}
}
}
}
}
//function that handles the read button event
private async void readBuffer()
{
{
if (currentSelectedService != null && currentSelectedCharacteristic != null)
{
GattCharacteristicProperties properties = currentSelectedCharacteristic.CharacteristicProperties;
//if selected characteristics has read property
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
//read value asynchronously
GattReadResult result = await currentSelectedCharacteristic.ReadValueAsync();
if (result.Status == GattCommunicationStatus.Success)
{
int a, b, c, d, e, f;
var reader = DataReader.FromBuffer(result.Value);
//byte [] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(ret);
a = ret[0];
b = ret[1];
c = ret[2];
d = ret[3];
e = ret[4];
f = ret[5];
Ret_val(ret);
}
}
}
}
}
private void Response_TextChanged(object sender, EventArgs e)
{
}
}
In my VB6 program I call the Library like this: (It is obviously not working, but i dont know how i should do it.
Dim WithEvents CSharpInteropServiceEvents As CSharpInteropService.LibraryInvoke
Dim load As New LibraryInvokeparam(0) = Me.hwnd
Dim sa as variant
Set CSharpInteropServiceEvents = load
sa = load.GenericInvoke("C:\Program Files (x86)\Microsoft Visual Studio\VB98\WINCOM\BleSirLo.dll", "BleSirLo.Program", "Main", param)
I trying to write a Console Application which will establish a connection to a mailbox using EWS and then print a line every time a new email is received.
The end result once I have this working is to turn this into a service, and have a task created every time an email arrives in a certain mailbox, but for now I cant get the Console to write a line upon receipt.
Console Application Project
Program.cs
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd");
service.Credentials = wbcred;
service.AutodiscoverUrl("myemailaddress#mydomain.com", RedirectionUrlValidationCallback);
EWSConnection.SetStreamingNotifications(service);
}
internal static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
//The default for the validation callback is to reject the URL
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
Class Library Project
EWSConnection.cs
public static void SetStreamingNotifications(ExchangeService service)
{
StreamingSubscription subscription;
// Subscribe to streaming notifications in the Inbox.
subscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail);
// Create a streaming connection to the service object, over which events are returned to the client.
// Keep the streaming connection open for 30 minutes.
StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30);
connection.AddSubscription(subscription);
connection.OnNotificationEvent += OnEvent;
connection.OnDisconnect += OnDisconnect;
connection.Open();
bool status = connection.IsOpen;
Console.WriteLine($"Connection Open:{status}");
}
I can add the OnEvent and OnDisconnect methods if required. What's happening is the console prints
Connection Open:True Press any key to continue . . .
Then, when I send an email to that mailbox nothing happens, no break points are triggered and nothing is output to the console, which is what those two methods do.
Why is my OnEvent method not firing?
Edit - OnEvent & OnDisconnect methods
public static void OnEvent(object sender, NotificationEventArgs args)
{
StreamingSubscription subscription = args.Subscription;
// Loop through all item-related events.
foreach (NotificationEvent notification in args.Events)
{
switch (notification.EventType)
{
case EventType.NewMail:
Console.WriteLine("\n————-Mail created:————-");
break;
case EventType.Created:
Console.WriteLine("\n————-Item or folder created:————-");
break;
case EventType.Deleted:
Console.WriteLine("\n————-Item or folder deleted:————-");
break;
}
// Display the notification identifier.
if (notification is ItemEvent)
{
// The NotificationEvent for an e-mail message is an ItemEvent.
ItemEvent itemEvent = (ItemEvent)notification;
Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);
}
else
{
// The NotificationEvent for a folder is an FolderEvent.
FolderEvent folderEvent = (FolderEvent)notification;
Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
}
}
}
and
public static void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
// Cast the sender as a StreamingSubscriptionConnection object.
StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
// Ask the user if they want to reconnect or close the subscription.
ConsoleKeyInfo cki;
Console.WriteLine("The connection to the subscription is disconnected.");
Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
while (true)
{
cki = Console.ReadKey(true);
{
if (cki.Key == ConsoleKey.Y)
{
connection.Open();
Console.WriteLine("Connection open.");
break;
}
else if (cki.Key == ConsoleKey.N)
{
// The ReadKey in the Main() consumes the E.
Console.WriteLine("\n\nPress E to exit");
break;
}
}
}
}
Annoyingly, I was missing the Console.ReadKey() method. It worked as expected once I added this...
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd","myDomain");
service.Credentials = wbcred;
service.AutodiscoverUrl("myemailaddress#mydomain.com", RedirectionUrlValidationCallback);
EWSConnection.SetStreamingNotifications(service);
Console.ReadKey(); //<-- this was missing
}
Bind the methods to the current subscription as this
connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
Here's a example
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.
I've just downloaded the MSNP-Sharp library with the aim of creating my own messaging client, however I am struggling to get the example to sign in. The code all compiles and runs, but when I provide my login details and select "Login" I almost immediately get the following SocketException:
"No connection could be made because the target machine actively refused it 64.4.9.254:1863"
I've stepped through the code and it's the messenger.Connect() function that is causing this, somewhat obviously. When I run the example I only change the login and password details. I am running Windows 7 x86 with the latest version of Windows Live Messenger.
I have tried disabling my antivirus, even going as far as to temporarily uninstall it in case that was the error.
I have also tried disabling Windows Firewall, with no luck.
Firstly, use the stable version of MSNPSharp (that is, 3.0). Since it is a SocketException, this may relate to a problem within the internet protocol (a firewall for instance). Try to ensure that nothing is blocking the program from accessing to the MSN protocol. Since you have said you have disabled your Windows Firewall, could there be anything else that could be blocking it?
Secondly, have you tried using MSN Messenger Live for a test. If that works, MSNPSharp client should probably work too. Ensure you have .NET Framework 2.0 or within their version of the .NET Framework. If it constantly appears to be a problem, I don't believe this is a problem from the MSNPSharp client (I'm not sure however).
here is a demo,i hope it would be useful
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Color;
namespace MSNRobot
{
using MSNPSharp;
using MSNPSharp.Core;
using MSNPSharp.DataTransfer;
class RobotConversation
{
private Conversation _conversation = null;
private RobotMain _robotmain = null;
public RobotConversation(Conversation conv, RobotMain robotmain)
{
Console.WriteLine("==> Struct a conversation");
_conversation = conv;
_conversation.Switchboard.TextMessageReceived += new EventHandler<TextMessageEventArgs>(Switchboard_TextMessageReceived);
_conversation.Switchboard.SessionClosed += new EventHandler<EventArgs>(Switchboard_SessionClosed);
_conversation.Switchboard.ContactLeft += new EventHandler<ContactEventArgs>(Switchboard_ContactLeft);
_robotmain = robotmain;
}
//online status
private void Switchboard_TextMessageReceived(object sender, TextMessageEventArgs e)
{
Console.WriteLine("==>Received Msg From " + e.Sender.Mail + " Content:\n" + e.Message.Text);
//echo back ///////////// TODO /////////////////
_conversation.Switchboard.SendTextMessage(e.Message);
}
private void Switchboard_SessionClosed(object sender, EventArgs e)
{
Console.WriteLine("==>Session Closed, Remove conversation");
_conversation.Switchboard.Close();
_conversation = null;
_robotmain.RobotConvlist.Remove(this);
}
private void Switchboard_ContactLeft(object sender, ContactEventArgs e)
{
Console.WriteLine("==>Contact Left.");
}
}
class RobotMain
{
private Messenger messenger = new Messenger();
private List<RobotConversation> _convs = new List<RobotConversation>(0);
public RobotMain()
{
messenger.NameserverProcessor.ConnectionEstablished += new EventHandler<EventArgs>(NameserverProcessor_ConnectionEstablished);
messenger.Nameserver.SignedIn += new EventHandler<EventArgs>(Nameserver_SignedIn);
messenger.Nameserver.SignedOff += new EventHandler<SignedOffEventArgs>(Nameserver_SignedOff);
messenger.NameserverProcessor.ConnectingException += new EventHandler<ExceptionEventArgs>(NameserverProcessor_ConnectingException);
messenger.Nameserver.ExceptionOccurred += new EventHandler<ExceptionEventArgs>(Nameserver_ExceptionOccurred);
messenger.Nameserver.AuthenticationError += new EventHandler<ExceptionEventArgs>(Nameserver_AuthenticationError);
messenger.Nameserver.ServerErrorReceived += new EventHandler<MSNErrorEventArgs>(Nameserver_ServerErrorReceived);
messenger.Nameserver.ContactService.ReverseAdded += new EventHandler<ContactEventArgs>(Nameserver_ReverseAdded);
messenger.ConversationCreated += new EventHandler<ConversationCreatedEventArgs>(messenger_ConversationCreated);
messenger.Nameserver.OIMService.OIMReceived += new EventHandler<OIMReceivedEventArgs>(Nameserver_OIMReceived);
messenger.Nameserver.OIMService.OIMSendCompleted += new EventHandler<OIMSendCompletedEventArgs>(OIMService_OIMSendCompleted);
}
public List<RobotConversation> RobotConvlist
{
get
{
return _convs;
}
}
private void NameserverProcessor_ConnectionEstablished(object sender, EventArgs e)
{
//messenger.Nameserver.AutoSynchronize = true;
Console.WriteLine("==>Connection established!");
}
private void Nameserver_SignedIn(object sender, EventArgs e)
{
messenger.Owner.Status = PresenceStatus.Online;
Console.WriteLine("==>Signed into the messenger network as " + messenger.Owner.Name);
}
private void Nameserver_SignedOff(object sender, SignedOffEventArgs e)
{
Console.WriteLine("==>Signed off from the messenger network");
}
private void NameserverProcessor_ConnectingException(object sender, ExceptionEventArgs e)
{
//MessageBox.Show(e.Exception.ToString(), "Connecting exception");
Console.WriteLine("==>Connecting failed");
}
private void Nameserver_ExceptionOccurred(object sender, ExceptionEventArgs e)
{
// ignore the unauthorized exception, since we're handling that error in another method.
if (e.Exception is UnauthorizedException)
return;
Console.WriteLine("==>Nameserver exception:" + e.Exception.ToString());
}
private void Nameserver_AuthenticationError(object sender, ExceptionEventArgs e)
{
Console.WriteLine("==>Authentication failed:" + e.Exception.InnerException.Message);
}
private void Nameserver_ServerErrorReceived(object sender, MSNErrorEventArgs e)
{
// when the MSN server sends an error code we want to be notified.
Console.WriteLine("==>Server error received:" + e.MSNError.ToString());
}
void Nameserver_ReverseAdded(object sender, ContactEventArgs e)
{
//Contact contact = e.Contact;
//contact.OnAllowedList = true;
//contact.OnPendingList = false;
//messenger.Nameserver.ContactService.AddNewContact(contact.Mail);
Console.WriteLine("==>ReverseAdded contact mail:" + e.Contact.Mail);
//messenger.Nameserver.AddNewContact(
e.Contact.OnAllowedList = true;
e.Contact.OnForwardList = true;
}
private void messenger_ConversationCreated(object sender, ConversationCreatedEventArgs e)
{
Console.WriteLine("==>Conversation created");
_convs.Add(new RobotConversation(e.Conversation, this));
}
//offline status
void Nameserver_OIMReceived(object sender, OIMReceivedEventArgs e)
{
Console.WriteLine("==>OIM received at : " + e.ReceivedTime + " From : " +
e.NickName + " (" + e.Email + ") " + e.Message);
TextMessage message = new TextMessage(e.Message);
message.Font = "Trebuchet MS";
//message.Color = Color.Brown;
message.Decorations = TextDecorations.Bold;
Console.WriteLine("==>Echo back");
messenger.OIMService.SendOIMMessage(e.Email, message.Text);
}
void OIMService_OIMSendCompleted(object sender, OIMSendCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("OIM Send Error:" + e.Error.Message);
}
}
public void BeginLogin(string account, string password)
{
if (messenger.Connected)
{
Console.WriteLine("==>Disconnecting from server");
messenger.Disconnect();
}
// set the credentials, this is ofcourse something every MSNPSharp program will need to implement.
messenger.Credentials = new Credentials(account, password, MsnProtocol.MSNP16);
// inform the user what is happening and try to connecto to the messenger network.
Console.WriteLine("==>Connecting to server...");
messenger.Connect();
//displayImageBox.Image = global::MSNPSharpClient.Properties.Resources.loading;
//loginButton.Tag = 1;
//loginButton.Text = "Cancel";
// note that Messenger.Connect() will run in a seperate thread and return immediately.
// it will fire events that informs you about the status of the connection attempt.
// these events are registered in the constructor.
}
/// <summary>
/// main()
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string robot_acc = "";
string robot_passwd = "";
if (args.Length == 0)
{
Console.WriteLine("USAGE:MSNRobot.exe <msn_account> [password]");
return;
}
robot_acc = args[0];
if (args.Length == 2)
robot_passwd = args[1];
else
{
Console.WriteLine("Password for " + robot_acc + ":");
robot_passwd = Console.ReadLine();
}
RobotMain app = new RobotMain();
app.BeginLogin(robot_acc, robot_passwd);
while (true)
{
Console.WriteLine("I am a MSN robot:" + robot_acc);
Console.ReadLine();
}
}
}
}
Have you tried the example client for MSNPSharp?