How to get data from web service in window phone 8 - web-services

private void GetData()
{
StudentWS.StudentWSSoapClient MyClient = new StudentWS.StudentWSSoapClient();
MyClient.GetStudentCompleted +=MyClient_GetStudentCompleted;
MyClient.GetStudentAsync(CONNECTION_KEY);
}
void MyClient_GetStudentCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
}
How to get the data from the method in webservice

Related

How to get header value in UploadStringCompletedEventHandler method ASP.NET (Web API Service using HttpClient)

In My Windows Phone 8 App, I create WebClient object and initiate the with UploadStringAsync. and Create webClientLogin.UploadStringCompleted using UploadStringCompletedEventHandler.
WebClient webClientLogin = new WebClient();
webClientLogin.Headers["content-type"] = "application/json";
webClientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(webClientUploadStringCompleted);
webClientLogin.UploadStringAsync(new Uri(URL + "LogIn"), "POST", stockiestData);
Here stockiestData is Encoded Using Encoding.UTF8
I Get response as well.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var logindetails = JsonConvert.DeserializeObject<LogResponse>(e.Result);
}
But I need to get the Header in this above method (webClientUploadStringCompleted).
I send the header like follows HttpContext.Current.Response.AppendHeader("Msg","Checked");
This response created in WebApi
How to get this?
Able to get header values using sender Object in the following method.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
}
We have to cast this object as WebClient.
Following method shows how to send in WebApi
[HttpPost]
[ActionName("LogIn")]
public dynamic LogIn(List<Student> Student, HttpRequestMessage request)
{
if (Student!= null)
{
HttpContext.Current.Response.AppendHeader("Msg", "Resived");
}
Following code shows you how to get header value from Windows phone 8
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
WebClient web = (WebClient)sender;
WebHeaderCollection myWebHeaderCollection = (WebHeaderCollection)web.ResponseHeaders;
var v = web.ResponseHeaders["Msg"];
}

how to get contacts list from google glass using GDK

I'm implement Google Glass app.
I want to get contacts list from google glass using GDK.
I already tried contacts Api v3 (ContactsService)
but i failed because -
i can't scrolling & tapping(click) pop-up (OK Button) after glass update XE16
-> run to android phone is ok.
i tried
mirror api. device OAuth.... -> no example.. i don't know how...
if you have sample code, As it is also upload. Would you? I'd appreciate that.
here is my code.
public class MainActivity extends Activity
{
private Account[] accounts;
private AccountManager mManager;
private ContactsService mService;
private URL feedUrl;
private final String url = "https://www.google.com/m8/feeds/contacts/default/full";
private final String ACCOUNTS_TYPE = "com.google";
private final String AUTH_TOKEN_TYPE = "cp";
private String mToken;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mManager = AccountManager.get(this);
accounts = mManager.getAccountsByType(ACCOUNTS_TYPE);
Log.d("account", ""+accounts[0]);
mManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>()
{
public void run(AccountManagerFuture<Bundle> future)
{
try
{
mToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
GetTask task = new GetTask();
task.execute(mToken);
}
catch (OperationCanceledException e)
{
e.printStackTrace();
}
catch (AuthenticatorException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}, null);
}
public void createService(String token) throws IOException, ServiceException
{
mService = new ContactsService("contacts_list");
mService.setUserToken(token);
feedUrl = new URL(url);
ContactFeed resultFeed = (ContactFeed)mService.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) getContacts(entry);
}
private class GetTask extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params)
{
try
{
String token = "";
if(params != null)
{
for(String s : params) token += s;
}
createService(token);
}
catch (ServiceException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
public void getContacts(ContactEntry entry) throws ServiceException, IOException
{
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullName = name.getFullName().getValue();
Log.d("name", fullName);
}
}
else Log.d("name", "no name");
if (entry.hasPhoneNumbers())
{
for (PhoneNumber phone : entry.getPhoneNumbers())
{
String phoneNum = phone.getPhoneNumber();
Log.d("phone", phoneNum);
}
}
else Log.d("phone", "no phone");
}
}

Obtain List from asynctask

public class GetAllEggs extends AsyncTask<Void, Void, List<Egg>> {
List<Egg> eggs;
Egg eg;
JSONParser jParser = new JSONParser();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Egg> doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// Thread.sleep(5000);
/*** fetch data from server and save in the local db ***/
String url = Utils.alleggsofuser;
JSONObject jObject = jParser.makeHttpRequest(url, "GET", null);
//Log.d(DEBUG_TAG, "news response: " + response);
JSONArray categoryArray = new JSONArray(
jObject.getString("categories"));
for (int i = 0; i < categoryArray.length(); i++) {
/* make entries in the db */
JSONObject Category = categoryArray.getJSONObject(i);
eg=new Egg();
eg.setEggid(Category.getInt("eggid"));
eg.setApp_user_id(Category.getInt("app_user_id"));
eg.setEgg_query(Category.getString("egg_query"));
eg.setEgg_date_time(null);
eggs.add(eg);
/**/
}
/**/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// pBar.cancel();
}
return eggs;
}
protected void onPostExecute(List<Egg> result) {
// TODO Auto-generated method stub
}
List<Egg> eggs=new ArrayList();
new GetAllEggs().execute(eggs);
i want eggs to grab data returned by GetAllEggs().execute().
So that i can Use the eggs returned, in another class where it can be displayed.
I am trying to assign the data returned to a list in the new class.
I cannot carry out the operation in postexecute() because of the structure of the program
Instead of passing from post execute to ui thread i can call a ui thread in post execute using
runOnUiThread(new Runnable() { public void run() {}});

how to use external (free available or paid) web services

how to use the external web service (paid or free) in the application.
For example:
Here is the code snippet from one of the site (http://debugmode.net/2010/09/10/consuming-wcf-rest-service-in-asp-net-web-site/) which is using the self created service. But instead of it if one has to use the external service how should be proceeded?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
WebClient proxy = new WebClient();
byte[] abc = proxy.DownloadData((new Uri("http://localhost:4567/Service1.svc/GetData")));
Stream strm = new MemoryStream(abc);
DataContractSerializer obj = new DataContractSerializer(typeof(string));
string result = obj.ReadObject(strm).ToString();
TextBox1.Text = result;
}

uploading file from backberry to web service = JVM error 104 Uncaught NullPointerException?

I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code