Outbound Dialer SIP configuration - c#

I am trying to build a UCMA standalone outbound dialer. Unfortunately I can't find much information on how to connect to a SIP or how to configure this to begin with. I got a GetOnSIP and would like to associate it with my application. Any help would be appreciated!
Thanks
//set up my application
internal void Start()
{
_applicationId = ConfigurationManager.AppSettings["applicationId"];
_recipientSipUri = ConfigurationManager.AppSettings["recipientSipUri"];
//string urisToDialString = ConfigurationManager.AppSettings["numbersToDial"];
_urisToDial.Add("phone number goes here");
ServerPlatformSettings platformSettingsObj = new ServerPlatformSettings(_applicationId, Dns.GetHostEntry("localhost").HostName,
5060, string.Empty /* empty string for the GRUU */);
Utils.WriteDebug("Endpoint: " + platformSettingsObj.Localhost);
_platform = new CollaborationPlatform(platformSettingsObj);
_platform.AllowedAuthenticationProtocol = SipAuthenticationProtocols.None;
try
{
_platform.BeginStartup(ar =>
{
try
{
_platform.EndStartup(ar);
Console.WriteLine("Platform started.");
StartEndpoint();
Console.WriteLine("Platform Endpoint Initiated.");
CallSession sessionObj = new CallSession(_urisToDial.First(), _endpoint);
sessionObj.InitiateCall();
}
catch (RealTimeException ex)
{
Console.WriteLine(ex);
}
}, null);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex);
}
}
private void StartEndpoint()
{
// Create a placeholder URI for the endpoint.
ApplicationEndpointSettings endpointSettings =
new ApplicationEndpointSettings("sip:default#" +
Dns.GetHostEntry("localhost").HostName);
// Make this a default routing endpoint, so that
// all requests sent to the listening port on this IP,
// regardless of To URI, will come to the endpoint.
endpointSettings.IsDefaultRoutingEndpoint = true;
// Create a new endpoint and register for AV calls.
_endpoint = new ApplicationEndpoint(_platform, endpointSettings);
_endpoint.RegisterForIncomingCall<AudioVideoCall>(OnCallReceived);
try
{
_endpoint.BeginEstablish(ar =>
{
try
{
_endpoint.EndEstablish(ar);
Console.WriteLine("Endpoint started.");
}
catch (RealTimeException ex)
{
Console.WriteLine(ex);
}
}, null);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex);
}
}
public CallSession(string number, ApplicationEndpoint endpointObj)
{
// Set the host and port to which the INVITE should be sent
// i'm going to guess that this is where the sbc ip goes
ConnectionContext connectionContextObj = new ConnectionContext("192.168.0.56", 5060);
optionsObj.ConnectionContext = connectionContextObj;
//configure this to use udp
_phoneNumber = number;
_endpoint = endpointObj;
}
public bool InitiateCall()
{
bool isInitiated = true;
try
{
Utils.WriteDebug("About to Initiate a phone Call");
Conversation convObj = new Conversation(_endpoint);
AudioVideoCall avcallObj = new AudioVideoCall(convObj);
// Establish the call using the options we created
//avcall.BeginEstablish("sip:test#test.greenl.ee", optionsObj,
avcallObj.BeginEstablish("tel:+" + _phoneNumber, optionsObj,
ar =>
{
try
{
avcallObj.EndEstablish(ar);
Console.WriteLine("The call with Local Participant: " + avcallObj.Conversation.LocalParticipant + " and Remote Participant: " + avcallObj.RemoteEndpoint.Participant + " is now in the established state.");
}
catch (RealTimeException ex)
{
isInitiated = false;
Utils.LogError(ex);
}
},
null);
}
catch (InvalidOperationException ex)
{
isInitiated = false;
Utils.LogError(ex);
}
return isInitiated;
}

Related

Static methods in Web API... Correct or wrong?

I am writing an asp.net web API using Visual Studio 2019. When I write as in the example below, Visual Studio recommends me making the method static. So I followed the suggestions and made all methods of the Web API static. Is this correct? What is the advantage if it is correct and what is the disadvantage if it is wrong?
Thank you...
Severity Code Description Project File Line Suppression State
Message CA1822 Member AdresleriGetir does not access instance data and can be marked as static (Shared in VisualBasic) Devriye.WebApi**
My method:
[HttpPost]
public static Adres[] AdresleriGetir([FromBody]GirisParametresi girisParametresi)
{
if (girisParametresi != null)
{
string query = #"SELECT * FROM ADRESLER WHERE AKTIF=1";
Cagri cagri = new Cagri()
{
Proje = "Devriye.WebApi",
Modul = "AdresController",
Metot = "AdresGetir",
Nesne = new JavaScriptSerializer().Serialize(girisParametresi)
};
Log log = new Log(null, cagri, girisParametresi.Oturum);
using (DataTable dataTable = DataAccessLayer.VerileriGetir(query, null, log))
{
List<Adres> adresler = new List<Adres>();
if (dataTable.Rows.Count > 0)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Adres adres = new Adres();
try { adres.Cadde = Convert.ToString(dataTable.Rows[i]["Cadde".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.EklenmeTarihi = Convert.ToDateTime(dataTable.Rows[i]["EklenmeTarihi".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.ID = Convert.ToInt32(dataTable.Rows[i]["ID".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Il = Convert.ToString(dataTable.Rows[i]["Il".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Ilce = Convert.ToString(dataTable.Rows[i]["Ilce".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.KapiNo = Convert.ToString(dataTable.Rows[i]["KapiNo".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Mahalle = Convert.ToString(dataTable.Rows[i]["Mahalle".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.PostaKodu = Convert.ToInt32(dataTable.Rows[i]["PostaKodu".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Sokak = Convert.ToString(dataTable.Rows[i]["Sokak".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
adresler.Add(adres);
}
return adresler.ToArray();
}
else
{
return null;
}
}
}
else
{
return null;
}
}
This function doesn't access any instance data or call any instance methods.
I've had similar questions about R# wanting to convert this type of function to static. See this SO question for some reasons. From the accepted answer in the link;
It makes me ask myself if the method in question should actually be
part of the type or not. Since it doesn't use any instance data, you
should at least consider if it could be moved to its own type. Is it
an integral part of the type, or is it really a general purpose
utility method?
If it does make sense to keep the method on the specific type, there's
a potential performance gain as the compiler will emit different code
for a static method.

Get the live data on TCP server from UWP (UPDATED)

Below is one method that basically sends the data to TCP Server.
UPDATE BEGINS HERE:
//////////////////////////////////
private string FormatValueByPresentation(IBuffer buffer, GattPresentationFormat format)
{
// BT_Code: For the purpose of this sample, this function converts only UInt32 and
// UTF-8 buffers to readable text. It can be extended to support other formats if your app needs them.
byte[] data;
CryptographicBuffer.CopyToByteArray(buffer, out data);
if (format != null)
{
if (format.FormatType == GattPresentationFormatTypes.UInt32 && data.Length >= 4)
{
return BitConverter.ToInt32(data, 0).ToString();
}
else if (format.FormatType == GattPresentationFormatTypes.Utf8)
{
try
{
return Encoding.UTF8.GetString(data);
}
catch (ArgumentException)
{
return "(error: Invalid UTF-8 string)";
}
}
else
{
// Add support for other format types as needed.
return "Unsupported format: " + CryptographicBuffer.EncodeToHexString(buffer);
}
}
else if (data != null)
{
// We don't know what format to use. Let's try some well-known profiles, or default back to UTF-8.
if (selectedCharacteristic.Uuid.Equals(GattCharacteristicUuids.HeartRateMeasurement))
{
try
{
///////LOOK HERE/////
**string b = ParseHeartRateValue(data).ToString();
TrySend(b);
//return "Heart Rate: " + ParseHeartRateValue(data).ToString();
return "Heart Rate: " + b;**
}
catch (ArgumentException)
{
return "Heart Rate: (unable to parse)";
}
}
else if (selectedCharacteristic.Uuid.Equals(GattCharacteristicUuids.BatteryLevel))
{
try
{
// battery level is encoded as a percentage value in the first byte according to
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.battery_level.xml
return "Battery Level: " + data[0].ToString() + "%";
}
catch (ArgumentException)
{
return "Battery Level: (unable to parse)";
}
}
// This is our custom calc service Result UUID. Format it like an Int
else if (selectedCharacteristic.Uuid.Equals(Constants.ResultCharacteristicUuid))
{
return BitConverter.ToInt32(data, 0).ToString();
}
// No guarantees on if a characteristic is registered for notifications.
else if (registeredCharacteristic != null)
{
// This is our custom calc service Result UUID. Format it like an Int
if (registeredCharacteristic.Uuid.Equals(Constants.ResultCharacteristicUuid))
{
return BitConverter.ToInt32(data, 0).ToString();
}
}
else
{
try
{
return "Unknown format: " + Encoding.UTF8.GetString(data);
}
catch (ArgumentException)
{
return "Unknown format";
}
}
}
else
{
return "Empty data received";
}
return "Unknown format";
}
///////// END OF UPDATE //////
private async void TrySend(string data)
{
// Create the StreamSocket and establish a connection to the echo server.
StreamSocket socket = new StreamSocket();
try
{
var streamSocket = new Windows.Networking.Sockets.StreamSocket();
{
//The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
var hostName = new Windows.Networking.HostName("127.0.0.1");
await streamSocket.ConnectAsync((new Windows.Networking.HostName("127.0.0.1")), "9999");
// Send a request to the echo server.
using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
while (true)
{
await streamWriter.WriteLineAsync(data);
await streamWriter.FlushAsync();
}
//await streamWriter.WriteLineAsync(data);
//await streamWriter.FlushAsync();
}
}
}
}
catch (Exception)
{
}
}
And here is my TCP Server code that receives the data:
public class EchoServer {
public static void Main() {
TcpListener listener = null;
try
{
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9999);
listener.Start();
Console.WriteLine("TCP Server Has Started....");
while (true)
{
Console.WriteLine(" ");
Console.WriteLine("Waiting for incoming client connections....");
Console.WriteLine(" ");
Console.WriteLine("A message will display below once the client starts and establishes a connection ");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine(" ");
Console.WriteLine("Okay, Accepting Client connection now");
Console.WriteLine(" ");
Console.WriteLine("Accepted new client connection.....");
StreamReader reader = new StreamReader(client.GetStream());
StreamWriter writer = new StreamWriter(client.GetStream());
string s = string.Empty;
while (!(s = reader.ReadLine()).Equals("Exit") || (s == null)) {
Console.WriteLine("From client -> " + s);
writer.WriteLine("From server -> " + s);
writer.Flush();
}
reader.Close();
writer.Close();
client.Close();
}
} catch (Exception e)
{
Console.WriteLine(e);
} finally
{
if (listener != null)
{
listener.Stop();
}
}
}
}
Now, the data I am trying to get are the heart rates and it changes every two seconds. However on TCP server I only get the first recorded value of a heart rate and it keeps repeating instead of getting new one.
There is a similar post I saw here on stackoverflow : UWP TCP receive data continuously
and someone suggested to use while loop which I did as you can see in the code.
Are there any other suggestions on what should I do?
Thanks
while (true)
{
await streamWriter.WriteLineAsync(data);
await streamWriter.FlushAsync();
}
The while(true) will keep repeating, meaning that it will always send 'data' at its current value. This is what causes your issue.
In my opinion, you should keep a connection to your TCP server open outside of your 'TrySend' method, and use this method only to send the data. This way you won't need to use this loop.
EDIT :
Try this :
private async void CharacteristicReadButton_Click()
{
while(true)
{
// BT_Code: Read the actual value from the device by using Uncached.
GattReadResult result = await selectedCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success)
{
string formattedResult = FormatValueByPresentation(result.Value, presentationFormat);
rootPage.NotifyUser($"Read result: {formattedResult}", NotifyType.StatusMessage);
//string formattedResult = FormatValueByPresentation(result.Value, presentationFormat);
//rootPage.NotifyUser($"Read result: {formattedResult}", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser($"Read failed: {result.Status}", NotifyType.ErrorMessage);
}
}
}

How to get all uid of messages using "$ UID SEARCH ALL"?

I am trying to get all messages id from my email,but it doesn't work. I get this answer:
$ BAD [CLIENTBUG] Unrecognised command\r\n\0\0\0\0.
How do I get the correct response?
string uids1 = ReceiveResponse("$ SELECT INBOX\r\n");
string uids = ReceiveResponse("$ UID SEARCH ALL" + "\r\n");//query to server
private string ReceiveResponse(string command)
{
_sb = new StringBuilder();
try
{
if (command != "")
{
if (_tcpClient.Connected)
{
_dummy = Encoding.ASCII.GetBytes(command);
_ssl.Write(_dummy, 0, _dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
_ssl.Flush();
_buffer = new byte[2048];
_tcpClient.ReceiveTimeout = 20000;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
do
{
try
{
bytes = _ssl.Read(_buffer, 0, 2048);
var msg = Encoding.UTF8.GetString(_buffer);
_sb.Append(msg);
Thread.Sleep(3);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
} while (_tcpClient.Available > 0);
string text = _sb.ToString().Replace("\0", string.Empty);
return _sb.ToString();
}
catch (Exception ex)//if we have some problem show message
{
throw new ApplicationException(ex.Message);
}
}

Reading OPC Values from OPC Server using C#

I have an OPC-DA Server that a SCADA software writes the variables and its values in it so I want to read them synchronously with using C#. I have already write my algorithm but I could not read the variables. The code creates a subscription or may be creates a group instance that writes the own variables and values in it but I do not want this. I need to just read the values from OPC server.
I have established a connection between OPC Server but I have not reach the variables which writes the variables into OPC Server.
Where is the problem, I cannot realise it. Could you suggest a solution about it?
My Code:
class OpcFunctions
{
Opc.Da.Server Server = null;
OpcCom.Factory Factory = new OpcCom.Factory();
Opc.Da.Item[] Items;
Opc.Da.Subscription Group;
Opc.IRequest myReq;
Opc.Da.WriteCompleteEventHandler WriteEventHandler;
Opc.Da.ReadCompleteEventHandler ReadEventHandler;
public void GetOpcServers(TreeView OpcServerTreeList, ListBox OpcConnectionUrlListBox)
{
try
{
OpcCom.ServerEnumerator myServerEnumerator = new OpcCom.ServerEnumerator();
Opc.Server[] Servers = myServerEnumerator.GetAvailableServers(Opc.Specification.COM_DA_20);
ListServers(Servers,OpcServerTreeList,OpcConnectionUrlListBox);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ListServers(Opc.Server[] OpcServerList , TreeView OpcServerTreeList, ListBox OpcConnectionUrlListBox)
{
try
{
OpcServerTreeList.Nodes.Clear();
OpcConnectionUrlListBox.Items.Clear();
foreach(Opc.Server myServer in OpcServerList)
{
TreeNode myTreeNode = new TreeNode(myServer.Name);
myTreeNode.Nodes.Add(myServer.Url.HostName + ":" + myServer.Url.Path + ":" + myServer.Url.Port);
myTreeNode.Nodes.Add(myServer.Url.ToString());
myTreeNode.Nodes.Add(myServer.IsConnected.ToString());
OpcServerTreeList.Nodes.Add(myTreeNode);
OpcConnectionUrlListBox.Items.Add(myServer.Url.ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public bool ConnectOpcServer(string OpcUrl)
{
Opc.URL Url = new Opc.URL(OpcUrl);
Server = new Opc.Da.Server(Factory, null);
try
{
Server.Connect(Url, new Opc.ConnectData(new System.Net.NetworkCredential()));
Opc.Da.SubscriptionState GroupState = new Opc.Da.SubscriptionState();
GroupState.Name = "Group1";
GroupState.Active = true;
Group = (Opc.Da.Subscription)Server.CreateSubscription(GroupState);
Group.DataChanged += new Opc.Da.DataChangedEventHandler(GroupDataChanged);
Items = Group.AddItems(Items);
ReadEventHandler = new Opc.Da.ReadCompleteEventHandler(ReadCompleteCallback);
Group.Read(Group.Items, 123, ReadCompleteCallback, out myReq);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
void GroupDataChanged(object subscriptionHandle, object requestHandle, Opc.Da.ItemValueResult[] values)
{
uint order = 1;
foreach (Opc.Da.ItemValueResult chitem in values)
{
myWriteLogList(order, chitem.Timestamp, chitem.ItemName, chitem.Value.ToString(), chitem.Quality.ToString());
++order;
}
}
void myWriteLogList(uint order, DateTime timestamp, string name, string value, string signalquality)
{
SettingsUI.OpcExplorer.dataGridViewOpcExplorer.BeginInvoke((MethodInvoker)delegate
{
SettingsUI.OpcExplorer.dataGridViewOpcExplorer.Rows.Add(null,order,timestamp,name,value,signalquality);
});
}
void ReadCompleteCallback(object clientHandle, Opc.Da.ItemValueResult[] results)
{
uint order = 1;
foreach (Opc.Da.ItemValueResult readResult in results)
{
myWriteLogList(order, readResult.Timestamp, readResult.ItemName, readResult.Value.ToString(), readResult.Quality.ToString());
++order;
}
}
}
Your 'Items' is empty!
sample:
Opc.Da.Item[] items = new Opc.Da.Item[1];
items[0] = new Opc.Da.Item();
items[0].ItemName = "PlcGroup.Items.value";
Try read from server...
ADD ITEMS AND READ
var result=Server.read(items);
For(i=0;i<result.length;i++) { Console.writeln(result[i].value); }

How to test if a proxy server is working or not?

I've got a pretty big list with proxy servers and their corresponding ports. How can I check, if they are working or not?
Working? Well, you have to use them to see if they are working.
If you want to see if they are online, I guess ping is a first step.
There is a Ping class in .NET.
using System.Net.NetworkInformation;
private static bool CanPing(string address)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(address, 2000);
if (reply == null) return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
return false;
}
}
I like to do a WhatIsMyIP check through a proxy as a test.
using RestSharp;
public static void TestProxies() {
var lowp = new List<WebProxy> { new WebProxy("1.2.3.4", 8080), new WebProxy("5.6.7.8", 80) };
Parallel.ForEach(lowp, wp => {
var success = false;
var errorMsg = "";
var sw = new Stopwatch();
try {
sw.Start();
var response = new RestClient {
//this site is no longer up
BaseUrl = "https://webapi.theproxisright.com/",
Proxy = wp
}.Execute(new RestRequest {
Resource = "api/ip",
Method = Method.GET,
Timeout = 10000,
RequestFormat = DataFormat.Json
});
if (response.ErrorException != null) {
throw response.ErrorException;
}
success = (response.Content == wp.Address.Host);
} catch (Exception ex) {
errorMsg = ex.Message;
} finally {
sw.Stop();
Console.WriteLine("Success:" + success.ToString() + "|Connection Time:" + sw.Elapsed.TotalSeconds + "|ErrorMsg" + errorMsg);
}
});
}
However, I might suggest testing explicitly for different types (ie http, https, socks4, socks5). The above only checks https. In building the ProxyChecker for https://theproxisright.com/#proxyChecker, I started w/ the code above, then eventually had to expand for other capabilities/types.
try this:
public static bool SoketConnect(string host, int port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
System.Threading.Thread.Sleep(500);
var hip = IPAddress.Parse(host);
var ipep = new IPEndPoint(hip, port);
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
string strIP = "10.0.0.0";
int intPort = 12345;
public static bool PingHost(string strIP , int intPort )
{
bool blProxy= false;
try
{
TcpClient client = new TcpClient(strIP ,intPort );
blProxy = true;
}
catch (Exception ex)
{
MessageBox.Show("Error pinging host:'" + strIP + ":" + intPort .ToString() + "'");
return false;
}
return blProxy;
}
public void Proxy()
{
bool tt = PingHost(strIP ,intPort );
if(tt == true)
{
MessageBox.Show("tt True");
}
else
{
MessageBox.Show("tt False");
}

Categories

Resources