getting the System.Threading.Tasks.Task`1[System.Int32] error - asp.net-mvc

i am trying to convert my code to a sync but when i run it
i get in one of my vars the value "System.Threading.Tasks.Task`1[System.Int32]" instead of the expected ans
i have read most of the same questions asked in this topic but none of them helped me solved the problem
i tried to use properly the await but its isn't helped
public async Task<int> userloginAsync(string name,string pass)
{
using (SqlConnection con = new SqlConnection(#"/////:P//////"))
{
using (SqlCommand cmd = new SqlCommand("UserLoginPro"))
{
cmd.Connection = con;
cmd.CommandText = "SELECT count(id) FROM user_table where name =#name and password =#password; ";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#password", pass);
await con.OpenAsync();
var ans1 = await cmd.ExecuteScalarAsync();
var ans = ans1.ToString();
con.Close();
int res = Convert.ToInt32(ans);
con.Close();
return res;
}
}
}
its should query the mssql if there is an match to inputs(username and password)
and if there is return 1
if not 0
(in the DB there is unique usernames so it can be only one )

Related

retrieve checkbox values and mark as checked

i'm trying to retrieve options from database to checkbox and if it has the same product ID it has to be checked by default
this is the insert code to database
for (int i = 0; i < ddlcaroptions.Items.Count; i++)
{
if (ddlcaroptions.Items[i].Selected == true)
{
Int64 PCarOptionID = Convert.ToInt64(ddlcaroptions.Items[i].Value);
SqlCommand cmd2 = new SqlCommand("insert into tblCarOptionQuant values('" + PID + "','" + PCarOptionID + "')", con);
cmd2.ExecuteNonQuery();
}
}
it works fine now i want to edit this checkbox and update database
now i bind the checkbox from another table that has name and values
SqlCommand cmd = new SqlCommand("select * from tblCarOption", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
ddlcaroptions.DataSource = dt;
ddlcaroptions.DataTextField = "CarOptionNameAR";
ddlcaroptions.DataValueField = "CarOptionID";
ddlcaroptions.DataBind();
}
now i have all the options but i want the selected values to be the ones that user already checked before and saved in tblCarOptionQuant table,
i tried to get the values by this command
using (SqlCommand getselectedop = new SqlCommand("select PCarOptionID from tblCarOptionQuant where PID = " + PID + "", con))
its okay but now what can i do to set selected values from this command result !??
you can use FindByValue to get the specific item and set it to selected, refer the code below
string value = "SomeValue";
var item = ddlcompany.Items.FindByValue(value);
if (item != null)
item.Selected = true;
the problem is when you retrieve data and convert to string you get only 1st row so i used StringBuilder to build 1 string has all rows in table :)
!! Attention !!
before you use this code make sure you bind your checkbox with all the values that user checked or not ,, then use this code to get the options that selected before (by the user)
using (SqlCommand getselectedop = new SqlCommand("RetrieveCarOptions", con))
{
getselectedop.CommandType = CommandType.StoredProcedure;
getselectedop.Parameters.AddWithValue("#PID", Convert.ToInt64(Request.QueryString["PID"]));
con.Open();
using (SqlDataReader reader = getselectedop.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
if (reader.HasRows)
{
if (sb.Length > 0) sb.Append("___");
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
if (reader.GetValue(i) != DBNull.Value)
sb.AppendFormat("{0}-", Convert.ToString(reader.GetValue(i)));
SelectCheckBoxList(reader["PCarOptionID"].ToString(), ddlcaroptions);
}
}
}
}
now split and check if it has the same value to mark as checked
private void SelectCheckBoxList(string valueToSelect, CheckBoxList ddlcaroptions)
{
string[] aray = valueToSelect.Split(',');
foreach (string listItem2 in aray)
{
ListItem listItem = ddlcaroptions.Items.FindByValue(valueToSelect);
listItem.Selected = true;
}
}
i hope this answer is clear and help someone else :)

Is it possible to switch wifi networks in Appium?

While executing my test suite I have to switch between different wifi networks available in Android Device.
In the middle of the execution I have to change my wifi connection from Wifi_Network_1 to Wifi_Network_2 provided ssid name and password of wifi network is known. How can it be done?
I am using:
Appium server -->1.8.1
java-client --> 6.1.0
selenium-java --> 3.13.0
Since NetworkConnectionSetting has been deprciated, I am not able to find alternate for it.
I can toggle wifi on/off using
driver.toggleWifi();
But it is not suitable for my case as i need to toggle between different wifi network available using SSID name and its password.
Thanks in advance.
Hi I'am using this method due Appium deprecated their switch for wifi, and I've created my own override via console via commands from adb. It is working for me so give it a try:
public synchronized boolean wifiSetup(String udid, boolean flg) {
synchronized (this) {
String flgEnabled = (flg) ? "enable" : "disable";
List<String> output = Console.runProcess(false, "adb -s " + udid + " shell am broadcast -a io.appium.settings.wifi --es setstatus " + flgEnabled);
for (String line : output) {
System.err.println(line);
if (line.equalsIgnoreCase("Broadcast completed: result=-1"))
return true;
}
return false;
}
}
usage to switch off:
wifiSetup("xxxUDIDfromAndroid", false);
usage to switch on:
wifiSetup("xxxUDIDfromAndroid", true);
And here is part for calling console:
public class Console {
private static final String[] WIN_RUNTIME = { "cmd.exe", "/C" };
private static final String[] OS_LINUX_RUNTIME = { "/bin/bash", "-l", "-c" };
private Console() {
}
private static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
#SuppressWarnings({ "hiding"})
private static <String> String[] concatStr(String[] first, String[] second) {
String[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static List<String> runProcess(boolean isWin, String... command) {
String[] allCommand = null;
try {
if (isWin) {
allCommand = concat(WIN_RUNTIME, command);
} else {
allCommand = concat(OS_LINUX_RUNTIME, command);
}
ProcessBuilder pb = new ProcessBuilder(allCommand);
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String _temp = null;
List<String> line = new ArrayList<String>();
while ((_temp = in.readLine()) != null) {
// system.out.println("temp line: " + _temp);
line.add(_temp);
}
// system.out.println("result after command: " + line);
return line;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Hope this helps,

Cannot refresh listview with observablecollection

I am trying to refresh my listview when an item is removed from it, but every time it gives me this error:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index.
Before updating the ObservableCollection, I do this:
Groups = new ObservableCollection<RequestGroups>();
And then I fill it with this:
var temp = (JArray)resultJson["data"];
JArray jarr = temp;
foreach (JObject contents in jarr.Children<JObject>())
{
Requests obj = new Requests();
obj.Id = (int)contents["id"];
Client c = new Client();
c.address = contents["address"].ToString();
c.phone = contents["phone"].ToString();
c.name = contents["user"].ToString();
obj.Client = c;
obj.Date = contents["date"].ToString();
obj.Duration = contents["duration"].ToString();
obj.DurationText = "Duración: "+contents["duration"].ToString()+"h";
obj.Price = "$" + contents["price"].ToString();
String[] cDate = obj.Date.Split(' ');
String cHour = cDate[1]+" "+cDate[2];
obj.Hour = cHour;
String[] date = cDate[0].Split('-');
String title = months[date[1]] + " " + date[0];
obj.Title = title;
bool flag = false;
foreach(RequestGroups rqG in Groups){
if(rqG.Title.Equals(title)){
rqG.Add(obj);
flag = true;
}
}
if(!flag){
RequestGroups rq = new RequestGroups(title, date[1] + "-" + date[0]);
rq.Add(obj);
Device.BeginInvokeOnMainThread(() =>
{
Groups.Add(rq);
});
}
}
This is where I remove the items:
private async Task UpdateRequest(int status,int idEvent)
{
HttpClient hTTPClient = new HttpClient();
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
client.BaseAddress = new Uri(Utils.baseUrl);
Dictionary<string, string> dataToSend = new Dictionary<string, string>();
dataToSend.Add("session", Utils.loginKey);
dataToSend.Add("eventId", idEvent+"");
dataToSend.Add("status", status.ToString());
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataToSend, new KeyValuePairConverter());
var contentVar = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync("/UpdateEvent", contentVar);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
string contents = await response.Content.ReadAsStringAsync();
var resultJson = JObject.Parse(result);
if ((int)resultJson["status"] == 0)
{
await base.DisplayAlert((string)resultJson["msg"], "", "OK");
return;
}
else if ((int)resultJson["status"] == 1)
{
//I'm currently trying to reload the whole view, before this was calling the method above.
await this.mainPage.Navigation.PushAsync(new NavigationPage(new MasterMenu.MainPage()));
await getRequests();
}
else
{
await base.DisplayAlert("Error procesando la solicitud, intente más tarde", "", "Ok");
return;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error update request: {0}", ex);
}
await Task.Delay(1);
}
If I leave it like that, UI will not update. Please help me, as I've been struggling with this issue for 2 days now. It happens exclusively on iOS.
The issue was fixed after updating iOS. The problem was caused because of a buggy iOS version that had problems indexing objects. After updating, everything ran as smoothly as usual. If anyone runs into this issue (exclusively on iOS), try updating both iOS and Xamarin Forms.

sqljocky query does not have a method 'then' (dart database access)

I'm trying to code sql access to a database using sqljocky in Dart. As I want to make some computation with the result returned by my database Handler, the method return a Future.
But when I try to run it, I'm getting the following error:
Uncaught Error: The null object does not have a method 'then'`
I've ran the debugger and found that this error raise on:
db.query('select * from user where email="$email"').then(...)
but the catchError clause doesn't fire.
My handler method is:
// db is a ConnectionPool
Future<Map<String,String>> queryUser(String email){
print(email);
db.query('select * from user where email="${email}"').then((result) { // here raise the error
Map<String,String> results = new Map<String,String>();
result.forEach((row){
results['status'] = '200';
results['ID'] = row[0];
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
});
return results;
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
return results;
});
}
And the method that call this handler is:
List getUser(String email) {
Future<Map<String,String>> result = dbhandler.queryUser(email);
result.then((Map<String,String> result) {
String statuscode = result['status'];
result.remove('status');
String json = JSON.encode(result);
List pair = new List();
pair.add(statuscode);
pair.add(json);
return pair;
});
If I run the query directly in phpmyadmin, it return correct data, so it is correct.
Can someone give me a hint about how to solve it?
The queryUser() method will always return null, as there is no return statement. In the next release of Dart there will be a static hint warning for this, but at the moment there is none.
Perhaps the code below is what you meant to do. Note the initial return statement before db.query(), and the extra result.toList() call. I haven't tested this, so there's probably a typo or two.
Future<Map<String,String>> queryUser(String email){
print(email);
return db.query('select * from user where email="${email}"')
.then((result) => result.toList())
.then((rows) {
var row = rows.single;
Map<String,String> results = new Map<String,String>();
results['status'] = '200';
results['ID'] = row[0];
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
return results;
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
return results;
});
}
You can also make this a bit cuter using map literals:
Future<Map<String,String>> queryUser(String email){
return db.query('select * from user where email="${email}"')
.then((result) => result.toList())
.then((rows) => <String, String> {
'status': '200',
'ID': rows.single[0],
'Image': rows.single[1],
'Name': rows.single[2],
'Email': rows.single[3],
'Password': rows.single[4] })
.catchError((error) => <String, String> {'status': '500'});
}
Finally I found the answer using Completer to control the Future object, but the real problem was, as Greg Lowe said, that my methods doesn't return anything as they come to end before the then clause.
Using completer, I've made my query method as:
Future<Map<String,String>> queryUser(String email){
Completer c = new Completer();
db.query('select * from user where email="$email"').then((result) {
Map<String,String> results = new Map<String,String>();
result.forEach((row){
results['status'] = '200';
results['ID'] = row[0].toString();
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
}).then((onValue){
c.complete(results);
});
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
c.completeError((e) => print("error en queryUser"));
});
return c.future;
}
I also solved an error when using the foreach method, at first I supposed it return nothing, but after that, I noticed that it return a Future, so I added a then clause.
And my getUser method:
Future<List> getUser(String email) {
Completer c = new Completer();
Future<Map<String,String>> result = dbhandler.queryUser(email);
result.then((Map<String,String> result) {
String statuscode = result['status'];
result.remove('status');
String json = JSON.encode(result);
List pair = new List();
pair.add(statuscode);
pair.add(json);
c.complete(pair);
});
return c.future;
}
After those changes, everything works right

How to handle SQL Query CommandTimeout in C# 2.0

I have got below code in c#.
SqlConnection conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;");
conn.Open();
if (conn != null)
{
//create command
SqlCommand cmd = new SqlCommand("dbo.GETTridionLinkData", conn);
cmd.Parameters.AddWithValue("#PageID", "637518");
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 500;
StringBuilder sbXML = new StringBuilder();
//Adding Root node
sbXML.Append("<TridionLinks>");
//Reading all the values of Stored procedure return
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while (reader.Read())
{
sbXML.Append(reader.ReadOuterXml().Replace("//", "/"));
}
}
//Closing the root node tag
sbXML.Append("</TridionLinks>");
XmlDocument xDoc = new XmlDocument();
//Loading string xml in XML Document
xDoc.LoadXml(sbXML.ToString());
}
In above code you can see that, I have set the cmd.CommandTimeout = 500;, now I want to give user an error message if the timeout is more than this or you can say database is down.
Please suggest!!
Please refer to
How to catch SQLServer timeout exceptions
The question has already been answered..
To improve coding, you can use
try{
using (sqlconnection Conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"){
...
}
}catch(sqlException ex){
if (ex.Number == -2) {
//return your message to the control or display the error
}
}
well just an example..

Resources