How to increase timeout when calling webservice in windows phone app? - windows-phone-8

I am developed one windows phone app.but app was crashed due to timeout exception.how to handle this timeout exception.please help me.below is my code:
public async void Login()
{
var client = new NewReloadApp.JsonWebClient();
var resp = await client.DoRequestAsync(Url.weburl + "Validateuser_v2?Emailid=" + Emailid.Text + "&Password=" + password.Password + "&DeviceID=" + deviceid + "&PlatformID=7&DeviceToken=windowsReload&Mobilemodel=nokia&Appversion=1.4.14&MobileOS=windows");
string result = resp.ReadToEnd();
JObject obj = JObject.Parse(result);
}
I am not using any httpwebrequest method.in the above code I try to set timeout property but I could not get any timeout method.please help me how to set timeout for the above code.
below is my jsonwebclient class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace NewReloadApp
{
class JsonWebClient
{
public async Task<T> DoRequestJsonAsync<T>(WebRequest req)
{
var ret = await DoRequestAsync(req);
var response = await ret.ReadToEndAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
}
public async Task<T> DoRequestJsonAsync<T>(string uri)
{
var ret = await DoRequestAsync(uri);
var response = await ret.ReadToEndAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
}
public async Task<System.IO.TextReader> DoRequestAsync(WebRequest req)
{
var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res => ((HttpWebRequest)res.AsyncState).EndGetResponse(res), req);
var result = await task;
var resp = result;
var stream = resp.GetResponseStream();
var sr = new System.IO.StreamReader(stream);
return sr;
}
public async Task<System.IO.TextReader> DoRequestAsync(string url)
{
HttpWebRequest req = HttpWebRequest.CreateHttp(url);
req.AllowReadStreamBuffering = true;
var tr = await DoRequestAsync(req);
return tr;
}
}
}

Use a CancellationToken:
I dint try but it may help you.
public async Task<System.IO.TextReader> DoRequestAsync(string url)
{
CancellationTokenSource ct= new CancellationTokenSource(2000); //2
HttpWebRequest req = HttpWebRequest.CreateHttp(url);
req.AllowReadStreamBuffering = true;
var tr = await DoRequestAsync(req).AsTask(ct.Token);;
return tr;
}
as mentioned in this post

Related

how to read data from MYSQL in flutter

i want to read all data from table "add_news".the code is given below
var db = Mysql();
void _getnews() async{
await db.getConnection().then((conn) async{
// the select query
String sql = "select * from add_news;";
await conn.query(sql).then((results) {
for(var row in results){
print(row);
}
});
conn.close();
});
}
can some please tell me how can i do this??
If you want to show inside your flutter app, then try this.
Display it using future builder. And also make a Model of your database
Repo Link
Future<List<Profiles>> getSQLData() async {
final List<Profiles> profileList = [];
final Mysql db = Mysql();
await db.getConnection().then((conn) async {
String sqlQuery = 'select email, password from users';
await conn.query(sqlQuery).then((results) {
for (var res in results) {
final profileModel =
Profiles(email: res["email"], password: res["password"]);
profileList.add(profileModel);
}
}).onError((error, stackTrace) {
print(error);
return null;
});
conn.close();
});
return profileList;
}

Cannot read property 'getAllProducts' of undefined

The problem is in db.js because it's trying to load something from db which does not exist.
In my index.js page:
const dataB = require("./db").getAllProducts;
app.get('/scrapper', async (req, res) => {
const Myobjects = await dataB.getAllProducts();
res.send(Myobjects)
})
And in my db.js page:
async function getAllProducts() {
const connection = await getConnection();
const pageRepo = connection.getRepository(Crawlers);
const pages = await pageRepo.find();
connection.close();
return pages;
}
async function InsertScrappedData(texte, image, price){
const connection = await getConnection();
const page = new Crawler();
page.texte = texte;
page.image = image;
page.price = price;
const crawlertrepo=connection.getRepository(Crawlers);
const res=await crawlertrepo.save(Crawlers);
Console.log('saved',res);
const Allpages = await crawlertrepo.find();
connection.close();
return Allpages;
}
Exporting my functions
module.exports = [
getAllProducts,
InsertScrappedData
]
module.exports is an object type, not an array, so you need to use curly brackets when assigning it.
module.exports = {
getAllProducts,
InsertScrappedData
}
Relevant documentation
This is actually a condensed form of assigning the getAllProducts function to the getAllProducts key of a new object and then assigning that object to module.exports
// Equivalent but unnecessarily verbose
module.exports = {
getAllProducts: getAllProducts,
InsertScrappedData: InsertScrappedData
}

Unable to fetch existing db file in flutter

I'm new to flutter and sqflite. For a project I was trying to use an existing database. I have kept my db file in a assest folder. When I run it on my emulator it shows nothing. Can someone tell me where did I do wrong? It's exactly not showing any error, but it's showing something like:
HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1
ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3
ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem
ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2
ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache
ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3
GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr
ANDROID_EMU_gles_max_version_3_0
W/OpenGLRenderer( 5874): Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without..
class DatabaseHelper {
static final _databaseName = "lastRandomdb.db";
static final _databaseVersion = 1;
static final table = "Randomdb";
static final columnEmail = "email";
static final columnName = "name";
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (database != null) return database;
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
var databasepath = await getDatabasesPath();
String path = join(databasepath, _databaseName);
//check existing
var exists = await databaseExists(path);
if (!exists) {
print("copy database start");
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {
//copy
ByteData data = await rootBundle.load(join("assets", _databaseName));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
//write
await File(path).writeAsBytes(bytes, flush: true);
}
} else {
print("opening exsisting database");
}
return await openDatabase(path, version: _databaseVersion);
}
//crud
Future<List<Contact>> getAllContacts() async {
Database db = await instance.database;
final List<Map<String, dynamic>> map = await db.query(table);
return List.generate(map.length, (index) {
return Contact.fromMap(map[index]);
});
}
Future<int> getCount() async {
Database db = await instance.database;
return Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT(EMAIL) FROM $table"));
}
}
this is my model file
final String COL_NAME = "name";
final String COL_EMAIL = "email";
class Contact {
String name, email;
Contact({this.name, this.email});
Contact.map(dynamic obj1) {
this.name = obj1['NAME'];
this.email = obj1['EMAIL'];
}
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
//method
COL_NAME: name,
COL_EMAIL: email,
};
return map;
}
Contact.fromMap(Map<String, dynamic> map) {
//named constructor to return emoloyee model obj
name = map[COL_NAME];
email = map[COL_EMAIL];
}
#override
String toString() {
return 'Contact{name: $name, email: $email}';
}
}
Ok let's evaluate your _initDatabase line by line
first you create the path and check if it exists
var databasepath = await getDatabasesPath();
String path = join(databasepath,_databaseName);
//check existing
var exists = await databaseExists(path);
Seems good, then if it doesn't exist you want to copy it from the AssetFolder
try{
await Directory(dirname(path)).create(recursive: true);
}catch(_){
//copy
ByteData data = await rootBundle.load(join("assets",_databaseName));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
//write
await File(path).writeAsBytes(bytes, flush: true);
}
you try to create the Directory in the path (I don't know what method is dirname but I will believe it returns the path). If nothing fails then it will run
return await openDatabase(path,version: _databaseVersion);
It will enter the catch and copy the db from asset only if the creation of the Directory throws an error, is there a condition when it will fail that? If not then it will never try to copy the db. If you're sure that creating a Directory won't throw an error you should just run the code without the try catch
await Directory(dirname(path)).create(recursive: true);
ByteData data = await rootBundle.load(join("assets",_databaseName));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes, flush: true);

nodejs- req.body not parsing correctly for arrays and embedded object

I am using nodejs(expressjs) as server. I have android app that sends json request to server. I have mongoose schema defined like this
var mongoose=require('mongoose'),
Schema=mongoose.Schema;
var actSchema= new Schema({
actfees: {type: Number},
actage: {
from: {type: Number},
to: {type: Number}
},
actbatches: [{
days: [String],
starttime: {type: String},
endtime: {type: String}
}]
});
The incoming request looks like this
{ actId: '28',
actage: '{from=3.0, to=40.0}',
actbatches: '[{days=[Tue, Wed, Thu, Fri], endtime=17:00, starttime=16:00}]',
actdescr: 'Learn 5 different style of swimming',
actfees: '4000'
}
See actage and actbatches parameters. They are treated as strings instead of array (in case of actbatches) or embedded objects(in case of age).
My app.js has following lines
var express = require('express')
, mongoose = require('mongoose').set('debug', true)
, bodyParser = require('body-parser');
var app = express();
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
//CLIENT CODE
BEAN Classes:
public class ActBean {
private String actfees;
private ActAgeBean actage;
private ArrayList<String> days;
getters & setters....
}
public class ActAgeBean {
private int from;
private int to;
//getters & setters...
}
Android Application Class:
private void Save(ActBean actbean)
{
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> actMap = new Gson().fromJson(new Gson().toJson(actbean), type);
post(url, actMap);
}
The post method:
public String post(String url, Map<String, Object> data) throws Exception {
HttpPost request = new HttpPost(url);
List<NameValuePair> nameValuePairs = setParams(data);
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode > 300){
throw new Exception("Error executing POST request! Received error code: " + response.getStatusLine().getStatusCode());
}
//return new JSONObject(readInput(response.getEntity().getContent()));
return readInput(response.getEntity().getContent());
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
setParams:
private List<NameValuePair> setParams(Map<String, Object> data){
List<NameValuePair> nameValuePairs = null;
if (data != null && !data.isEmpty()) {
nameValuePairs = new ArrayList<NameValuePair>(2);
Iterator<String> it = data.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
Object value = data.get(name);
nameValuePairs.add(new BasicNameValuePair(name, value.toString()));
}
}
return nameValuePairs;
}
Please suggest how can I make sure req.body correctly identifies array and embedded object.

ApplicationData.Current.LocalFolder.GetFoldersAsync(folderName) return ERROR COM call

I have this code for Windows Phone 8 app on VS 2013:
public async Task<bool> DoesFileExists(string fileName)
{
try
{
StorageFolder localFolder= ApplicationData.Current.LocalFolder;
var myFolder = await localFolder.GetFolderAsync(folderName);
StorageFile file = await myFolder .GetFileAsync(fileName);
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.Source);
return false;
}
}
This code always get Error HRESULT E_FAIL has been returned from a call to a COM component and when I tried this:
var playerFolder = await localFolder.GetFoldersAsync();
foreach (var f in playerFolder)
if (f.Name == folderName)
{
var files = await f.GetFileAsync(fileName);
}
localFolder.GetFoldersAsync() works fine but crash on var files = await f.GetFileAsync(fileName)
Any help?