Getting error while consuming Web API in Xamarin forms cross platform - asp.net-web-api

Getting below error while consuming web API in Xamarin forms "Cannot convert from Login to System.Net.Http.HttpCompletionOption"
I'm new to mobile development ,please help me in completing the above code for consuming the API's in Xamarin cross platform.
Below is the code for WEB API
public class DBLoginController : ApiController
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_test"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpGet]
[ActionName("getCustomerInfo")]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_admin";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_admin";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
[HttpPost]
public int Login([System.Web.Http.FromBody] Login lgn)
{
int ret = 0;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from tbl_admin where username='"+lgn.username+"'username and password='"+ lgn.password + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
ret = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch
{
}
return ret;
}
}
Below is the code for consuming API in xamarin form
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://********.com/api/DBLogin/getCustomer");
Login lgn = new Login { username = txtUsername.Text.ToString(), password = txtPassword.Text.ToString() };
var response = client.GetAsync("api/Login/Login").Result;
var a = response.Content.ReadAsStringAsync();
if (a.Result.ToString().Trim() == "0")
{
messageLabel.Text = "Invalid login credentials.";
}
else
{
await Navigation.PushModalAsync(new Page2());
}
}
}
}
please help
Thanks in advance

Related

Giving this error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable'

This code giving a error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable' how to resolve it.
using (XLWorkbook wb = new XLWorkbook()) this line giving the error.
I have also added assembly reference ClosedXML but its not working
Is there any way to resolved this issue?
using System.Web;
using System.Data.SqlClient;
using System.IO;
using ClosedXML.Excel;
using System.Web.Mvc;
using SHIPVICTUAL.Controllers;
namespace SHIPVICTUAL.Controllers
{
public class shipController : Controller
{
// GET: ship
public ActionResult Index()
{
return View();
}
public ActionResult ExportToExcel(FormCollection formCollection)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBShipVictual"));
cmd = new SqlCommand("Reports_rdlc", con);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
dt.TableName = "Report";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-disposition", "attachment;ReportList.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
{
}
}
}
catch
{
}
return View();
}
}
} ```

ObjectContext.Translate not working in oracle 19 version

this is my function that translate result from db to object classe.
public static List<T> GetListBySP<T>(string pSPName, params object[] pParamArray)
{
List<T> res = null;
//string connStr = ConfigurationManager.ConnectionStrings[sConnStr].ConnectionString;
string connStr = DbFactory.ConnStr;
using (OracleConnection conn = new OracleConnection(connStr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = pSPName;
cmd.CommandType = CommandType.StoredProcedure;
FillParameters(cmd.Parameters, pParamArray);
cmd.Parameters.Add("pCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
using (var db = DbFactory.CreateRo())
{
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
}
}
}
return res;
}
after update oracle version to 19.
exaption throw on line
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
the exeption is:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
the project run on .net framework 4.6.2

SqlException was unhandled(incorrect syntax error)

When I try to enter login, the program is sending me throw section & writing something about incorrect synxtax error '='.
public bool personelEntryControl(string password, int UserId)
{
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ID=#Id and PAROLA=#password", con);
cmd.Parameters.Add("#Id", SqlDbType.VarChar).Value = UserId;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = Convert.ToBoolean(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
throw;
}
return result;
}
public void personelGetbyInformation(ComboBox cb)
{
cb.Items.Clear();
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ", con);
if (con.State == ConnectionState.Closed) ;
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cPersoneller p = new cPersoneller();
p._PersonelId = Convert.ToInt32(dr["ID"]);
p._PersonelGorevId = Convert.ToInt32(dr["GOREVID"]);
p._PersonelAd = Convert.ToString(dr["AD"]);
p._PersonelSoyad = Convert.ToString(dr["SOYAD"]);
p._PersonelParola = Convert.ToString(dr["PAROLA"]);
p._PersonelKullanıcıAdı = Convert.ToString(dr["KULLANICIADI"]);
p._PersonelDurum = Convert.ToBoolean(dr["DURUM"]);
cb.Items.Add(p);
}
dr.Close();
con.Close();
}
You appear to be trying to filter with your cmd SQLCommand. However, you left out the keyword WHERE, hence the incorrect syntax error. It should be something like:
SqlCommand cmd = new SqlCommand("Select * from Personeller WHERE ID=#Id and PAROLA=#password", con)

How to use RESTful service in Xamarin.Forms to fetch JSON data

Since I am new to Xamarin, I would really appreciate if someone could explain me how to consume RESTful service (returning JSON data) using Xamarin Forms with the simplest example.
You can use JSON.net and HTTP request, here is a quick example of how to use the movie database which is a free movie database GET and POST examples, hope this helps:
const string _baseUrl = "http://api.themoviedb.org/3/";
const string _pageString = "&page=";
//GET Example
public static async Task<ObservableCollection<Movie>> GetTopRatedMoviesAsync(int page = 1)
{
HttpClient client = new HttpClient();
//_apiKey = themoviedb api key, page = page size 1 = first 20 movies;
string topRatedUrl = _baseUrl + "movie/top_rated?" + _apiKey + _pageString + page;
HttpResponseMessage result = await client.GetAsync (topRatedUrl, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try{
string content = await result.Content.ReadAsStringAsync ();
ObservableCollection<Movie> MovieList = GetJsonData(content);
//return a ObservableCollection to fill a list of top rated movies
return MovieList;
}catch(Exception ex){
//Model Error
Console.WriteLine (ex);
return null;
}
}
//Server Error or no internet connection.
return null;
}
static ObservableCollection<Movie> GetJsonData(string content){
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["results"];
ObservableCollection<Movie> movieList = new ObservableCollection<Movie> ();
foreach (var jObj in jarray) {
Movie newMovie = new Movie();
newMovie.Title = (string)jObj["title"];
newMovie.PosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.HighResPosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.Id = (int)jObj["id"];
newMovie.Overview = (string)jObj["overview"];
newMovie.VoteCount = (double)jObj["vote_count"];
newMovie.ReleaseDate = (DateTime)jObj["release_date"];
newMovie.VoteAverage = (float)jObj["vote_average"];
movieList.Add(newMovie);
}
return movieList;
}
//POST Example:
public static async Task<bool> PostFavoriteMovieAsync(Movie movie)
{
try
{
HttpClient client = new HttpClient();
//_sessionId = string with the movie database session.
string tokenUrl = _baseUrl + "account/id/favorite?" + _apiKey + _sessionId;
string postBody = JsonConvert.SerializeObject(new Favorite{
favorite = !movie.Favorite,
media_id = movie.Id,
});
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (tokenUrl,
new StringContent (postBody, Encoding.UTF8, "application/json"));
if(response.IsSuccessStatusCode)
return true;
else
return false;
}
catch(Exception ex){
Console.WriteLine (ex.Message);
return false;
}
}

How to show progress bar with progress calculation in winform while filling dataset?

Here is my code i want to load a progress bar while dataset filling and data importing in a datagridview.Plz Help me
private void btnLoad_Click(object sender, EventArgs e)
{
string str="select Cert_ID,Card_Number,Name,DOB,Mobile,Gender,Relation ";
str = str + " from dbo.beneficiary";
SqlConnection conn = null;
SqlDataAdapter sqlda = null;
DataSet res = new DataSet();
DataTable dt = new DataTable();
try
{
_connectionString = "xyz.........";
conn = new SqlConnection(_connectionString);
conn.Open();
SqlCommand command = new SqlCommand(str, conn);
sqlda = new SqlDataAdapter(command);
sqlda.Fill(res);
dataGridView1.DataSource=res.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
}

Resources