I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.
Related
I am trying to develop a data access service using Visual Studio 2019, .Net Core 3.0. I am using NancyFX to handle http requests. this is working just fine as a console application. When I build and run, then in browser go to HTTP://localhost/, it returns the proper data. I have a working Nancy module to handle requests. Here is original Main code:
static void Main(string[] args)
{
Logger.LogInfo("NancyDataService starting...");
var uri = new Uri(ConfigurationManager.AppSettings["uri"]);
var hostConfig = new HostConfiguration();
hostConfig.UrlReservations.CreateAutomatically = true;
hostConfig.RewriteLocalhost = false;
using (var nancyHost = new NancyHost(uri, new AppBootstrapper(), hostConfig))
{
try
{
nancyHost.Start();
Console.WriteLine($"Nancy now listening on {uri}.\n\nPress any key to exit");
Logger.LogInfo($"Nancy now listening on {uri}...");
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
Console.WriteLine("Error " + ex.Message + "\n\nPress any key to exit");
}
Console.ReadKey();
Logger.LogInfo("NancyDataService stopped...");
}
}
Now I want to make it a Windows Service. First try is with Topshelf. The following Main code is basically taken from Topshelf documentation and other articles about Topshelf.
static void Main(string[] args)
{
Logger.LogInfo("NancyDataService starting...");
var rc = HostFactory.Run(x =>
{
x.Service<DataService>(s =>
{
s.ConstructUsing(name => new DataService());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.StartAutomatically();
x.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));
x.SetServiceName("NancyDataService");
});
var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); //11
Environment.ExitCode = exitCode;
}
Here is my DataService class, basically built from the Topshelf docs and a couple of articles I found:
class DataService
{
public DataService()
{
}
private SemaphoreSlim _semaphoreToRequestStop;
private Thread _thread;
public void Start()
{
// start Nancy here
var uri = new Uri(ConfigurationManager.AppSettings["uri"]);
var hostConfig = new HostConfiguration();
hostConfig.UrlReservations.CreateAutomatically = true;
hostConfig.RewriteLocalhost = false;
using var nancyHost = new NancyHost(uri, new AppBootstrapper(), hostConfig);
try
{
nancyHost.Start();
Console.WriteLine($"Nancy now listening on {uri}...");
Logger.LogInfo($"Nancy now listening on {uri}...");
// spin thread here
_semaphoreToRequestStop = new SemaphoreSlim(0);
_thread = new Thread(DoWork);
_thread.Start();
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
Console.WriteLine($"Error: {ex.Message}");
}
}
private void DoWork(object obj)
{
while (true)
{
Console.WriteLine("doing work..");
if (_semaphoreToRequestStop.Wait(500))
{
Console.WriteLine("Stopped");
break;
}
}
}
public void Stop()
{
Logger.LogInfo("NancyDataService stopping...");
_semaphoreToRequestStop.Release();
_thread.Join();
//return true;
}
}
So now when I run the project in design mode (which Topshelf says you should be able to do), it seems to start fine and Nancy seems to be listening on the right port. However, when I go to the browser and type in HTTP//localhost:8080/, I get "This site can't be reached. localhost refused to connect"
I have the latest version of Topshelf (4.2.1) and Topshelf.Log4Net packages.
Can anyone shed any light on this? Thanks...
Solved this issue. Turned out to be incorrect scoping of my NancyHost object. Works fine now.
Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
I am creating a mobile app where I need users to be able to select multiple images. I am using the cn1 lib file chooser but I am only able to select one Image. How can I select multiple images. Here is the code I use to select the image.
chooseImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
animateImage.show();
if (FileChooser.isAvailable()){
FileChooser.showOpenDialog(".jpg,.png,.gif", e2->{
String file = (String)e2.getSource();
if (file == null){
animateImage.add("No File Was Selected");
animateImage.revalidate();
}else {
String extension = null;
if (file.lastIndexOf(".") > 0){
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)){
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
animateImage.addComponent(new SpanLabel(Util.readToString(fis)));
} catch (Exception ex) {
Log.e(ex);
}
}else{
try{
Image image = URLImage.createImage((String)e2.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}
//animateImage.add("Selected file "+file);
}
}
animateImage.revalidate();
});
/*try{
Image image = URLImage.createImage((String)evt.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}*/
}
}
});
Thanks
There is no support for that in the cn1lib. You can fork the cn1lib and add support for it manually by changing the native code in the lib.
This isn't supported currently in the standard Codename One API, there is an RFE to add it here: https://github.com/codenameone/CodenameOne/issues/2383
I want to create a program that checks ip address continuously.
i have a code that checks ip address and port, like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace WinNetworkIOCS {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void ConnectButton_Click(object sender, EventArgs e) {
DisableFields();
DoNetworkingConnection();
}
private void DisableFields() {
PortBox.Enabled = false;
IPAddressBox.Enabled = false;
SendMessageBox.Enabled = false;
ConnectButton.Enabled = false;
}
private void EnableFields() {
PortBox.Enabled = true;
IPAddressBox.Enabled = true;
SendMessageBox.Enabled = true;
ConnectButton.Enabled = true;
}
private void WriteToStatusBar(string Message) {
//EnableFields();
ThreadHelperClass.SetText(this, lblStatus, Message);
}
private void DoNetworkingConnection() {
Thread MyThread = null;
try {
ThreadStart ThreadMethod = new ThreadStart(ConnectTo);
MyThread = new Thread(ThreadMethod);
} catch (Exception e) {
WriteToStatusBar("Failed to create thread with error: " + e.Message);
return;
}
try {
MyThread.Start();
} catch (Exception e) {
WriteToStatusBar("The thread failed to start with error: " + e.Message);
}
}
private void ConnectTo() {
string ServerName = this.IPAddressBox.Text;
int Port = System.Convert.ToInt32(this.PortBox.Text);
WriteToStatusBar("IP Address: " + ServerName + "Port: " + Port);
Socket ClientSocket = null;
try {
// Let's connect to a listening server
try {
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
WriteToStatusBar("Socket is OK...");
} catch (Exception e) {
throw new Exception("Failed to create client Socket: " + e.Message);
}
IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port));
try {
ClientSocket.Connect(ServerEndPoint);
WriteToStatusBar("Connect() is OK...");
} catch (Exception e) {
throw new Exception("Failed to connect client Socket: " + e.Message);
}
} catch (Exception e) {
WriteToStatusBar(e.Message);
ClientSocket.Close();
return;
}
// Let's create a network stream to communicate over the connected Socket.
NetworkStream ClientNetworkStream = null;
try {
try {
// Setup a network stream on the client Socket
ClientNetworkStream = new NetworkStream(ClientSocket, true);
WriteToStatusBar("Instantiating NetworkStream...");
} catch (Exception e) {
// We have to close the client socket here because the network
// stream did not take ownership of the socket.
ClientSocket.Close();
throw new Exception("Failed to create a NetworkStream with error: " + e.Message);
}
StreamWriter ClientNetworkStreamWriter = null;
try {
// Setup a Stream Writer
ClientNetworkStreamWriter = new StreamWriter(ClientNetworkStream);
WriteToStatusBar("Setting up StreamWriter...");
} catch (Exception e) {
ClientNetworkStream.Close();
throw new Exception("Failed to create a StreamWriter with error: " + e.Message);
}
try {
ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());
ClientNetworkStreamWriter.Flush();
WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");
} catch (Exception e) {
throw new Exception("Failed to write to client NetworkStream with error: " + e.Message);
}
} catch (Exception e) {
WriteToStatusBar(e.Message);
} finally {
// Close the network stream once everything is done
ClientNetworkStream.Close();
}
}
delegate void SetTextCallback(string text);
}
Problem is that it does not check the ip address and port continuously.
What to add into my code to make this happen?
I am assuming that what you mean is that you wish to be able to run your program more than once, not that you wish for it to check over and over again and therefore that your problem is in fact that your program finishes the task of pinging but then never allows you to enter new information?
This is because in your function
private void ConnectButton_Click(object sender, EventArgs e) {
DisableFields();
DoNetworkingConnection();
}
You run the function DisableFields(); and DoNetworkingConnection(); Assuming that the DoNeworkingConnection(); works and it runs the code once then your problem is that you never enable your controls again since in
private void WriteToStatusBar(string Message) {
//EnableFields();
ThreadHelperClass.SetText(this, lblStatus, Message);
}
You have commented out EnableFields(); that re-enables your controls. If this is not the case and you are actually trying to make it run continuously you would have to wrap the sending part of the ConnectTo() in a while loop
while(true)
{
ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());
ClientNetworkStreamWriter.Flush();
WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");
}
Though if this is the case please state what you are trying to achieve and you will probably get a better solution because this will quickly turn into something like a DOS attack..
I've been working with GWT and appengine. Now I want to change my database to a relational one. I prefer PostgreSQL over MySQL because of the schema architecture.
I already work in projects with JDBC, but I cannot make it work in my appengine project.
What am I doing wrong?
I think you are mistake. If you want your backend to connect to JDBC you have to disable appengine.
I recommend creating a new web project with the google eclipse plugin but without appengine. Then copy all the source files and start from there.
I let you my class to connect to PostgreSQL vua JDBC
public class ConexionBD
{
private Vector <Connection> connections = new Vector<Connection>();
protected int cantCon=3;
private static ConexionBD pool;
private ConexionBD(){
for (int i= 0; i< cantCon;i++)
connections.add(connect());
}
public static ConexionBD getPoolConnection(){
if (pool== null)
pool =new ConexionBD();
return pool;
}
private Connection connect()
{
try
{
//Setear driver
Class.forName ("org.postgresql.Driver").newInstance ();
Connection con = DriverManager.getConnection ("jdbc:postgresql://localhost:5432/llevomisnegocios","postgres","root");
return con;
}
catch (SQLException e){
System.out.println("Mensaje Error al Conectar: " + e.getMessage());
//System.out.println("Stack Trace: " + e.getStackTrace());
return null;
}catch (Exception ex){
System.out.println("Mensaje Error al Conectar: " + ex.getMessage());
//System.out.println("Stack Trace: " + ex.getStackTrace());
return null;
}
}
public void closeConnections(){
for (int i=0; i<connections.size();i++)
{
try
{
connections.elementAt(i).close();
}
catch(Exception e)
{
System.out.println("Mensaje Error: " + e.getMessage());
System.out.println("Stack Trace: " + e.getStackTrace());
}
}
}
public Connection getConnection(){
Connection c = null;
if (connections.size()>0)
c = connections.remove(0);
else{
c = connect();
System.out.println("PoolConnection: Conexion Exitosa con la BD");
}
return c;
}
public void realeaseConnection(Connection c){
connections.add(c);
}
}