Client cannot connect to Wcf Service - c#

I would like to upload file to wcf service from android. The service already open but every time connect to the service it fail, stuck at .connect().
After few minutes it throw Exception:
failed to connect to /10.16.2.56 (port 80): connect failed: ETIMEDOUT
(Connection timed out)
I configure my wcf side almost same as this, please help!
Here my code of android :
try
{
Bitmap bm = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost("http://10.16.2.37/wcf3/service1.svc/GetStream");
ByteArrayBody bab =new ByteArrayBody(data,"001.jpg");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("uploaded", bab);
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
System.out.println("2");
HttpResponse response = httpClient.execute(postRequest);
System.out.println("response");
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
System.out.println("Response: " + s);
}
}
catch (Exception e)
{
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}

Its worked for me.
package databaseconnect.databaseconnect;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class MainActivity extends Activity {
private static String SOAP_ACTION = "http://example.com/IService1/InsertData";
private static String NAMESPACE = "http://example.com/";
private static String METHOD_NAME = "InsertData";
private static String URL = "http://example.com/Service1.svc?wsdl";
Button Save,Clear;
EditText name,mobile,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText);
mobile = (EditText) findViewById(R.id.editText2);
email = (EditText) findViewById(R.id.editText3);
Save=(Button)findViewById(R.id.button);
Clear=(Button)findViewById((R.id.clear));
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
Clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name.setText("");
mobile.setText("");
email.setText("");
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params)
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name", name.getText().toString());
request.addProperty("mobile", mobile.getText().toString());
request.addProperty("email", email.getText().toString());
//request.addProperty("name", "testuser");
// request.addProperty("mobile", "123456789");
//request.addProperty("email", "sample#google.com");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
envelope.setOutputSoapObject(request);
String res=null;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,180000);
androidHttpTransport.debug=true;
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (Exception e)
{
name.setText(e.toString());
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

TCP-IP Connection Android App to C# Server

so what im actually trying to do is to comunicate with a DMX-Interface pluged to a PC/Host via an Xamarin Android App.
Allready got my Server running, works also with an console client i wrote first. So now I wrote the app,using the same Way as before, with a TCPClient and then writing the data via a stream.
Because I'm running the app in the emulator I use as IP 10.0.2.2 to connect, but I cannot establish a connection. The App crashes or I get a timeout exeption. Been trying and researching now for two days and now i'm desperate, so I attach my code here, hope anyone can help
Thanks, Johannes
App:
public class MainActivity : Activity
{
public Stream Stream;
TcpClient Client = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
//adding control elements from Resource.Layout.Main
Button at = FindViewById<Button>(Resource.Id.at);
Button enter = FindViewById<Button>(Resource.Id.enter);
Button thru = FindViewById<Button>(Resource.Id.thru);
Button all = FindViewById<Button>(Resource.Id.all);
Button one = FindViewById<Button>(Resource.Id.one);
Button two = FindViewById<Button>(Resource.Id.two);
Button three = FindViewById<Button>(Resource.Id.three);
Button four = FindViewById<Button>(Resource.Id.four);
Button five = FindViewById<Button>(Resource.Id.five);
Button six = FindViewById<Button>(Resource.Id.six);
Button seven = FindViewById<Button>(Resource.Id.seven);
Button eight = FindViewById<Button>(Resource.Id.eight);
Button nine = FindViewById<Button>(Resource.Id.nine);
Button zero = FindViewById<Button>(Resource.Id.zero);
Button comma = FindViewById<Button>(Resource.Id.comma);
Button connect = FindViewById<Button>(Resource.Id.connect);
Button clear = FindViewById<Button>(Resource.Id.clear);
at.Click += (o, e) =>
{
UpdateCmdLine("#");
};
clear.Click += (o, e) =>
{
FlushCmdLine();
};
enter.Click += (o, e) =>
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
ProcessData(cmdLine.Text);
FlushCmdLine();
};
thru.Click += (o, e) =>
{
UpdateCmdLine("/");
};
all.Click += (o, e) =>
{
UpdateCmdLine("#");
};
one.Click += (o, e) =>
{
UpdateCmdLine("1");
};
two.Click += (o, e) =>
{
UpdateCmdLine("2");
};
three.Click += (o, e) =>
{
UpdateCmdLine("3");
};
four.Click += (o, e) =>
{
UpdateCmdLine("4");
};
five.Click += (o, e) =>
{
UpdateCmdLine("5");
};
six.Click += (o, e) =>
{
UpdateCmdLine("6");
};
seven.Click += (o, e) =>
{
UpdateCmdLine("7");
};
eight.Click += (o, e) =>
{
UpdateCmdLine("8");
};
nine.Click += (o, e) =>
{
UpdateCmdLine("9");
};
zero.Click += (o, e) =>
{
UpdateCmdLine("0");
};
comma.Click += (o, e) =>
{
UpdateCmdLine(",");
};
connect.Click += (o, e) =>
{
try
{
TextView ip = FindViewById<TextView>(Resource.Id.ipField);
TextView port = FindViewById<TextView>(Resource.Id.portField);
TextView connectionStatus = FindViewById<TextView>(Resource.Id.connectedStatus);
Client = new TcpClient("10.0.2.2", 4711);
connectionStatus.Text = "Connected";
}
catch (System.Exception)
{
}
};
//implementing click functions
}
public void UpdateCmdLine(string update)
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text += update;
}
public void FlushCmdLine()
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text = "";
}
public int[] GetData(string channel, string value)
{
int[] data = new int[] {Int32.Parse(channel), Int32.Parse(value)};
return data;
}
public void SendData(int channel, int data)
{
if (Client.Connected)
{
Stream = Client.GetStream();
byte[] outgoingBytes = new byte[] {Convert.ToByte(channel),Convert.ToByte(data)};
Stream.Write(outgoingBytes,0,outgoingBytes.Length);
}
}
public void ProcessData(string cmdLine)
{
string[] divideStackedOps = cmdLine.Split(',');
foreach (string s in divideStackedOps)
{
if (s.Contains("/"))
{
string[] dividedThru = s.Split('/');
int channel1 = Int32.Parse(dividedThru[0]);
string[] dividedAt = dividedThru[1].Split('#');
int channel2 = Int32.Parse(dividedAt[0]);
int value = Int32.Parse(dividedAt[1]);
for (int e = channel2; e >= channel1; e--)
{
SendData(e, value);
}
}
else if (s.Contains("#"))
{
string[]dividedAll = s.Split('#');
int value = Int32.Parse(dividedAll[1]);
for (int e = 100; e > 0; e--)
{
SendData(e, value);
}
}
}
}
}
}
Server
public class DmxInterface
{
[DllImport("K8062D.dll")]
public static extern void StartDevice();
[DllImport("K8062D.dll")]
public static extern void SetData(int channel, int data);
[DllImport("K8062D.dll")]
public static extern void StopDevice();
[DllImport("K8062D.dll")]
public static extern void SetChannelCount(int count);
}
class Program
{
private static TcpListener Listener;
private static ArrayList Threads = new ArrayList();
public static Boolean ServerStopped;
public static void Main()
{
DmxInterface.StartDevice();
DmxInterface.SetChannelCount(10);
//Initialize Listener, start Listener
int port = 4711;
IPAddress ip = IPAddress.Parse("127.0.0.1");
Listener = new TcpListener(ip, port);
Listener.Start();
Console.WriteLine("Creating new listener on: "+ip+":"+port);
//Initialize MainServerThread, start MainServerThread
Console.WriteLine("Starting MainThread");
Thread mainThread = new Thread(Run);
mainThread.Start();
Console.WriteLine("Done");
while (!ServerStopped)
{
Console.WriteLine("Write 'stop' to stop Server...");
String cmd = "";
cmd = Console.ReadLine();
if (cmd.ToLower().Equals("stop"))
{
Console.WriteLine("stopping server");
ServerStopped = true;
}
else
{
Console.WriteLine("unknow command: " + cmd);
}
}
EndThreads(mainThread);
}
public static void EndThreads(Thread mainThread)
{
//stopping MainThread
mainThread.Abort();
Console.WriteLine("MainThread stopped");
//stopping all Threads
for (IEnumerator e = Threads.GetEnumerator(); e.MoveNext();)
{
//Getting next ServerThread
Console.WriteLine("Stopping the ServerThreads");
ServerThread serverThread = (ServerThread)e.Current;
//Stop it
serverThread.Stop = true;
while (serverThread.Running)
{
Thread.Sleep(1000);
}
}
//Stopping Listener
Listener.Stop();
Console.WriteLine("listener stopped");
Thread.Sleep(5000);
Console.Clear();
}
//opening a new ServerThread
public static void Run()
{
while (true)
{
Console.WriteLine("Listener waiting for connection wish");
//waiting for incoming connection wish
TcpClient client = Listener.AcceptTcpClient();
Threads.Add(new ServerThread(client));
}
}
}
class ServerThread
{
public bool Stop;
public bool Running;
private TcpClient client;
public ServerThread(TcpClient client)
{
this.client = client;
//starting new thread with run() function
Console.WriteLine("Starting new ServerThread");
new Thread(new ThreadStart(Run)).Start();
}
//threaded function
public void Run()
{
Stream stream = null;
Boolean gotstream = false;
Console.WriteLine("Reading incoming Data Stream");
Running = true;
while (!gotstream)
{
//making sure stream is not null to avoid exeption
if (client.GetStream() != null)
{
//getting stream, setting flag true
stream = client.GetStream();
gotstream = true;
}
}
Boolean loop = true;
byte[] incomingValues = new byte[] {255, 255};
Boolean gotData = false;
while (loop)
{
//checking if a remote host is still connected
if (client.Connected)
{
try
{
//reading Byte Array
stream.Read(incomingValues, 0, incomingValues.Length);
gotData = true;
}
catch (Exception e)
{
//catching exeptions
Console.WriteLine("Ooops, something wrent wrogn \n" + e);
loop = false;
}
if (gotData)
{
//converting bytes to int, sending DMX Values
int channel = Convert.ToInt32(incomingValues[0]);
int value = Convert.ToInt32(incomingValues[1]);
DmxInterface.SetData(channel, value);
Console.WriteLine("Received Data... \n Channel: " + channel + " Value: " + value);
}
}
else
{
//exiting loop if connection is lost
Console.WriteLine("connection lost");
Program.ServerStopped = true;
loop = false;
}
}
}
}
}

"A socket operation failed because the destination host was down" when connecting pc to mobie device

My project is to connecting pc with mobile device using 32feet.net library.
Until Now, my solution is doing steps like:
Scanning for devices in area.
pairing with selected device .
request pairing with mobile device and when it's okay this error appear :
"A socket operation failed because the destination host was down" and I don't know why and how to overcome this problem. Any help with this problem will be appreciated.
And my solution is:
namespace Bluetooth
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
items = new List<string>();
InitializeComponent();
}
private void Connect_Click(object sender, EventArgs e)
{
if(ServerStarted )
{
updateUI("Server Already Started");
return;
}
if(rbClient.Checked)
{
//ConnectAsClient();
StartScan();
}
else
{
ConnectAsServer();
}
}
private void StartScan()
{
listBox.DataSource = null;
listBox.Items.Clear();
items.Clear();
Thread bluethoothscanthread = new Thread(new ThreadStart(scan));
bluethoothscanthread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan()
{
updateUI("Starting Scan ...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan Completed......");
updateUI(devices.Length.ToString() + "devices discovered");
foreach(BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
UpdateDeviceList();
}
private void ConnectAsServer()
{
Thread BluethoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
BluethoothServerThread.Start();
}
private void ConnectAsClient()
{
throw new NotImplementedException();
}
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
bool ServerStarted = false;
public void ServerConnectThread()
{
ServerStarted = true;
updateUI("Server Started , Waiting For Clients ");
BluetoothListener bluelistner = new BluetoothListener(mUUID);
bluelistner.Start();
BluetoothClient conn = bluelistner.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mstream = conn.GetStream();
while(true)
{
// handle server connection
try
{
byte[] Received = new byte[1024];
mstream.Read(Received, 0, Received.Length);
updateUI("Received : " + Encoding.ASCII.GetString(Received));
byte[] Sent = Encoding.ASCII.GetBytes("Hello World ");
mstream.Write(Sent, 0, Sent.Length);
}
catch(IOException exception)
{
updateUI("Client has disconnected !!! ");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate ()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0 ;
};
Invoke(del);
}
private void UpdateDeviceList()
{
Func<int> del = delegate ()
{
listBox.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceinfo;
private void listBox_DoubleClick(object sender, EventArgs e)
{
deviceinfo = devices.ElementAt(listBox.SelectedIndex);
updateUI(deviceinfo.DeviceName + "Was Selected , attempting connect");
if( pairDevice())
{
updateUI("Device Paired.....");
updateUI("Starting Connect Thread");
Thread bluethoothClientThread = new Thread(new ThreadStart(ClientconnectThread));
bluethoothClientThread.Start();
}
else
{
updateUI("Pair Failed");
}
}
private void ClientconnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("Attempting Connect");
client.BeginConnect(deviceinfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
BluetoothEndPoint bep = new BluetoothEndPoint(deviceinfo.DeviceAddress, BluetoothService.AvctpProtocol);
BluetoothClient cli = new BluetoothClient();
client.Connect(bep); // the exception throw in this line //
Stream stream = cli.GetStream();
stream.ReadTimeout = 10000;
//Stream peerStream = cli.GetStream();
// client.Connect(BluetoothAddress.Parse(items(0)), mUUID);
//client.EndConnect(result);
//while(true)
//{
// while (!ready) ;
// stream.Write(message, 0, message.Length);
//}
//streaming(result);
if(result.IsCompleted)
{
// client.EndConnect(result);
// Stream stream = client.GetStream();
// stream.ReadTimeout = 1000;
updateUI("Ya rabbbbb");
//while (!ready) ;
//stream.Write(message, 0, message.Length);
}
}
void streaming (IAsyncResult result)
{
BluetoothListener listn = new BluetoothListener(mUUID);
listn.Start();
BluetoothClient conn = listn.AcceptBluetoothClient();
Stream peerstream = conn.GetStream();
bool rightconn = peerstream.CanRead;
if(rightconn)
{
updateUI("Now you can streaming");
}
else
{
updateUI("Not Yet");
}
}
string mypin = "1234";
private bool pairDevice()
{
if(!deviceinfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceinfo.DeviceAddress, mypin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
} // End of namespace
I think I followed same example with you and of course I encountered same problem.
Rest of my codes are same with yours until "private void ClientconnectThread()" function and here is mine;
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attempting connect");
//client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
BluetoothAddress addressSeleccionado = deviceInfo.DeviceAddress;
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
BluetoothEndPoint ep = new BluetoothEndPoint(addressSeleccionado, mUUID);
client.Connect(ep);
updateUI("connected");
Stream stream = client.GetStream();
while (true)
{
byte[] received = new byte[1024];
stream.Read(received, 0, received.Length);
updateUI("received: ");
for (int i = 0; i < 15; i++)
{
updateUI(received[i].ToString());
}
if (ready)
{
ready = false;
stream.Write(message, 0, message.Length);
}
}
}
With this code I can connect the remote device and implement basic send/receive data communication. In order to my search over internet, "if this code does not fit for you", you might think that 32feet is not compatible with your bluetooth driver. (by the way my PC's OS is 64bit Win7 and I use the internal BT device of my PC )
Best regards.

How to call method in java from c# code?

I have written a method in android(java) i.e. is used to upload image to the server. I want this method to be called from c# code. How to go about i have no idea, the java code follows below?
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("imageName", imageName );
request.addProperty("base64String", compressedImageString);
//request.addProperty("compressedImageBitmap", compressedImageBitmap);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
Toast.makeText(getApplicationContext(), result.getProperty(0).toString(), Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
buttonBrowse = (Button) findViewById(R.id.buttonBrowse);
buttonBrowse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position!= null){
showPopup(MainActivity.this, position);
}
}
#SuppressWarnings("deprecation")
private void showPopup(final Activity activity, Point position) {
int popupWidth = 120;
int popupHeight = 130;
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = layoutInflater.inflate(R.layout.activity_popup, linearLayout);
popupWindow = new PopupWindow(activity);
popupWindow.setContentView(popupView);
popupWindow.setWidth(popupWidth);
popupWindow.setHeight(popupHeight);
int offset_X = 85;
int offset_Y = 5;
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAtLocation(popupView, Gravity.NO_GRAVITY, position.x + offset_X, position.y + offset_Y);
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus){
int[] location = new int[2];
buttonBrowse.getLocationOnScreen(location);
position = new Point();
position.x = location[0];
position.y = location[1];
}
public void buttonGallery_Click(View v){
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
}
public void buttonTakePhoto_Click(View v){
TakePhoto();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent){
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
selectedImageUri = intent.getData();
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
String path = selectedImageRealPath;
imageName = path.substring(path.lastIndexOf("/")+1, path.length());
imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
compressedImageString = imageCompression(selectedImageRealPath);
}
break;
case CAMERA_REQUEST:
try
{
if(resultCode == RESULT_OK){
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
compressedImageString = imageCompression(selectedImageRealPath);
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
break;
}
popupWindow.dismiss();
}
private void TakePhoto() {
ContentValues values = new ContentValues();
imageName = String.valueOf(System.currentTimeMillis());
values.put(MediaStore.Images.Media.TITLE, imageName);
selectedImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
private String imageCompression(String filePath) {
File imageFile = new File(filePath);
FileInputStream fis = null;
try
{
fis = new FileInputStream(imageFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 600, 300, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos );
byte[] b = baos.toByteArray();
String imageString = Base64.encodeToString(b, Base64.DEFAULT);
//byte[] imageByte = imageString.getBytes();
return imageString;
}
public String getRealPathFromURI(Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
}
I want to call the method on buttonBrowse from c#
You cannot call java code directly from C# code.
You can wrap java classes as COM
See the link below
http://www.rgagnon.com/javadetails/java-0045.html

How to communicate between a c# server (WinRT/Metro) and android client?

I am looking for a way to communicate either over TCP or HTTP between android and C# 2012. Here is what I have so far
JAVA CLIENT:
package com.example.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)this.findViewById(R.id.button1);
tc = (TextView) this.findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Thread th = new Thread(new Runnable() {
public void run() {
connect();
}
});
th.start();
}
});
}
private void connect() {
InetAddress[] server;
try {
server = InetAddress.getAllByName("192.168.1.100");
Socket socket = new Socket(server[0], 3975);
if (socket.isConnected()){
Log.d("connected", "connected");
}
PrintWriter w = null;
BufferedReader r = null;
w = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
w.println("test");
/*String m = null;
while ((m=r.readLine())!= null) {
w.write(m,0,m.length());
w.flush();
}*/
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
C# SERVER:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
public async void ServiceButtonClick(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
try
{
await listener.BindServiceNameAsync("3975");
lblMessage.Text = "We are listening for connections...";
}
catch (Exception ee)
{
lblMessage.Text = "Unable to bind service.. " + ee.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "We are connected to the client";
});
try
{
while (true)
{
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 1";
});
return;
}
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringlength);
if (stringLength != actualStringLength)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 2";
});
return;
}
string temp;
temp = reader.ReadString(actualStringLength);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "Client said - " + reader.ReadString(3);
});
}
}
catch (Exception e)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "ERROR: " + e.Message + " - " + e.Source + " - " + e.StackTrace;
});
}
}
}
Now when I click the button on the client, the socket is connected, but when I send data to the C# server from my phone, nothing shows up on the server. Is there anything I am doing wrong on the receiving or sending end? I am just trying to send basic strings over TCP.

WebClient async stuck

I have this code:
autoResetEvent = new AutoResetEvent(false);
clien = new WebClient();
clien.Encoding = Encoding.UTF8;
clien.DownloadDataCompleted += new DownloadDataCompletedEventHandler(clien_DownloadDataCompleted);
clien.DownloadDataAsync(new Uri("http://www.classoneequipment.com/"));
autoResetEvent.WaitOne();
void clien_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
Encoding enc = Encoding.UTF8;
myString = enc.GetString(e.Result);
autoResetEvent.Set();
}
When I run this code in a button click event - It works fine. but when I run the code from big class it gets stucked and don't arrive to the func: clien_DownloadDataCompleted.
You approach it all wrong. If you want to download 3000 or more pages you got to be a bit more efficient and not wait on the event from each download.
Implementation (just a rough draft, you have to complete it)
public class Downloader
{
ConcurrentQueue<Uri> _queue = new ConcurrentQueue<Uri>();
int _maxWorkers = 10;
long _currentWorkers = 0;
ManualResetEvent _completed;
public void Enqueue(Uri uri)
{
_queue.Enqueue(uri);
if (Interlocked.Read(_currentWorkers) < _maxWorkers)
{
// not very thread safe, but we just want to limit the workers
// within a reasonable limit. 1 or 2 more doesn't really matter.
Interlocked.Increment(_currentWorkers);
// yes, i'm a bit old fashioned.
TriggerJob();
}
}
private void TriggerJob()
{
Uri uri;
if (!_queue.TryDequeue(out uri))
{
Interlocked.Decrement(_currentWorkers);
return;
}
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.DownloadDataCompleted += DownloadDataCompleted;
client.DownloadDataAsync(uri);
}
private void DownloadDataCallback(object sender, DownloadDataCompletedEventArgs e)
{
try
{
// If the request was not canceled and did not throw
// an exception, display the resource.
if (!e.Cancelled && e.Error == null)
{
var args = new DownloadedEventArgs { uri = e.Uri, data = (byte[])e.result};
DownloadCompleted(this, args)
}
else
{
var args = new DownloadFailedEventArgs { uri = e.Uri, error = e.Error };
DownloadFailed(this, args);
}
}
catch (Exception err)
{
var args = new DownloadFailedEventArgs { uri = e.Uri, error = err };
DownloadFailed(this, args);
}
TriggerJob();
}
public event EventHandler<DownloadedEventArgs> DownloadCompleted = delegate{};
public event EventHandler<DownloadFailedEventArgs> DownloadFailed = delegate{};
}
public class DownloadedEventArgs
{
public Uri uri;
public byte[] data;
}
public class DownloadFailedEventArgs
{
public Uri uri;
public Exception error;
}
Usage:
var downloader = new Downloader();
downloader.Completed += (o,e) { Console.WriteLine("Whoohoho, completed: " + e.Uri); };
for (x = 1; x < 100000; x++)
{
downloader.Enqueue(new Uri("http://somewhere.com));
}

Categories

Resources