Blackberry - How to consume wcf rest services - blackberry-eclipse-plugin

Recently i have started working on consuming wcf rest webservices in blackberry.
I have used the below two codes:
1.
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
// passing q’s value and ie’s value
postData.append("UserName", "hsharma#seasiaconsulting.com");
postData.append("Password", "mind#123");
HttpPosst hh=new HttpPosst();
add(new LabelField("1"));
String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData);
add(new LabelField("2"));
add(new LabelField(res));
public String GetResponse(String url, URLEncodedPostData data)
{
this._postData = data;
this._url = url;
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// logMessage("Carrier coverage.");
// String carrierUid = getCarrierBIBSUid();
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
// Check for an MDS connection instead (BlackBerry Enterprise
// Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the
// user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
// logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// logMessage("no other options found, assuming device.");
// connectionString = ";deviceside=true";
}
conDesc = conFactory.getConnection(url + connectionString);
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if (null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection) conDesc.getConnection();
// set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length",Integer.toString(data.size()));
// body content of
// post data
connection.setRequestProperty("Connection", "close");
// close
// the
// connection
// after
// success
// sending
// request
// and
// receiving
// response
// from
// the
// server
connection.setRequestProperty("Content-Type","application/json");
// we set the
// content of
// this request
// as
// application/x-www-form-urlencoded,
// because the
// post data is
// encoded as
// form-urlencoded(if
// you print the
// post data
// string, it
// will be like
// this ->
// q=remoQte&ie=UTF-8).
// now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
// when this
// code is
// called,
// the post
// data
// request
// will be
// send to
// server,
// and after
// that we
// can read
// the
// response
// from the
// server if
// the
// response
// code is
// 200 (HTTP
// OK).
if (responseCode == HttpConnection.HTTP_OK)
{
// read the response from the server, if the response is
// ascii character, you can use this following code,
// otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while ((read = in.read()) != -1)
buf.append((char) read);
response = buf.toString();
}
// don’t forget to close the connection
connection.close();
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
}
return response;
}
public boolean checkResponse(String res)
{
if(!res.equals(""))
{
if(res.charAt(0)=='{')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
but with this code i am unable to obtain response as what the above wcf web service return
which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]})
Can anybody help me regarding its parsing in blackberry client end.
2.And the another code which i used is:
public class KSoapDemo extends MainScreen
{
private EditField userNametxt;
private PasswordEditField passwordTxt;
private ButtonField loginBtn;
String Username;
String Password;
public KSoapDemo()
{
userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com");
passwordTxt = new PasswordEditField("Password : ", "mind#123");
loginBtn = new ButtonField("Login");
add(userNametxt);
add(passwordTxt);
add(loginBtn);
loginBtn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert("Hi Satyaseshu..!");
login();
}
});
}
private void login()
{
if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0)
{
//Dialog.alert("You must enter a username and password", );
}
else
{
String username = userNametxt.getText();
String password = passwordTxt.getText();
System.out.println("UserName... " + username);
System.out.println("Password... " + password);
boolean value = loginPArse1(username, password);
add(new LabelField("value... " + value));
}
}
public boolean onClose()
{
Dialog.alert("ADIOOO!!");
System.exit(0);
return true;
}
public boolean loginPArse1(String username, String password)
{
username=this.Username;
password=this.Password;
boolean ans = false;
String result = null;
SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration");
//request.addProperty("PowerValue","1000");
//request.addProperty("fromPowerUnit","kilowatts");
//request.addProperty("toPowerUnit","megawatts");
request.addProperty("userName",Username);
request.addProperty("Password", Password);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
add(new LabelField("value... " + "1"));
HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters());
ht.debug = true;
add(new LabelField("value... " + "2"));
//System.out.println("connectionType is: " + connectionType);
try {
ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope);
SoapObject body = (SoapObject) envelope.bodyIn;
add(new LabelField("soap....="+body.toString()));
add(new LabelField("property count....="+body.getPropertyCount()));
// add(new LabelField("Result....="+body.getProperty("HelloWorldResult")));
//result = body.getProperty("Params").toString();
// add(new LabelField("value... " + "4"));
ans=true;
}
catch (XmlPullParserException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (IOException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (Exception ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
}
return ans;
}
and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error
Please help me in this regard
Thanks And Regards
Pinkesh Gupta

Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end.
This 2 classess definitely helps in achieving the above code parsing.
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class ConnectionThread extends Thread
{
private boolean start = false;
private boolean stop = false;
private String url;
private String data;
public boolean sendResult = false;
public boolean sending = false;
private String requestMode = HttpConnection.POST;
public String responseContent;
int ch;
public void run()
{
while (true)
{
if (start == false && stop == false)
{
try
{
sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (stop)
{
return;
}
else if (start)
{
http();
}
}
}
private void getResponseContent( HttpConnection conn ) throws IOException
{
InputStream is = null;
is = conn.openInputStream();
// Get the length and process the data
int len = (int) conn.getLength();
if ( len > 0 )
{
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ( ( bytesread != len ) && ( actual != -1 ) )
{
actual = is.read( data, bytesread, len - bytesread );
bytesread += actual;
}
responseContent = new String (data);
}
else
{
// int ch;
while ( ( ch = is.read() ) != -1 )
{
}
}
}
private void http()
{
System.out.println( url );
HttpConnection conn = null;
OutputStream out = null;
int responseCode;
try
{
conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(requestMode);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length",Integer.toString(data.length()));
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/");
out = conn.openOutputStream();
out.write(data.getBytes());
out.flush();
responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
sendResult = false;
responseContent = null;
}
else
{
sendResult = true;
getResponseContent( conn );
}
start = false;
sending = false;
}
catch (IOException e)
{
start = false;
sendResult = false;
sending = false;
}
}
public void get(String url)
{
this.url = url;
this.data = "";
requestMode = HttpConnection.GET;
sendResult = false;
sending = true;
start = true;
}
public void post(String url, String data)
{
this.url = url;
this.data = data;
requestMode = HttpConnection.POST;
sendResult = false;
sending = true;
start = true;
}
public void stop()
{
stop = true;
}
}
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.SAXException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.ByteArrayInputStream;
import com.sts.example.ConnectionThread;
import com.sts.example.ResponseHandler;
public class DemoScreen extends MainScreen
{
private ConnectionThread connThread;
private BasicEditField response = new BasicEditField("Response: ", "");
private BasicEditField xmlResponse = new BasicEditField("xml: ", "");
private ButtonField sendButton = new ButtonField("Response");
public DemoScreen(ConnectionThread connThread)
{
this.connThread = connThread;
FieldListener sendListener = new FieldListener();
sendButton.setChangeListener(sendListener);
response.setEditable( false );
xmlResponse.setEditable( false );
add(sendButton);
add(response);
add(new SeparatorField());
add(xmlResponse);
}
public boolean onClose()
{
connThread.stop();
close();
return true;
}
private String getFieldData()
{
//{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"}
StringBuffer sb = new StringBuffer();
sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}");
return sb.toString();
}
class FieldListener implements FieldChangeListener
{
public void fieldChanged(Field field, int context)
{
StringBuffer sb = new StringBuffer("Sending...");
connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData());
while (connThread.sending)
{
try
{
Status.show( sb.append(".").toString() );
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (connThread.sendResult)
{
Status.show("Transmission Successfull");
xmlResponse.setText( connThread.responseContent );
try {
JSONObject jsonResponse = new JSONObject(connThread.responseContent);
JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject result = (JSONObject)jsonArray.get(i);
add(new LabelField("OutputCode"+result.getString("OutputCode")));
add(new LabelField("OutputDescription"+result.getString("OutputDescription")));
}
}
catch (JSONException e)
{
add(new LabelField(e.getMessage().toString()));
e.printStackTrace();
}
}
else
{
Status.show("Transmission Failed");
}
}
}
}

Related

Get posted file over HTTP Listener in c#

I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:8080").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
showPostedData(con.Request);
con.Response.StatusCode = (int)HttpStatusCode.NotFound;
string data = "Uploaded successful";
byte[] output = Encoding.ASCII.GetBytes(data);
con.Response.ContentType = "text/html";
con.Response.ContentLength64 = output.Length;
con.Response.OutputStream.Write(output , 0, output.Length );
}
}
public static void showPostedData(HttpListenerRequest request){
if (!request.HasEntityBody)
{
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string text;
if (request.ContentType != null)
{
text = reader.ReadToEnd();
}
Console.WriteLine( text );
}
My client html form has input box named file: <input type="file" name"file">
In the console output is like that :
file='Path of Choosed file not a file'
So How i get POSTED files and copy them to upload directory..?
Sorry for my english and thanks in advance...
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:80").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
var values = new HttpNameValueCollection(ref con);
try
{
Console.WriteLine(values.Files["file"].FileName);
File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default);
}
catch (Exception tr)
{
}
}
}
class HTTPFormData
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
}
public HTTPFormData(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}

self hosted pushsharp - Events_OnNotificationSendFailure Failure: There were not enough free threads in the ThreadPool to complete the operation

i my PushSharp service is self hosted in windows service,
but after a short while it always throws:
Events_OnNotificationSendFailure
- the exception is "There were not enough free threads in the ThreadPool to complete the operation". what is the proper way to do that?
public partial class PushNotificationService : ServiceBase
{
private static bool flagNotification = true;
static PushService push;
protected override void OnStart(string[] args)
{
SetPushService();
//start console service worker
Thread t = new Thread(NotificationServiceWorker);
t.IsBackground = true;
t.Start();
}
private static void NotificationServiceWorker()
{
try
{
int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
while (flagNotification)
{
try
{
/// get IosPushNotificationService
IosPushNotificationService pns = new IosPushNotificationService();
/// Get The New Notification from db
List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();
if (notificationToSend != null && notificationToSend.Count > 0)
{
SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
}
Thread.Sleep(sendNotificationTimeGap);
}
catch (Exception ex)
{
CustomError.Error("error in flagNotification loop", ex);
}
}
}
catch (Exception ex)
{
CustomError.Error("error in NotificationServiceWorker", ex);
}
}
private static void SetPushService()
{
push = new PushService();
push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
string androidPackage = ConfigurationManager.AppSettings["androidPackage"];
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });
string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
var appleCert = File.ReadAllBytes(appleCertificates);
var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;
push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));
}
}
Don't use thread instead you can use timer like this
protected override void OnStart(string[] args)
{
NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);
if (oNotificationComponent ==null)
oNotificationComponent = new NotificationComponent();
Heading
try
{
if (StartAppleNotificationService())
StartTimer();
}
catch (Exception ex)
{
NotificationServiceEventLog.WriteEntry(ex.Message);
}
base.OnStart(args);
}
private bool StartAppleNotificationService() {
bool IsStarted = false;
try
{
if (oPushService == null)
oPushService = new PushService();
NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
var settings = new ApplePushChannelSettings(true, appleCert, "123456");
oPushService.StartApplePushService(settings);
IsStarted = true;
}
catch (Exception ex)
{
throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
}
return IsStarted;
}
private bool StartTimer() {
try
{
Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
MyTimer = new Timer();
MyTimer.Interval += (1)*(60)*(1000);
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
}
catch (Exception ex) {
throw ex;
}
return true;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
string SentNotificationIDz = "";
try
{
MyTimer.Enabled = false;
string szConnectionString = #"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin#321";
//ConfigurationManager.AppSettings["connString"];
lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);
foreach (NotificationModel oNotificationModel in lNotifictaion)
{
SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
if (SentNotificationIDz == null)
SentNotificationIDz += oNotificationModel.Oid;
else
SentNotificationIDz += "," + oNotificationModel.Oid;
}
oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
MyTimer.Enabled = true;
}
catch (Exception ex) {
throw ex;
}
//
}
private void SendNotification(string p_szDeviceToken,string p_szAlert)
{
try
{
oPushService.QueueNotification(NotificationFactory.Apple()
.ForDeviceToken(p_szDeviceToken)
.WithAlert(p_szAlert)
.WithBadge(2)
.WithSound("default")
.WithExpiry(DateTime.Now.AddDays(1))
);
}
catch (Exception ex)
{
throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
}
}

how to upload audio to server: Blackberry

I'm trying to upload an .amr file to the server. My Code as follows:
private static void uploadRecording(byte[] data) {
byte[] response=null;
String currentFile = getFileName(); //the .amr file to upload
StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
connectionStr.append(getString());
PostFile req;
try {
req = new PostFile(connectionStr.toString(),
"uploadedfile", currentFile, "audio/AMR", data );
response = req.send(data);
} catch (Exception e) {
System.out.println("====Exception: "+e.getMessage());
}
System.out.println("Server Response : "+new String(response));
}
public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send(byte[] fileBytes) throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream(); // <<< EXCEPTION HERE!!!
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
System.out.println("====Exception : "+e1.getMessage());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
}
Highlighted above is the code line which throws the exception: Not Connected.
Can somebody tell me what can be done to correct this? Thanks a lot.
Updated:
public static String getString()
{
String connectionString = null;
String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
else
{
ServiceBook sb = ServiceBook.getSB();
net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null)
{
connectionString = ";deviceside=true;ConnectionUID="+uid;
}
else
{
// the carrier network
if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the
// carrier's
// TCP network
System.out.println("No Uid");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier
// BIBS
// request
System.out.println("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="
+ carrierUid + ";ConnectionType=mds-public";
}
}
//(BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging
// the user unnecessarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be
// reachable.
else {
System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
}
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {
try {
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals(
"ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
} catch (Exception e) {
System.out.println("====Exception : "+e.toString());
}
return null;
}

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();
}
}
}

J2ME, Nokia, HttpConnection

This code works fine on SonyEricsson and Motorola cellphones, but on Nokia it either fails at the beginnig not making any request at all or returns empty response, depending on model.
HttpConnection hc = null;
InputStream is = null;
InputStreamReader isr = null;
String result = "";
try
{
hc = (HttpConnection) Connector.open(url);
int rc = hc.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
{
throw new IOException(hc.getResponseMessage());
}
is = hc.openInputStream();
isr = new InputStreamReader(is, "utf-8");
int ch;
while ((ch = is.read()) != -1)
{
result += (char) ch;
}
}
finally
{
if (is != null)
{
is.close();
}
if (hc != null)
{
hc.close();
}
}
return result;
Tried different codes with byte buffers, streams, etc, result is always the same. What's the problem?
try it
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class Transport {
public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;
static {
if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
BUFFER_LENGTH = 1024;
USE_FLUSH = true;
}
}
public static String SESSION_COOKIE = null;
private static int rnd = 1;
private static final String request(String url, String method, Hashtable params) throws IOException {
HttpConnection conn = null;
DataOutputStream dos = null;
InputStream in = null;
try {
String encodedParams = null;
if (params != null && params.size() > 0) {
encodedParams = getEncodedParams(params);
}
if (method == null) {
if (encodedParams.length() < 2000) {
method = "GET";
} else {
method = "POST";
}
}
method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;
if (method.equalsIgnoreCase(HttpConnection.GET)) {
if (encodedParams != null) {
url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
encodedParams = null;
}
url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
}
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
if (conn == null) {
throw new IOException("HttpConnection is null, please check Access Point configuration");
}
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (SESSION_COOKIE != null) {
conn.setRequestProperty("Cookie", SESSION_COOKIE);
}
byte[] buff = new byte[BUFFER_LENGTH];
if (encodedParams != null) {
byte[] bytes = encodedParams.getBytes("UTF-8");
String lengthStr = bytes.length + "";
conn.setRequestProperty("Content-Length", lengthStr);
dos = conn.openDataOutputStream();
if (dos == null) {
throw new IOException("OutputStream is null, please check Access Point configuration");
}
for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
if (Transport.BUFFER_LENGTH == 1) {
dos.writeByte(bytes[i]);
} else {
int count = Math.min(Transport.BUFFER_LENGTH, l - i);
System.arraycopy(bytes, i, buff, 0, count);
dos.write(buff, 0, count);
}
if (Transport.USE_FLUSH) {
dos.flush();
}
}
dos.flush();
try {
dos.close();
} catch (IOException ex) {
}
}
String setCookie = conn.getHeaderField("Set-Cookie");
if (setCookie != null) {
int ind1 = setCookie.indexOf("JSESSIONID=");
if (ind1 > -1) {
int ind2 = setCookie.indexOf(";", ind1);
SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
}
}
in = conn.openInputStream();
if (in == null) {
throw new IOException("InputStream is null, please check Access Point configuration");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = in.read(buff);
while (n > -1) {
baos.write(buff, 0, n);
n = in.read(buff);
}
baos.flush();
baos.close();
String response = new String(baos.toByteArray(), "UTF-8");
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
return response;
} finally {
try {
dos.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
}
}
public static String getEncodedParams(Hashtable params) throws IOException {
String str = "";
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
Object value = params.get(name);
if (value == null || name == null) {
continue;
}
str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
}
if (str.length() > 1) {
str = str.substring(1);
}
return str;
}
}
I am not sure if this will work for you but I had a similar problem and found that specifying a port number made it work (on some older Nokia models). i.e convert:
http://www.mysite.com/my_page.html
to:
http://mysite.com:80/my_page.html

Resources