Need help to find where does API takes data from in ASP.NET MVC - c#

I am a begginer and i work in a MVC project which I cant understand it well yet.
I can't understand where does the API takes data from when I try to connect in Login Screen.
It doesn't use Entity Framework and there isn't a json with the data.
When I enter Id and Pass it calls an API (GetAPIResponse) which somehow finds that is correct.
Need help to understand the code and the logic behind it.
LoginBL class contains:
public bool IsAuthenticated(LoginEntity user)
{
string url = string.Empty;
string callType = string.Empty;
string server = string.Empty;
try
{
// get URL, Call type, Server from config file
url = ConfigurationManager.AppSettings["login_url"].ToString();
callType = ConfigurationManager.AppSettings["calltype"].ToString();
server = ConfigurationManager.AppSettings["server"].ToString();
// Encrypt password
string password = Scrambler.GenerateMD5Hash(user.Password);
// Prepare content for the POST request
string content = #"calltype=" + callType + "&server=" + server + "&user=" + user.UserName + "&pass=" + password + "";
Debug.WriteLine("Callcenter login url: " + content);
HttpResponseMessage json_list = ApiCallBL.GetAPIResponse(url, content);
LoginResponseEntity obj = new LoginResponseEntity();
obj = JsonConvert.DeserializeObject<LoginResponseEntity>(json_list.Content.ReadAsStringAsync().Result);
Debug.WriteLine(callType + " Response: " + json_list.Content.ReadAsStringAsync().Result);
//if API resultCode return 0 then user details and token save in session for further use
if (obj.ResultCode == 0)
{
int restrict = obj.UserInfo.RestrictCallType.HasValue ?
obj.UserInfo.RestrictCallType.Value : 0;
HttpContext.Current.Session["user_id"] = obj.UserInfo.usr_id;
HttpContext.Current.Session["user_name"] = obj.UserInfo.usr_username;
HttpContext.Current.Session["user_group_id"] = obj.UserInfo.UserGroupID;
HttpContext.Current.Session["groupid"] = obj.UserInfo.groupid;
HttpContext.Current.Session["token"] = obj.Token;
HttpContext.Current.Session["web_server_url"] = obj.ServerInfo.web_server_url;
HttpContext.Current.Session["centerX"] = obj.ServerInfo.DefaultGeoX;
HttpContext.Current.Session["centerY"] = obj.ServerInfo.DefaultGeoY;
HttpContext.Current.Session["dateFormat"] = obj.ServerInfo.dateFormat;
HttpContext.Current.Session["currency"] = obj.ServerInfo.currency;
HttpContext.Current.Session["customer_img"] = obj.ServerInfo.customer_img;
HttpContext.Current.Session["groups"] = obj.groups;
HttpContext.Current.Session["restrict_call_type"] = restrict ;
Debug.WriteLine("obj.UserInfo.UserGroupID " + obj.UserInfo.UserGroupID);
Debug.WriteLine("obj.UserInfo.groups " + obj.groups);
//HttpContext.Current.Session["defaultLanguage"] = obj.ServerInfo.defaultLanguage;
HttpCookie cookie = new HttpCookie("Login");
// if remember me checked then user name and password stored in cookie else cookes is expired
if (user.RememberMe)
{
cookie.Values.Add("user_name", obj.UserInfo.usr_username);
cookie.Values.Add("pwd", user.Password);
cookie.Expires = DateTime.Now.AddDays(15);
HttpContext.Current.Response.Cookies.Add(cookie);
}
else
{
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
}
return true;
}
else
{
//ResultCode -5 :Invalid Login ,-1:Database Error ,-2:Server Error ,-3:Invalid Parameter specified ,-4:Invalid Token
return false;
}
}
catch
{
throw;
}
finally
{
url = string.Empty;
callType = string.Empty;
server = string.Empty;
}
}
Okay here after converts pass to MD5 creates a "string content" with the information given.
Then in next line (HttpResponseMessage json_list = ApiCallBL.GetAPIResponse(url, content);) calls the API with the url and content as parameters where it finds if the data exists.
API code:
public static HttpResponseMessage GetAPIResponse(string url, string content)
{
StringBuilder traceLog = null;
HttpContent httpContent = null;
try
{
traceLog = new StringBuilder();
traceLog.AppendLine("Start: BusinessLayer getAPIResponse() Request Data:- " + DateTime.Now + "URL = " + url + "&content = " + httpContent);
using (HttpClient client = new HttpClient())
{
httpContent = new StringContent(content);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var resp = client.PostAsync(url, httpContent).Result;
Debug.WriteLine("resp: " + resp.Content.ReadAsStringAsync().Result);
traceLog.AppendLine("End: BusinessLayer getAPIResponse() call completed HttpResponseMessage received");
return resp;
}
}
catch
{
throw;
}
finally
{
traceLog = null;
httpContent.Dispose();
url = string.Empty;
content = string.Empty;
}
}
In the following line, console prints the result that I cant understand where it cames from (Debug.WriteLine("resp: " + resp.Content.ReadAsStringAsync().Result);)
Sorry for the confusion , I am in my first job with zero work experience and I am called to learn how this works alone without proper education on ASP.NET from them.

You will not go very far without debbugger. Learn how to debug in Visual Studio (YouTube tutorials might be fastest way). Place debug points along critical points in code (for example moment when client sends and receives response is line var resp = client.PostAsync...) and check variables.
Url for API server is actually defined in the line
url = ConfigurationManager.AppSettings["login_url"].ToString();
ConfigurationManager means Web.config file, check it's appSettings section for login_url entry, there is your url.
Btw, using (HttpClient client = new HttpClient()) is not a good way to use a HttpClient and will lead to port exhaustion. It's ok for small number of requests, but for larger ones you must reuse it, or use HttpClientFactory (for .NET Core).

Related

C# - Why does BrowserMob.GetHar() only return 1 entry?

I am writing some simple C# code to try automatically getting HAR file from Chrome browser. I am using browser-mob-proxy and there is a function: GetHar() which is supposed to return some different entries of URL, request and response time, etc. However, it always return me only 1 entry which is the original URL I am negativing to: www.google.com
I've tried to use dr.Navigate().Refresh() to make sure the page is reloaded so there are some activities on chrome DevTool Network section.
server.Start();
Thread.Sleep(1000);
Client client = server.CreateProxy();
client.NewHar("google");
var chromeOptions = new ChromeOptions();
var seleniumProxy = new Proxy { HttpProxy = client.SeleniumProxy };
chromeOptions.Proxy = seleniumProxy;
var dr = new ChromeDriver(chromeOptions);
dr.Navigate().GoToUrl("http://www.google.com");
dr.FindElementByClassName("gb_e").Click();
Thread.Sleep(3500);
dr.Navigate().Refresh();
// Get the performance stats
HarResult harData = client.GetHar();
Log log = harData.Log;
Entry[] entries = log.Entries;
foreach (var e in entries)
{
Request request = e.Request;
Response response = e.Response;
var url = request.Url;
var time = e.Time;
var status = response.Status;
var testStr = "Url: " + url + " - Time: " + time + " Response: " + status;
}
I expected GetHar() function will return more entries instead of only 1.
Not sure why, but the issue has been resolved by adding SSL proxy:
var seleniumProxy = new Proxy { HttpProxy = client.SeleniumProxy , SslProxy = client.SeleniumProxy };

C# Sending Cookies with Post Request

I want to sign in to youtube with post request. I used xNet for HttpRequest.
I wrote following codes:
static void Main(string[] args)
{
string url = "https://accounts.google.com/_/signin/sl/lookup?hl=en&_reqid=55174&rt=j";
HttpClass httpClass = new HttpClass();;
httpClass.PostRequestAsync(url, "username", "password");
}
class HttpClass {
public async Task PostRequestAsync(string url, string account, string pass)
{
xNet.HttpRequest http = new xNet.HttpRequest();
http.Cookies = new CookieDictionary();
string type = "application/x-www-form-urlencoded;charset=utf-8";
string query =
"continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Ffeature%3Dsign_in_button%26action_handle_signin%3Dtrue%26app%3Ddesktop%26next%3D%252F%26hl%3Den&service=youtube&hl=en&f.req=%5B%22" + account + "%22%2C%22AEThLlxFJqXTI-dLw8jxU_Lw8c4Qtpc4DAAeEE1rpkbEUFqwwK1U86bZEzsWmZKM5IjRccPvbYTLgb0yonB3vputyMTNm-8YcGqbe_GeaB6RHFJImp_gZ-y0jFv4nduPGxM-zpJX8BahbDlIyeY2sP8-puVe3W1iwKX3rGcSFGMevHHK-ByNEUY%22%2C%5B%5D%2Cnull%2C%22TR%22%2Cnull%2Cnull%2C2%2Cfalse%2Ctrue%2C%5Bnull%2Cnull%2C%5B2%2C1%2Cnull%2C1%2C%22https%3A%2F%2Faccounts.google.com%2FServiceLogin%3Fuilel%3D3%26passive%3Dtrue%26service%3Dyoutube%26continue%3Dhttps%253A%252F%252Fwww.youtube.com%252Fsignin%253Ffeature%253Dsign_in_button%2526action_handle_signin%253Dtrue%2526app%253Ddesktop%2526next%253D%25252F%2526hl%253Den%26hl%3Den%22%2Cnull%2C%5B%5D%2C4%2C%5B%5D%2C%22GlifWebSignIn%22%5D%2C1%2C%5Bnull%2Cnull%2C%5B%5D%5D%2Cnull%2Cnull%2Cnull%2Ctrue%5D%2C%22" + account + "%22%5D&bgRequest=%5B%22identifier%22%2C%22!Pj2lPRxCiup4YICaVSxEHyFXdsNE5lECAAAAQ1IAAAAbCgAW9I8p8C1f10xg_NjCyA99rybP30APm5kBCr5B19mb-UkpwTj1ZsyybospA0TSjuUTuJeCHmkiRqKfhHxRE1CV0Yd7nifpK8VCTMNnmUMrl4-anneYlV-Bs3NQESEmJTEcxBOjvbo_tXSasO8KbZopdTxzUHm-qBGOQRTUZM4Hw6x-1HJdLoCQ2bi4FoAhbsWEt6paR0K4neYHS1kdxewjDKefWWCQ__O3C71yOjm6p0S1rjNUEM0ak9V8N2CcnIFYQ77b1B98nHCZmgMr81YtgAOF8ClSb4ZV8AiUc96rC1rvMV2RIvW54RUgsJwWHXBx0nid8tRMdUmzCTymoa-_at7qE1nJL8SMAU9WEnGOs0u2xKlBKGsjNgnqhligTDBDPnp7%22%5D&azt=AFoagUUuZ6teJ3APaa8f6ly_olQZHdGWBg%3A1525177142108&cookiesDisabled=false&deviceinfo=%5Bnull%2Cnull%2Cnull%2C%5B%5D%2Cnull%2C%22TR%22%2Cnull%2Cnull%2C%5B%5D%2C%22GlifWebSignIn%22%2Cnull%2C%5Bnull%2Cnull%2C%5B%5D%5D%5D&gmscoreversion=undefined&checkConnection=youtube%3A288%3A1&checkedDomains=youtube&pstMsg=1&";
string html;
html = http.Post(url, query, type).ToString();
htmlTest(html);
type = "application/x-www-form-urlencoded";
query =
account +
"&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Ffeature%3Dsign_in_button%26action_handle_signin%3Dtrue%26app%3Ddesktop%26next%3D%252F%26hl%3Den&password=" +
pass + "&ca=&ct=";
http.Cookies = new CookieDictionary();
html = http.Post(url, query, type).ToString();
htmlTest(html);
}
public void htmlTest(string html)
{
File.WriteAllText("a.html", html);
Process.Start("a.html");
}
}
Response is:
)]}' [[["er",null,null,null,["gf.rrerr",1,"https://support.google.com/accounts/answer/61416?hl\u003den"] ,null,"gf.rrerr"] ,["e",2,null,null,149] ]]
The given link "https://support.google.com/accounts/answer/61416?hl\u003den" is says you must to open your cache data. I think I need to pass cookies with post but How can I pass cookies with post request?
Try to use cookíe with code
request.Cookies = new CookieDictionary()
{
{"ggg", "hhh"}
};

how to get the response body in code webtest?

I wrote a webtest that calls a web-service.
I want to get the response body and do some validation on it.
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
WebTestRequest request2 = new WebTestRequest("webservice");
request2.Headers.Add("Content-Type", "application/json");
request2.Method = "POST";
request2.Encoding = System.Text.Encoding.GetEncoding("utf-8");
StringHttpBody request2Body = new StringHttpBody();
request2Body.ContentType = "application/json";
request2Body.InsertByteOrderMark = false;
request2Body.BodyString = #"{ <body>}";
request2.Body = request2Body;
WebTestResponse res = new WebTestResponse();
console.WriteLine(res.BodyBytes);
yield return request2;
request2 = null;
}
When i ran the above code i didn't get any response on my console.
How can i get the response body using coded webtest?
There are at least three problems with the code in the question
The code in the question does not perform the request before doing the WriteLine. The two statements WebTestResponse res = new WebTestResponse(); and console.WriteLine(res.BodyBytes); just create a new WebTestResponse object (with all default values) and then try to print part of its contents. The request is issued by the code that calls your GetRequestEnumerator method.
The console object is not defined. The normal console has a first letter uppercase, ie Console.
When a web test executes I am not sure where its "console" output will go. The standard output of a web test is not, as far as I know, a well defined thing.
An easy way to get at the response body is to use the PostRequest method of a WebTestRequestPlugin. For a start
public class BodyContentsDemo : WebTestRequestPlugin
{
public override void PostRequest(object sender, PostRequestEventArgs e)
{
byte[] bb = e.Response.BodyBytes;
string ss = e.Response.BodyString;
e.WebTest.AddCommentToResult(
"BodyBytes is " +
bb == null ? " null"
: bb.Length.ToString() + " bytes");
e.WebTest.AddCommentToResult(
"BodyString is " +
ss == null ? "null"
: ss.Length.ToString() + " chars");
// Use bb or ss.
}
}
Note the use of AddCommentToResult to provide logging information to the web test results log.
Finally I am able to find a solution for last couple of days I was struggling to capture the response text from Web Performance test. Hope this helps
public override IEnumerator GetRequestEnumerator()
{
WebTestRequest request2 = new WebTestRequest("webservice");
request2.Headers.Add("Content-Type", "application/json");
request2.Method = "POST";
request2.Encoding = System.Text.Encoding.GetEncoding("utf-8");
StringHttpBody request2Body = new StringHttpBody();
request2Body.ContentType = "application/json";
request2Body.InsertByteOrderMark = false;
request2Body.BodyString = #"{<body>}";
request2.Body = request2Body;
WebTestResponse res = new WebTestResponse();
console.WriteLine(res.BodyBytes);
yield return request2;
/*This will generate a new string which can be part of your filename when you run performance tests*/
String randomNo = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss").Replace("-", "").Replace(" ", "").Replace(":", "");
/*This will generate a new file each time your WebRequest runs so you know what the server is returning when you perform webtests*/
/*You can use some Json parser if your response is Json and capture and validate the response*/
System.IO.File.WriteAllText(#"C:\Users\XXXX\PerformanceTestRequests\LastResponse" + randomNo+ ".txt", this.LastResponse.BodyString);
request2 = null;
}

Verify app invite server-side

When our mobile app user sends app-invite to fb user and he accepts it, the server should give a reward to the first one. So I need a way to verify whether the invite was sent.
var fb = new FacebookClient(APP_ID + "|" + SECRET_ID);
fb.AppId = APP_ID;
fb.AppSecret = SECRET_ID;
dynamic result = fb.Get(???);
I searched on GraphAPI docs and it seems that I need to retrieve users apprequests. How to do that from the server side and where to look at to perform such verification?
UPDATE
Ok, now I know that it's allowed to reward only for accepted invites. I can record who invites who in the db and give a reward only when a new invited user joins. But I still need a way to verify that these invites were actually sent.
UPDATE2
As the documentation states apprequests call from application returns all the requests sent from this application. So I think it would be enough for me to just check that there are any requests from this app:
dynamic result = fb.Get("/" + facebookId + "/apprequests");
IEnumerable data = result.data;
return data.Cast<object>().Count() != 0;
But I can't check it now. Can anyone confirm that if a user sends invite to app to another user this invite will be seen through apprequests from the application access token?
my code for this:
public static FacebookRequestData GetInviteHash()
{
string requestId = Request["request_ids"];
var accessToken = GetAccessToken(ConfigurationManager.AppSettings["FacebookAppId"], ConfigurationManager.AppSettings["FacebookSecret"]);
string response;
using (var webClient = new WebClient())
{
response = webClient.DownloadString(string.Format("https://graph.facebook.com/{0}?{1}", requestId, accessToken));
}
var javaScriptSerializer = new JavaScriptSerializer();
return javaScriptSerializer.Deserialize<FacebookRequestData>(javaScriptSerializer.Deserialize<FacebookRequestInfo>(response).data);
}
private static string GetAccessToken(string appId, string password)
{
using (var webClient = new WebClient())
{
return webClient.DownloadString(string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", appId, password));
}
}
private class FacebookRequestInfo
{
public string data { get; set; }
}
FacebookRequestData - my custom class with structure of fields that I posted to fb earlier
Done it:
public static bool CheckInvite(string fromId, string toId)
{
var fb = new FacebookClient(APP_ID + "|" + SECRET_ID);
fb.AppId = APP_ID;
fb.AppSecret = SECRET_ID;
dynamic result = fb.Get(string.Format("/{0}/apprequests", toId));
foreach (var el in result.data)
if ((string)el.from.id == fromId)
{
DateTime dateTime = DateTime.Parse((string)el.created_time, CultureInfo.InvariantCulture);
if ((DateTime.Now - dateTime).TotalMinutes < 15)
{
return true;
}
}
return false;
}

Error reusing some async json method on windows phone

EDIT 1: I added below the code who calls and uses the second method, and the error and data I recive
First of all sorry if my English isn't good enough, and sorry if there is another thread with the solution. I haven't found it.
Ok, I'm making a windows phone 8 app that uses a lot of info from a web service. The app makes different Json Post and uses the info. I maked a method for Posting that WORKS:
public static async void checkdeviceid()
{
//Where we are posting to:
Uri theUri = new Uri("urlofexample");
//Create an Http client
HttpClient aClient = new HttpClient();
//Class that will be serialized into Json
objetoslistas.checkdeviceidinput paquete = new objetoslistas.checkdeviceidinput();
//Set some values
paquete.Text = "deviceID";
paquete.Text2 = App.device_id;
//serialize data
var serializado = JsonConvert.SerializeObject(paquete);
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, new StringContent(JsonConvert.SerializeObject(paquete), Encoding.UTF8, "application/json"));
if (aResponse.IsSuccessStatusCode)
{
string res = await aResponse.Content.ReadAsStringAsync();
var respuestaperfil = JsonConvert.DeserializeObject<objetoslistas.checkdeviceidoutput>(res.ToString());
//Do something with the data
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
}
}
This code its actually working, but the fact it's that my app will have maybe 30 or 40 diferent POST, so I tried to make a reusable method like this:
public static async Task<string> jsonPOST(Uri theUri, object paquete)
{
//Create an Http client and set the headers we want
HttpClient aClient = new HttpClient();
//serialize data
var serializado = JsonConvert.SerializeObject(paquete);
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, new StringContent(JsonConvert.SerializeObject(paquete), Encoding.UTF8, "application/json"));
if (aResponse.IsSuccessStatusCode)
{
string res = await aResponse.Content.ReadAsStringAsync();
return res;
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
return failureMsg;
}
}
This code gives me problems in the main, were it's called. As I can understand, the problem is that, as the method calls some await process, the rest of the code continues with the execution without expect for the await result...
The code in Main is:
objetoslistas.checkdeviceidinput paquete = new objetoslistas.checkdeviceidinput();
paquete.Text = "deviceID";
paquete.Text2 = App.device_id;
Uri url = new Uri("urlofhteservice");
Task<string> recibo = metodosJson.jsonPOST(url, paquete);
var respuestaperfil = JsonConvert.DeserializeObject<objetoslistas.checkdeviceidoutput>(recibo.ToString);
if (respuestaperfil.Text2 == null)
{
IsolatedStorageSettings.ApplicationSettings["DeviceRegistered"] = true;
}
else
{
IsolatedStorageSettings.ApplicationSettings["DeviceRegistered"] = false;
}
And I recive this error (translated from google translator, sorry)
There was an exception of type 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.DLL but not controlled in the user code
The data I have in "recibo" is
recibo Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" System.Threading.Tasks.Task<string>
So as I understand the await method is still waiting.
Was I clear?
Thanks

Categories