review comport code in wince 6.0 - windows-ce

hellou all, we have ibutton devices for reading ibutton. This device is usb and have FTDI virtual comport.
We have our simple aplication for reading data from reader, but reader have problem (when is more buttons swipe on reader - it stop send data)
In this case when we catch problem (sending G and g - like green diode stop and start), restart comport - but after reboot comport aplication takes 100% of cpu.
is here anybody which have any idea what we need to do or how modify source code.
thanks a lot
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using OpenNETCF;
namespace SerialDownload
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
AddLog("Vytvaram novy seriovy port");
serialPort1 = new System.IO.Ports.SerialPort();
serialPort1.PortName = "COM4";
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.DataReceived += serialPort1_DataReceived;
//serialPort1.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort1_ErrorReceived);
//serialPort1.PinChanged += new System.IO.Ports.SerialPinChangedEventHandler(serialPort1_PinChanged);
serialPort1.WriteBufferSize = 10000;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("Vytvoreny seriovy port");
}
bool zelena = false;
private void timerResetCOM_Tick(object sender, EventArgs e)
{
timerResetCOM.Enabled = false;
if (!nacitavam_kartu_serial)
{
try
{
string znak = "G";
if (!zelena)
{
znak = "g";
zelena = true;
}
else
{
zelena = false;
}
AddLog("Posielam " + znak);
serialPort1.WriteTimeout = 2000;
serialPort1.Write(znak);
System.Threading.Thread.Sleep(200);
AddLog("Odoslane " + znak);
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba serioveho portu pri odoslani G");
try
{
serialPort1.DataReceived -= serialPort1_DataReceived;
AddLog("robim discard");
serialPort1.DiscardOutBuffer();
System.Threading.Thread.Sleep(200);
AddLog("Discard dokonceny");
AddLog("Zatvaram port");
serialPort1.Close();
AddLog("port zatvoreny");
KillProc("SerialDownload");
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba zatorenia portu");
}
/*
try
{
AddLog("Dispose serioveho");
serialPort1.DataReceived -= serialPort1_DataReceived;
serialPort1.Dispose();
System.Threading.Thread.Sleep(200);
AddLog("Dispose serioveho OK");
AddLog("Vytvaram novy seriovy port");
serialPort1 = new System.IO.Ports.SerialPort();
serialPort1.PortName = "COM4";
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.DataReceived += serialPort1_DataReceived;
//serialPort1.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort1_ErrorReceived);
//serialPort1.PinChanged += new System.IO.Ports.SerialPinChangedEventHandler(serialPort1_PinChanged);
serialPort1.WriteBufferSize = 10000;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("Vytvoreny seriovy port");
}
catch (Exception ex)
{
AddLog("Chyba vytvaranie serioveho portu - alebo rusenia");
}
System.Threading.Thread.Sleep(1000);
try
{
AddLog("otvaram port");
serialPort1.Open();
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("port otvoreny");
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba otvorenia portu");
}*/
}
}
}
bool nacitavam_kartu_serial = false;
private void KillProc(string name)
{
var processes = OpenNETCF.ToolHelp.ProcessEntry.GetProcesses();
foreach (OpenNETCF.ToolHelp.ProcessEntry process in processes)
{
if (name == process.ExeFile)
{
process.Kill();
}
}
}
private void AddLog(string riadok)
{
Debug.WriteLine(DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss") + ": " + riadok);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
nacitavam_kartu_serial = true;
AddLog("Nacitacam data");
try
{
string pStrTmp = string.Empty;
while (serialPort1.BytesToRead > 0)
{
pStrTmp += (char)serialPort1.ReadByte();
System.Threading.Thread.Sleep(15);
}
string card_id_t = pStrTmp;
AddLog("Nacitane data: " + card_id_t);
StreamWriter subor = File.CreateText("\\NAND\\karta_serial.txt");
subor.Write(card_id_t);
subor.Close();
}
catch (Exception ex)
{
AddLog(ex.Message);
}
nacitavam_kartu_serial = false;
}
}
}

It is late, but I will leave my answer here.
I have seen similar problem with .NET Compact Framework and com port, two years ago. The device I had was on windows mobile 6, the other device was BT printer on comport.
Other handheld devices ran just fine, just this one had exactly the same problem, when you turn of the printer - the app ran slow, to the point where you could not use it for work anymore.
My temporal solution was to close the SerialPort object.
I hope it helps

Related

Worker stop in the middle and not updating progress bar

I'm trying to load information with worker and using reportprogress to update progress bar until finshing, but the worker stop working and doesn't finish the for loop or continue after several minutes. I don't know what's the problem and I tried every post here I can find related to this problem and didn't get anything. I hope I can finally get an answer posting my problem here.
Here's the relevant code:
public class Class1
{
public BackgroundWorker unit_read_data_setting_Worker;
public Class1()
{
unit_read_data_setting_Worker = new BackgroundWorker();
unit_read_data_setting_Worker.WorkerReportsProgress = true;
unit_read_data_setting_Worker.WorkerSupportsCancellation = false;
unit_read_data_setting_Worker.DoWork += new DoWorkEventHandler(unit_read_data_setting);
unit_read_data_setting_Worker.ProgressChanged += new ProgressChangedEventHandler(_update_progress);
unit_read_data_setting_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
public void unit_read_data_setting(object sender = null, DoWorkEventArgs e = null)
{
lock (FamilyTreeViewModel.Lock_ParameterList)
{
ObservableCollection<Parameter_UC_ViewModel> _internal_parameter_list =
FamilyTreeViewModel.GetInstance.ParameterList;
if (FamilyTreeViewModel.GetInstance.SelectedUnitSetting != null)
{
if (_internal_parameter_list.Count > 0)
{
for (int i = 0; i < _internal_parameter_list.Count; i++)
{
int startValue = i * 100 / _internal_parameter_list.Count;
unit_read_data_setting_Worker.ReportProgress(startValue);
// do stuff related to the index
// when progress_bar at 76 value, the loop stoppes and cotinue after a minute
}
}
}
}
}
private void _update_progress(object sender, ProgressChangedEventArgs e)
{
FamilyTreeViewModel.GetInstance.Unit_read_data_setting_progress_bar = e.ProgressPercentage;
}
private void Completed(object sender, RunWorkerCompletedEventArgs e)
{
// never gets here but there's no error
}
}

how to send data to be printed via bluetooth J2ME

can someone please help. i am trying to send data to a thermal printer using bluetooth. i understand how to discover the devices but not able to connect or know how to send the stream of data to be printed. what do I use here ? there is OBEX and RFComm. which one is appropriate. and can you plz share a sample of code to show how to do it, it would be much appreciated.
Below is a sample code that i have found which uses OBEX to search for near by devices and its actually for image transferring. can you plz point out to me the part that are important and how to change this in order to send a stream of Data rather than picture... plz plz help
public class BluetoothImageSender extends MIDlet implements CommandListener{
public Display display;
public Form discoveryForm;
public Form readyToConnectForm;
public Form dataViewForm;
public ImageItem mainImageItem;
public Image mainImage;
public Image bt_logo;
public TextField addressTextField;
public TextField subjectTextField;
public TextField messageTextField;
public Command selectCommand;
public Command exitCommand;
public Command connectCommand;
public List devicesList;
public Thread btUtility;
public String btConnectionURL;
public boolean readData = false;
public long startTime = 0;
public long endTime = 0;
public BluetoothImageSender() {
startTime = System.currentTimeMillis();
display = Display.getDisplay(this);
discoveryForm = new Form("Image Sender");
try{
mainImage = Image.createImage("/btlogo.png");
bt_logo = Image.createImage("/btlogo.png");
} catch (java.io.IOException e){
e.printStackTrace();
}
mainImageItem = new ImageItem("Bluetooth Image Sender", mainImage, Item.LAYOUT_CENTER, "");
discoveryForm.append(mainImageItem);
discoveryForm.append("\nThis application will scan the area for Bluetooth devices and determine if any are offering OBEX services.\n\n");
/// discoveryForm initialization
exitCommand = new Command("Exit", Command.EXIT, 1);
discoveryForm.addCommand(exitCommand);
discoveryForm.setCommandListener(this);
/// devicesList initialization
devicesList = new List("Select a Bluetooth Device", Choice.IMPLICIT, new String[0], new Image[0]);
selectCommand = new Command("Select", Command.ITEM, 1);
devicesList.addCommand(selectCommand);
devicesList.setCommandListener(this);
devicesList.setSelectedFlags(new boolean[0]);
/// readyToConnectForm initialization
readyToConnectForm = new Form("Ready to Connect");
readyToConnectForm.append("The selected Bluetooth device is currently offering a valid OPP service and is ready to connect. Please click on the 'Connect' button to connect and send the data.");
connectCommand = new Command("Connect", Command.ITEM, 1);
readyToConnectForm.addCommand(connectCommand);
readyToConnectForm.setCommandListener(this);
/// dataViewForm initialization
dataViewForm = new Form("File Sending Progress");
dataViewForm.append("Below is the status of the file sending process:\n\n");
dataViewForm.addCommand(exitCommand);
dataViewForm.setCommandListener(this);
}
public void commandAction(Command command, Displayable d) {
if(command == selectCommand) {
btUtility.start();
}
if(command == exitCommand ) {
readData = false;
destroyApp(true);
}
if(command == connectCommand ) {
Thread filePusherThread = new FilePusher();
filePusherThread.start();
display.setCurrent(dataViewForm);
}
}
public void startApp() {
display.setCurrent(discoveryForm);
btUtility = new BTUtility();
}
public void pauseApp() {
}
public void destroyApp(boolean b) {
notifyDestroyed();
}
////////////////
/**
* This is an inner class that is used for finding
* Bluetooth devices in the vicinity.
*/
class BTUtility extends Thread implements DiscoveryListener {
Vector remoteDevices = new Vector();
Vector deviceNames = new Vector();
DiscoveryAgent discoveryAgent;
// obviously, 0x1105 is the UUID for
// the Object Push Profile
UUID[] uuidSet = {new UUID(0x1105) };
// 0x0100 is the attribute for the service name element
// in the service record
int[] attrSet = {0x0100};
public BTUtility() {
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
discoveryForm.append(" Searching for Bluetooth devices in the vicinity...\n");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass cod) {
try{
discoveryForm.append("found: " + remoteDevice.getFriendlyName(true));
} catch(Exception e){
discoveryForm.append("found: " + remoteDevice.getBluetoothAddress());
} finally{
remoteDevices.addElement(remoteDevice);
}
}
public void inquiryCompleted(int discType) {
if (remoteDevices.size() > 0) {
// the discovery process was a success
// so out them in a List and display it to the user
for (int i=0; i<remoteDevices.size(); i++){
try{
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getFriendlyName(true), bt_logo);
} catch (Exception e){
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getBluetoothAddress(), bt_logo);
}
}
display.setCurrent(devicesList);
} else {
// handle this
}
}
public void run(){
try {
RemoteDevice remoteDevice = (RemoteDevice)remoteDevices.elementAt(devicesList.getSelectedIndex());
discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice , this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord){
for(int i = 0; i < servRecord.length; i++) {
DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
btConnectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
System.out.println(btConnectionURL);
}
display.setCurrent(readyToConnectForm);
readyToConnectForm.append("\n\nNote: the connection URL is: " + btConnectionURL);
}
public void serviceSearchCompleted(int transID, int respCode) {
if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
// the service search process was successful
} else {
// the service search process has failed
}
}
}
////////////////
/**
* FilePusher is an inner class that
* now gets the byte[] named file
* to read the bytes of the file, and
* then opens a connection to a remote
* Bluetooth device to send the file.
*/
class FilePusher extends Thread{
FileConnection fileConn = null;
String file_url = "/loginscreen.png";
byte[] file = null;
String file_name = "loginscreen.png";
String mime_type = "image/png";
// this is the connection object to be used for
// bluetooth i/o
Connection connection = null;
public FilePusher(){
}
public void run(){
try{
InputStream is = this.getClass().getResourceAsStream(file_url);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// now read the file in into the byte[]
int singleByte = 0;
while(singleByte != -1){
singleByte = is.read();
os.write(singleByte);
}
System.out.println("file size: " + os.size());
file = new byte[os.size()];
file = os.toByteArray();
dataViewForm.append("File name: " + file_url);
dataViewForm.append("File size: " + file.length + " bytes");
is.close();
os.close();
} catch (Exception e){
e.printStackTrace();
System.out.println("Error processing the file");
}
try{
connection = Connector.open(btConnectionURL);
// connection obtained
// create a session and a headerset objects
ClientSession cs = (ClientSession)connection;
HeaderSet hs = cs.createHeaderSet();
// establish the session
cs.connect(hs);
hs.setHeader(HeaderSet.NAME, file_name);
hs.setHeader(HeaderSet.TYPE, mime_type); // be sure to note that this should be configurable
hs.setHeader(HeaderSet.LENGTH, new Long(file.length));
Operation putOperation = cs.put(hs);
OutputStream outputStream = putOperation.openOutputStream();
outputStream.write(file);
// file push complete
outputStream.close();
putOperation.close();
cs.disconnect(null);
connection.close();
dataViewForm.append("Operation complete. File transferred");
endTime = System.currentTimeMillis();
long diff = (endTime - startTime)/1000;
System.out.println("Time to transfer file: " + diff);
dataViewForm.append("Time to transfer file: " + diff);
} catch (Exception e){
System.out.println("Error sending the file");
System.out.println(e);
e.printStackTrace();
}
}
}
}

Unity3D threads and GameObjects

I have an application within Unity3D (acting as a server) that receives messages from an exterior application (single client) with the following structure:
number(float) number(float) number(float)
The first two numbers represent the local position (x,z axis) and the last one a rotation value (y axis).
The goal is to use this data to update the Camera gameobject position (using the LoadPositions method) within the game scene. From what I've read manipulating gameobjects while outside Unity's main thread is not possible.
With that being said how can I change from and to Unity main thread so that I can both listen for messages and update the gameobjects position.
Also, anyone happens to know of a working example of a simple TCP Server in Unity without having to resort to threads?
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System;
using System.Text;
using System.Collections.Generic;
public class ProxyThreadServer : MonoBehaviour {
float x;
float z;
float rot;
Vector3 updatePos;
Vector3 updateRot;
string ip_address = "127.0.0.1";
string msgReceived;
string[] words;
int wordsNum;
int port = 8000;
int numSurf;
int jumpInterval;
Thread listen_thread;
TcpListener tcp_listener;
Thread clientThread;
TcpClient tcp_client;
bool isTrue = true;
// Use this for initialization
void Start ()
{
IPAddress ip_addy = IPAddress.Parse(ip_address);
tcp_listener = new TcpListener(ip_addy, port);
listen_thread = new Thread(new ThreadStart(ListenForClients));
listen_thread.Start();
}
private void ListenForClients()
{
this.tcp_listener.Start();
while(isTrue == true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcp_listener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
Debug.Log("Got client " + client);
}
}
private void HandleClientComm(object client)
{
tcp_client = (TcpClient)client;
NetworkStream client_stream = tcp_client.GetStream();
byte[] message = new byte[4096];
int bytes_read;
while(isTrue == true)
{
bytes_read = 0;
try
{
//blocks until a client sends a message
bytes_read = client_stream.Read(message, 0, 4096);
//Debug.Log(message);
}
catch (Exception e)
{
//a socket error has occurred
Debug.Log(e.Message);
break;
}
if(bytes_read == 0)
{
//client has disconnected
Debug.Log("Disconnected");
tcp_client.Close();
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
Debug.Log(encoder.GetString(message,0,bytes_read));
msgReceived = encoder.GetString(message,0,bytes_read);
LoadPositions(msgReceived);
}
if(isTrue == false)
{
tcp_client.Close();
Debug.Log("closing tcp client");
}
}
void OnApplicationQuit()
{
try
{
tcp_client.Close();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
// You must close the tcp listener
try
{
tcp_listener.Stop();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
}
void LoadPositions(string positions){
// Split string on spaces. This will separate all the words.
words = positions.Split(' ');
wordsNum = words.Length;
for (int i = 0; i <= wordsNum; i++) {
x = float.Parse(words[0], System.Globalization.CultureInfo.InvariantCulture);
z = float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture);
rot = float.Parse(words[2], System.Globalization.CultureInfo.InvariantCulture);
Debug.Log("Reading position: " + "x: " + x + " z: " + z + " yRot: " + rot);
updatePos = new Vector3(x, this.gameObject.transform.position.y, z);
this.gameObject.transform.position = updatePos;
updateRot = new Vector3(this.gameObject.transform.rotation.x, rot / 4, this.gameObject.transform.rotation.z);
this.transform.localEulerAngles = updateRot;
//UpdateCameraMatrix();
//StartCoroutine(UpdateSurfs());
}
}
}
While I haven't tried to do something quite like this before, assuming the limitations do exist as you mentioned, my approach would be to use a queue to store the messages then process them in the order they came in on the unity thread. So instead of calling LoadPositions when it comes it, add it to a queue
pendingMessages.Enqueue(msgReceived);
Then in the update method you process it:
void Update()
{
while (pendingMessages.Count() > 0)
LoadPositions(pendingMessages.Dequeue());
}
You can use .NET's Async TCP. It's based on callback delegates. (Working with it is a bit tricky though)

not able to receive sms, Help me correct the code

I don't know what is the problem, but SMS is not received with below code and when I see in the phone memory, app is invalid.
Can anyone correct this code?
I am having a lot of issues with this, it compiles well, but when it is on the real phone, the app says it is invalid,Nokia 2630 supports MIDP 2.0, so not a phone problem.
package Pushtest;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.GridLayout;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.util.Date;
import java.io.*;
/**
* #author test
*/
public class SendApprooval extends MIDlet implements Runnable, ActionListener, MessageListener {
Date todaydate;
private Dialog content, alert;
Thread thread;
String[] connections;
boolean done;
String senderAddress, mess;
MessageConnection smsconn = null, clientConn = null;
Message msg;
// public SendApprooval() {
/*
smsPort = getAppProperty("SMS-Port");
content = new Dialog("");
content.addComponent(new Label("Waiting for Authentication Request"));
content.setDialogType(Dialog.TYPE_INFO);
content.setTimeout(2000);
// exitCommand = new Command("Exit", Command.EXIT, 2);
// content.addCommand(exitCommand)
content.addCommand(exitCommand);
content.addCommandListener(this);
content.show();
} */
public void startApp() {
Display.init(this);
String smsConnection = "sms://:" + 5000;
if (smsconn == null) {
try {
smsconn = (MessageConnection) Connector.open(smsConnection);
smsconn.setMessageListener(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
connections = PushRegistry.listConnections(true);
if ((connections == null) || (connections.length == 0)) {
content.addComponent(new Label("Waiting for Authentication Request"));
}
done = false;
thread = new Thread(this);
thread.start();
// display.setCurrent(resumeScreen);
}
public void run() {
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
} catch (IOException e) {
content.addComponent(new Label(e.toString()));
Display.init(content);
}
}
public void pauseApp() {
done = true;
thread = null;
Display.init(this);
}
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
}
notifyDestroyed();
}
}
public void showMessage(String message, Display displayable) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setTitle("Error");
alert.addComponent(new Label(message));
alert.setDialogType(Dialog.TYPE_ERROR);
alert.setTimeout(5000);
alert.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
content.addComponent(new Label("Waiting for Authentication Request"));
content.setLayout(new GridLayout(5, 1));
content.setDialogType(Dialog.TYPE_INFO);
content.show();
done = false;
thread = new Thread(this);
thread.start();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int id = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdName1 = cmd.getCommandName();
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
if (("Exit").equals(cmdName1)) {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This may be cause because your sending SMS might not send on the port you defined in your code,
Please look at to this working example.
i found it guys, Thanks for your support, i'm sure i would come back with more queries, i have written a sample receiving sms code with port 5000, It would Help someone in someway,
Before you start,
Right click your application in netbeans and select properties. Now select the application descriptor. select the attribute tab and select the Add button. Give the following in the corresponding fields.
Name : SMS-Port
Value : portno
Now u have registered the port no successfully.
Now again select the push registry tab.
give the following in the corresponding fields.
Class Name : Package name.class name
Sender ip : *
Connection String: sms://:portno
Now u have registered the push registry successfully.
CODE HERE:
public class SMSReceiver extends MIDlet implements ActionListener, MessageListener {
private Form formReceiver;
private TextField tfPort;
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/m21.res");
UIManager.getInstance().setThemeProps(
r.getTheme(r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
e.printStackTrace();
}
formReceiver = new Form();
formReceiver.setTitle(" ");
formReceiver.setLayout(new GridLayout(4, 2));
formReceiver.setTransitionInAnimator(null);
TextField.setReplaceMenuDefault(false);
Label lblPort = new Label("Port");
tfPort = new TextField();
tfPort.setMaxSize(8);
tfPort.setUseSoftkeys(false);
tfPort.setHeight(10);
tfPort.setConstraint(TextField.DECIMAL);
formReceiver.addComponent(lblPort);
formReceiver.addComponent(tfPort);
formReceiver.addCommand(new Command("Listen"), 0);
formReceiver.addCommand(new Command("Exit"), 0);
formReceiver.addCommandListener(this);
formReceiver.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.addComponent(new Label("Message received : "+tMessage.getPayloadText()+"\n"));
} else {
formReceiver.addComponent(new Label("Unknown Message received\n"));
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int idi = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdNam = cmd.getCommandName();
if ("Listen".equals(cmdNam)) {
ListenSMS sms = new ListenSMS(tfPort.getSelectCommandText(), this);
sms.start();
}
if ("Exit".equals(cmdNam)) {
notifyDestroyed();
}
}
}
class ListenSMS extends Thread {
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
public ListenSMS(String port, MessageListener listener) {
this.port = port;
this.Listener = listener;
}
public void run() {
try {
msgConnection = (MessageConnection)Connector.open("sms://:" + 5000);
msgConnection.setMessageListener(Listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}

C# create configuration file

This code How can I create configuration file if so that i can change connection string easy
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 MySql.Data.MySqlClient;
using System.Web;
using mshtml;
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (webBrowser1.Document != null)
//{
// IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
// if (document != null)
// {
// IHTMLSelectionObject currentSelection = document.selection;
// IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
// if (range != null)
// {
// const String search = "We";
// if (range.findText(search, search.Length, 2))
// {
// range.select();
// }
// }
// }
//}
}
}
}
You can create an XML configuration file looking like this :
<db-config>
<server>192.168.0.78</server>
<database>webboard</database>
<...>...</...>
</db-config>
Then, use XMLTextReader to parse it.
Here is a basic example of how you can use it to parse XML files :
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Hint : Use the ReadTofollowing() to get your values.
Once your XML DB Config Reader class is done, you use it each time you need a new connection, and you'll only need to change your DB Config XML file to change your DB Connections configuration.
Edit : there is an interesting article about Storing database connection settings in .NET here.
Use the default
System.Configuration.ConfigurationManager
that C# supports!
See: http://msdn.microsoft.com/en-us/library/bb397750.aspx

Resources