Retrieve Data from Mysql Database in WebApi To HttpRecquest? - c#

I am trying to retrieve a set of data from a MySQL database in a WebAPI application and access it through HTTP request from a mobile app. Hence I created a WebApi, a RestClient class and the class where I would show the data, this is my code.
Web API
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// GET: api/Blog
[HttpGet]
public IEnumerable<string> Get()
{
}
// GET: api/Blog/5
[HttpGet("{id}", Name = "GetBlogItems")]
public string Get(int id)
{
}
// POST: api/Blog
[HttpPost]
public void Post([FromBody] RetrieveDataClass value)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
}
// PUT: api/Blog/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
So, in my database, I have three rows with a telephone number of +233892929292, after the filter I have to get three rows. and I would also filter to only the topic and summary column.
RestClient Class
public class BlogRestClient<T>
{
private const string WebServiceUrl = "http://localhost:57645/api/Blog/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
public async Task<bool> PostAsync(T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PostAsync(WebServiceUrl, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> PutAsync(int id, T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> DeleteAsync(int id, T t)
{
var httpClient = new HttpClient();
var response = await httpClient.DeleteAsync(WebServiceUrl + id);
return response.IsSuccessStatusCode;
}
}
ModelData Class
public class ModelDataClass
{
public string Telephone ;
public string Created/Saved ;
public string TopicSaved1 ;
public string SummarySaved1 ;
public string CategoriesSaved1 ;
public string Body1 ;
public string Body2 ;
public string Body3 ;
public string Body4 ;
public ModelDataClass()
{
}
}
The Values for the strings in ModelDataClass are set in another class to post in MySQL database. Since that is not causing the problem in question, I have not included the code.
RetrieveDataClass
public class RetrieveDataClass
{
public string Topic ;
public string Summary ;
public RetrieveDataClass()
{
GetDataEvent();
AddBlog();
}
public void GetDataEvent()
{
BlogRestClient<ModelDataClass> restClient = new
BlogRestClient<ModelDataClass>();
await restClient.GetAsync();
}
public ObservableCollection<ModelDataClass> BlogItems = new
ObservableCollection<ModelDataClass>();
public void AddBlog()
{
BlogListView.ItemsSource = BlogItems;
}
}
Question1
How do I retrieve the data from, Mysql, to WebAPI accessed through the REST client class(It's for mobile so I have to use Http request)?
Question2
I would like to create a listView for each row I retrieve through the MySQL database. With the heading being the data in the topic column and the subheading is with the data in summary column.

Your application is designed with the Multitier Architecture pattern. As such, you need to ensure you have a separation of concerns.
The Web API will represent your presentation logic layer. It will parse the client's request, query for the data as required and format the returned data as needed.
The RetrieveClient can then handle the data access layer. It will manage access to the database, insert, update, delete as needed.
The key point here is to ensure that each layer talks to the other to perform actions and that you do not directly access the database in your presentation layer.
As such,
How to retrieve data?
In your Data Access Layer :
public class RetrieveDataClass
{
private IDbConnection connection;
public RetrieveDataClass(System.Data.IDbConnection connection)
{
// Setup class variables
this.connection = connection;
}
/// <summary>
/// <para>Retrieves the given record from the database</para>
/// </summary>
/// <param name="id">The identifier for the record to retrieve</param>
/// <returns></returns>
public EventDataModel GetDataEvent(int id)
{
EventDataModel data = new EventDataModel();
string sql = "SELECT id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4 WHERE id = #id";
using (IDbCommand cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
IDbDataParameter identity = cmd.CreateParameter();
identity.ParameterName = "#id";
identity.Value = id;
identity.DbType = DbType.Int32; // TODO: Change to the matching type for id column
cmd.Parameters.Add(identity);
try
{
connection.Open();
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
data.id = reader.GetInt32(reader.GetOrdinal("id"));
// TODO : assign the rest of the properties to the object
}
else
{
// TODO : if method should return null when data is not found
data = null;
}
}
// TODO : Catch db exceptions
} finally
{
// Ensure connection is always closed
if (connection.State != ConnectionState.Closed) connection.Close();
}
}
// TODO : Decide if you should return null, or empty object if target cannot be found.
return data;
}
// TODO : Insert, Update, Delete methods
}
The above will get a record from the database, and return it as an object. You can use ORM libraries such as EntityFramework or NHibernate instead but they have their own learning curve.
How to return the data?
Your client will call the WebAPI, which in turn query for the data from the data access layer.
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// TODO : Move the connection string to configuration
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
// GET: api/Blog
/// <summary>
/// <para>Retrieves the given record from the database</para>
/// </summary>
/// <param name="id">Identifier for the required record</param>
/// <returns>JSON object with the data for the requested object</returns>
[HttpGet]
public IEnumerable<string> Get(int id)
{
IDbConnection dbConnection = System.Data.Common.DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
RetrieveDataClass dal = new RetrieveDataClass(dbConnection);
EventDataModel data = dal.GetDataEvent(id);
if (data != null)
{
// Using Newtonsoft library to convert the object to JSON data
string output = Newtonsoft.Json.JsonConvert.SerializeObject(data);
// TODO : Not sure if you need IEnumerable<string> as return type
return new List<string>() { output };
} else
{
// TODO : handle a record not found - usually raises a 404
}
}
// TODO : other methods
}
There are lots of other examples online on how to access the data via API. Have a look on google and review. A few that come to mind are
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

i solved the problem.
WebApi
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// GET: api/Blog
[HttpGet]
public List<BlogViews> Get()
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `Telephone` ='Created'";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
List<BlogViews> GetBlogList = new List<BlogViews>();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
BlogViews BV = new BlogViews();
BV.id = (MSQLRD["id"].ToString());
BV.DisplayTopic = (MSQLRD["Topic"].ToString());
BV.DisplayMain = (MSQLRD["Summary"].ToString());
GetBlogList.Add(BV);
}
}
conn.Close();
return GetBlogList;
}
// GET: api/Blog/5
[HttpGet("{id}", Name = "GetBlogItems")]
public string Get(int id)
{
}
// POST: api/Blog
[HttpPost]
public void Post([FromBody] RetrieveDataClass value)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
}
// PUT: api/Blog/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
RetriveDataClass
public class RetrieveDataClass
{
public RetrieveDataClass()
{
AddBlog();
}
public class BlogViews
{
public string id { get; set; }
public string DisplayTopic { get; set; }
public string DisplayMain { get; set; }
public ImageSource BlogImageSource { get; set; }
}
public List<BlogViews> BlogList1 = new List<BlogViews>();
public async Task< List<BlogViews>> GetBlogs()
{
BlogRestClient<BlogViews> restClient = new BlogRestClient<BlogViews>();
var BlogV = await restClient.GetAsync();
return BlogV;
}
public async void AddBlog()
{
BlogList1 = await GetBlogs();
BlogListView.ItemsSource = BlogList1;
}
}
so now i get a listview ,which contains each row from the database and each item in the listview heading is DisplayTopic and subheading is DisplayMain.

Related

Controller.Json() returns null

I'm only using ASP.Net and MVC, no other libraries.
The code is the following:
//ExpensesController.cs - the controller
public IActionResult getExpenses()
{
List<ExpensesViewModel> list = new List<ExpensesViewModel>();
string connectionString = "Data Source=DESKTOP-72RT825;Initial Catalog=AccountingDB;Integrated Security=True;Pooling=False";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand query = new SqlCommand("Select * from Expenses", sqlConnection);
try
{
SqlDataReader reader;
reader = query.ExecuteReader();
while (reader.Read())
{
String name = reader.GetValue(0).ToString();
String value = reader.GetValue(1).ToString();
String date = reader.GetValue(2).ToString();
list.Add(new ExpensesViewModel() { Name = name, Date=date, Value = value });
Debug.Print(name + " " + " " + value);
}
}
catch (SqlException ex)
{
Debug.Print(ex.Message);
return Json(ex.Message);
}
JsonResult jsonResult = null;
try
{
jsonResult = Json(list);
}
catch(Exception ex)
{
Debug.Write(ex.Message);
}
return jsonResult;
}
//The View Model
public class ExpensesViewModel
{
public string Name;
public string Value;
public string Date;
}
The data that Json(list) returns is null, even though the list is not, I looked in the debugger, the connection to the DB is good, the data arrives, it is put into the list, but when I try and convert it to Json it fails. I've tried adding elements into the list manually, the Json function still returns null.
Change your view model to use properties, not fields:
public class ExpensesViewModel
{
public string Name { get; set; }
public string Value { get; set; }
public string Date { get; set; }
}
The reason is that the default model binder binds to properties with public getters/setters.

C#/.NET I'm trying to create a login authentication for users, but my BCrypt verification is not working

I'm creating a login and user verification system using C#/.NET. This is my first time creating such a system so I need some guidance or strategies on how to go about accomplishing this. Thank you
Login Request
public class UserLoginRequest
{
public string Email { get; set; }
public string Password { get; set; }
}
Login Result
public class LoginResult
{
public int? Id { get; set; }
public string Email { get; set; }
}
Login SERVICE
public LoginResult Login(UserLoginRequest login)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "User_GetByEmail";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#email", login.Email);
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
LoginResult result = new LoginResult();
string PasswordHash = "";
{
result.Id = (int)reader["Id"];
result.Email = (string)reader["Email"];
PasswordHash = (string)reader["PasswordHash"];
};
if (BCrypt.Net.BCrypt.Verify(login.Password, PasswordHash))
{
return result;
}
else
{
return null;
}
}
}
}
Login Controller
[HttpPost, Route("api/login")]
public HttpResponseMessage Login(UserLoginRequest userLogin)
{
LoginResult result = userService.Login(userLogin);
if (result != null && result.Id.HasValue)
{
return Request.CreateResponse(HttpStatusCode.OK, result);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse("Invalid username or password"));
}
}
I figured it out, the problem was in my stored procedure where i did not allow enough characters to be passed into the database

Create data without Entity Framework

I'm trying to insert data into my database using ASP.NET MVC without Entity Framework and it doesn't work.
I tried these tutorials:
InsertUpdateDelete in ASP.NET MVC 5 without Entity Framework | C# Tutorial
ASP.Net MVC CRUD Operation without Entity Framework - YouTube
This is my controller:
public class AdresaController : Controller
{
private OracleConnection conn;
public AdresaController()
{
Connection connection = new Connection();
conn = connection.GetOracleConnection();
}
public ActionResult Create()
{
return View();
}
// POST: Adresa/Create
[HttpPost]
public ActionResult Create(AdresaModel obAdresa)
{
try
{
AdresaRepository x = new AdresaRepository(conn);
string result = x.CreateAdr(obAdresa);
ViewData["result"] = result;
ModelState.Clear();
return View();
}
catch
{
return View();
}
}
}
This is my repository:
public class AdresaRepository
{
private OracleConnection oracleConnection;
public AdresaRepository(OracleConnection oracleConnection)
{
this.oracleConnection = oracleConnection;
}
public string CreateAdr(AdresaModel obAdresa)//
{
string result = "";
try
{
string oString = "insert into adresa(id_adresa, strada, nr_str, bloc, localitate_id_loc) values(#id_adresa, #strada, #nr_str, #bloc, #localitate_id_loc)";
var cmdc = new OracleCommand(oString, oracleConnection);
cmdc.CommandType = CommandType.StoredProcedure;
cmdc.Parameters.Add(new OracleParameter("#id_adresa", obAdresa.IdAdresa));
cmdc.Parameters.Add(new OracleParameter("#strada", obAdresa.Strada));
cmdc.Parameters.Add(new OracleParameter("#nr_str", obAdresa.NrStrada));
cmdc.Parameters.Add(new OracleParameter("#bloc", obAdresa.Bloc));
cmdc.Parameters.Add(new OracleParameter("#localitate_id_loc", obAdresa.IdLoc));
oracleConnection.Open();
result = cmdc.ExecuteNonQuery().ToString();
oracleConnection.Close();
return result;
}
catch
{
return result = "";
}
finally
{
oracleConnection.Close();
}
}
}
And here is my model:
public class AdresaModel
{
public int IdAdresa { get; set; }
public string Strada { get; set; }
public string NrStrada { get; set; }
public string Bloc { get; set; }
public int IdLoc { get; set; }
}
#kashi_rock is on the right track but didn't explain the issue very well. When you execute a command, you can either set the CommandType to StoredProcedure and the CommandText to the name of a stored procedure or you can set CommnadType to Text (which is the default) and the CommandText to a SQL statement. You are mixing and matching. You are providing inline SQL but saying that you want to use a stored procedure. Basically, get rid of this line:
cmdc.CommandType = CommandType.StoredProcedure;
I find it very difficult to believe that no exception was thrown. It should have tried to tell you that there was no stored procedure with the name you specified or the like. You need to up your exception handling game or you'll be mystified by other things that seem to just not work with no indication of why.

Implement the Entity Framework in the Web API

I am Newbie to ASP.NET, created the MVC Framework Web API which accepts the array of ID's as input parameter and queries the Oracle DB, this should return the result in the JSON format.Our query is like
SELECT STCD_PRIO_CATEGORY_DESCR.DESCR AS CATEGORY,
STCD_PRIO_CATEGORY_DESCR.SESSION_NUM AS SESSION_NUMBER,
Trunc(STCD_PRIO_CATEGORY_DESCR.START_DATE) AS SESSION_START_DATE
from STCD_PRIO_CATEGORY
where STCD_PRIO_CATEGORY_DESCR.STD_REF IN(X,Y,Z)
where X,Y,Z are the values we will be passing as input parameters
I created the API controller as
public class PDataController : ApiController
{
public HttpResponseMessage Getdetails([FromUri] string[] id)
{
List<OracleParameter> prms = new List<OracleParameter>();
string connStr = ConfigurationManager.ConnectionStrings["PDataConnection"].ConnectionString;
using (OracleConnection dbconn = new OracleConnection(connStr))
{
var inconditions = id.Distinct().ToArray();
var srtcon = string.Join(",", inconditions);
DataSet userDataset = new DataSet();
var strQuery = #"SELECT STCD_PRIO_CATEGORY_DESCR.DESCR AS CATEGORY,
STCD_PRIO_CATEGORY_DESCR.SESSION_NUM AS SESSION_NUMBER,
Trunc(STCD_PRIO_CATEGORY_DESCR.START_DATE) AS SESSION_START_DATE
from STCD_PRIO_CATEGORY
where STCD_PRIO_CATEGORY_DESCR.STD_REF IN(";
StringBuilder sb = new StringBuilder(strQuery);
for(int x = 0; x < inconditions.Length; x++)
{
sb.Append(":p" + x + ",");
OracleParameter p = new OracleParameter(":p" + x,OracleDbType.NVarchar2);
p.Value = inconditions[x];
prms.Add(p);
}
if(sb.Length > 0) sb.Length--;
strQuery = sb.ToString() + ")";
using (OracleCommand selectCommand = new OracleCommand(strQuery, dbconn))
{
selectCommand.Parameters.AddRange(prms.ToArray());
using (OracleDataAdapter adapter = new OracleDataAdapter(selectCommand))
{
DataTable selectResults = new DataTable();
adapter.Fill(selectResults);
var returnObject = new { data = selectResults };
var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=ProvantisStudyData.json", out contentDisposition))
{
response.Content.Headers.ContentDisposition = contentDisposition;
}
return response;
}}}}}}
It works perfectly and returns the result as
{"data":[{"CATEGORY":"Internal Study","SESSION_NUMBER":7,"SESSION_START_DATE":"2015-02-13T00:00:00"}]}
But would like to implement the entity framework here by using the Model and the DBContext.I created the model class and the DataContext Class as follows
namespace PSData.Models
{ public class StudyDataModel
{ [Key]
public string CATEGORY { get; set; }
public int SESSION_NUMBER { get; set; }
public DateTime SESSION_START_DATE { get; set; }
}}
And
namespace PSData.Models
{
public class StudyDataContext:DbContext
{
public DbSet<StudyDataModel> details { get; set; }
}}
I am not sure how to implement them in the controller. When I tried to create the Controller using Web API 2 Controller with actions,using Entity Framework selected both the Model Class and the DB Context Class it creates controller with
private StudyDataContext db = new StudyDataContext();
// GET: api/StdData
public IQueryable<StudyDataModel> Getdetails()
I am not sure how to proceed as the return type is the HttpResponseMessage in my other Controller where I am returning the JSON message. Any help is greatly appreciayed
You do not need to explicitly convert it to json format. The content negotiation module and media formatter will take care of converting the data to the needed format (XML/JSON) based on the request. By default it returns JSON.
Assuming you have a DTO class like this
public class CategoryDto
{
public string Category { get; set; }
public int SessionNumber { get; set; }
public DateTime SessionStartDate { get; set; }
}
and in your action method, you can use Request.CreateResponse method.
public HttpResponseMessage Get()
{
var db = new StudyDataContext();
var data = db.details.Select(x => new CategoryDto {
Category = x.Category,
SessionStartDate = x.SessionStartDate,
SessionNumber = x.SessionNumber }
).ToList();
return Request.CreateResponse(HttpStatusCode.OK, data);
}

Assign global variable from async method using c#

I have an async method whereby i want to pull some data and assign to global variable for use in another method.
Below is the method:
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
gName = serStatus.name;
gEmail = serStatus.email;
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
The variables gName and gEmail have already been declared.
I want to use the variables to register user using the following logic:
protected void RegisterGoogleUser()
{
string strCon = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sql5 = "SELECT Email FROM Members where Email=#gEmail";
using (SqlConnection con5 = new SqlConnection(strCon))
{
using (SqlCommand cmd5 = new SqlCommand(sql5, con5))
{
con5.Open();
cmd5.Parameters.AddWithValue("#gEmail", gEmail);
Object result = cmd5.ExecuteScalar();
con5.Close();
if (result != null)
{
lblMessage.Text = "This e-mail is already registered. If you forgot your password, use forgot password link to recover it.";
return;
}
else
{
string providerName = "Google";
string conn = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string query = "INSERT INTO Members(Name, Email, ProviderName)values(#gName,#gEmail,#providerName)";
using (SqlConnection connection = new SqlConnection(conn))
{
using (SqlCommand cmd1 = new SqlCommand(query, connection))
{
cmd1.Parameters.AddWithValue("#gName", gName);
cmd1.Parameters.AddWithValue("#gEmail", gEmail);
cmd1.Parameters.AddWithValue("#providerName", providerName);
connection.Open();
cmd1.ExecuteNonQuery();
Session.Add("GEmail", gEmail);
Session.Add("CurrentUserName", gName);
Response.Redirect("ExternalRegistration.aspx");
connection.Close();
}
}
}
}
}
}
Below is GoogleUserOutputData class and Google Login Method
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
protected void btnGoogleLogin_Click(object sender, System.EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["Provider"] = "Google";
Response.Redirect(Googleurl);
}
The exception i am getting is: "The parameterized query '(#gEmail nvarchar(4000))SELECT Email FROM Members where Email=#g' expects the parameter '#gEmail', which was not supplied."
You really need to read more about how to use Asynchronous Programming.
If you call getgoogleplususerdataSer() without the await keyword, the execution of your block of code continues even before the end of the method.
So:
private async Task callingMethod()
{
getgoogleplususerdataSer();
Console.WriteLine(gName); // maybe null, runs before the end of previous method.
Console.WriteLine(gEmail); // maybe null
}
instead:
private async Task callingMethod()
{
await getgoogleplususerdataSer(); // wait for this to end, then continue.
Console.WriteLine(gName); // null
Console.WriteLine(gEmail); // null
}

Categories