Object becomes null after calling HTTPClient.PostAsJsonAsync to access Web Api - asp.net

In my web form (ASP .Net 4.8, VB .Net), I have calling the following function from code-behind submit sales transaction via web api:
Public Async Function SendSale(fs As SaleTxnReqModel) As Task(Of SaleTxnRespModel)
Dim returnData As SaleTxnRespModel = New SaleTxnRespModel()
Dim apiUrl = "Sales/SendSale"
Dim resultRemark As String = String.Empty
Try
Using client = New HttpClient()
client.BaseAddress = New Uri(AppComp.NormalizeBaseUrl(constWebApiUri))
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsJsonAsync(apiUrl, content)
returnData = Await response.Content.ReadAsAsync(Of SaleTxnRespModel)()
If Not response.IsSuccessStatusCode Then
resultRemark = AppComp.SetWebServStatusText(response.StatusCode)
End If
End Using
Catch ex As Exception
resultRemark = AppComp.GetExceptionMessage(ex)
Finally
returnData.REMARK = resultRemark
End Try
Return returnData
End Function
At the receiving web api, the request object has become null. 
[Route("SendFuelSale")]
[HttpPost]
public IActionResult SendFuelSale(SaleTxnReqModel txn)
{
// Process sales transaction...
}
I have tried using SendAsync method and it worked:
Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")
Dim request = New HttpRequestMessage(HttpMethod.Post, apiUrl)
request.Content = content
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
I just wonder what went wrong when using PostAsJsonAsync  method.
Any idea? Please adivse. Thanks.

Related

getting data from Web Services c#

I have an issue loading data in the correct format from web services.
Web Service code:
[WebMethod]
public string LoadLearrner(string id)
{
MyFunctions func = new MyFunctions();
DataSet ds;
DataSet dtsta = SQLServer.GetDsBySP("Load_Learner_ForCRM","learnerId", id.ToString());
string[] cntName = new string[dtsta.Tables[0].Rows.Count];
List<string> list = new List<string>();
int i = 0;
foreach (DataRow rdr in dtsta.Tables[0].Rows)
{
list.Add(rdr[0].ToString());
list.Add(rdr[1].ToString());
list.Add(rdr[2].ToString());
list.Add(rdr[3].ToString());
list.Add(rdr[5].ToString());
i++;
}
String[] str = list.ToArray();
string JSONString=string.Empty;
JSONString = JsonConvert.SerializeObject(str);
return JSONString;
}
Code that's used to call the above web service method is:
WebRequest request = (HttpWebRequest)WebRequest.Create("http://abc/Company/CrmLearner.asmx/LoadLearrner?id=" + item.learner_id);
request.Method = "GET";
request.ContentType = "application/text";
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
Result is:
I don't want the result like that. I want to load proper XML or JSON and store it in an object.

Error in Instagram API

I am using asp vb.net and instagram api.
I found a tutorial on instagram api but it is in c#. I tried to convert from c# to VB the best I could but for some reason I am getting an error.
Error: The Remote Server Returned An Error 400 Bad Request
I am getting an error on line:
Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
My code:
Function GetDataInstagramToken()
Try
Dim parameters As New NameValueCollection
parameters.Add("client_id", Client_ID)
parameters.Add("client_secret", ClientSecret)
parameters.Add("grant_type", "authorization_code")
parameters.Add("redirect_uri", "http://localhost:8979/UI/InstaHome.aspx")
parameters.Add("code", Code)
Dim client As WebClient = New WebClient()
Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
Dim response = System.Text.Encoding.Default.GetString(result)
'deserializing nested JSON string to object
Dim jsResult As JObject = JsonConvert.DeserializeObject(response)
Dim accessToken As String = jsResult("access_token")
Dim id As Int16 = jsResult("user")("id")
'This code register id and access token to get on client side
Page.ClientScript.RegisterStartupScript(GetType(String()), "GetToken", "<script>var instagramaccessid=\"" + #"" + id + "" + " \ "; var instagramaccesstoken=\"" + #"" + accessToken + "" + " \ ";</script>")
Catch ex As Exception
myLabel.text += "-" &ex.message
End Try
End Function
In this line
client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
You don't send any value to Instagram. If you check your
parameter, you can see your key but you Can't see any
value.
Try this:
public async void GetTokenFromCode()
{
var values = new Dictionary<string, string> {
{ "client_id","Your ChatId" },
{ "client_secret", "Your Client Secret" },
{ "grant_type", "authorization_code" },
{ "redirect_uri", "Your Redirect url"},
{ "code", "code" } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.instagram.com/oauth/access_token", content);
var responseString = await response.Content.ReadAsStringAsync();
}

Not able to get query string

I am using the below code for setting URL in the current http context
public HttpContext SetNewHttpContext(string uRL)
{
var httpRequest = new HttpRequest("", uRL, "");
var httpResponse = new HttpResponse(new StringWriter());
return new HttpContext(httpRequest, httpResponse);
}
Invoking it as under
HttpContext.Current = SetNewHttpContext("http://root/test.aspx?userid=319279549&name=xyz");
var val = HttpContext.Current.Request.QueryString["userid"];
But i am not able to get the value of the querystring(userid here) and getting null.
Why?
Please help
Uri tempUri = new Uri("http://root/test.aspx?userid=319279549&name=xyz");
string sQuery = tempUri.Query;
NameValueCollection queryString =
System.Web.HttpUtility.ParseQueryString(sQuery ,Encoding.UTF8);

how to parse xml string from Post method response?

I have a xml string that return from Post method:
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
var stream = new GZipInputStream(response.GetResponseStream());
using (StreamReader reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
response.Close();
}
The responseString is the string I want to parse, using parseXmlString class below. However I can't call the method parseXmlString directly because of the static. How can I pass the responseString to the parseXmlString method to have them parse out and bind to the listBox. Or anyway to have the same result would be great.
void parseXmlString()
{
byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
MemoryStream str = new MemoryStream(byteArray);
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("tracks").Elements("item")
select new searchResult
{
artist = (string)query.Element("artist"),
album = (string)query.Element("album"),
track = (string)query.Element("track"),
// artistA = (string)query.Element("artists").Element("artist"),
};
// ListBox lb = new ListBox();
listBox1.ItemsSource = data;
var data1 = from query in xdoc.Descendants("artists").Elements("item")
select new searchResult
{
artistA = (string)query.Element("artist"),
};
listBox2.ItemsSource = data1;
}
Your approach is inversed logic. You know that you can have return values on methods, right?-)
What you need to do is let your ParseXmlString method take the responseString as a parameter, and let it return the created IEnumerable, like this:
private IEnumerable<SearchResult> ParseXmlString(responseString)
{
XDocument xdoc = XDocument.Load(responseString);
var data =
from query in xdoc.Descendants("tracks").Elements("item")
select new SearchResult
{
Artist = (string)query.Element("artist"),
Album = (string)query.Element("album"),
Track = (string)query.Element("track"),
};
return
from query in xdoc.Descendants("artists").Elements("item")
select new SearchResult
{
ArtistA = (string)query.Element("artist"),
};
}
And change your async code handling, to perform a callback to your UI thread, when it's done reading out the responseString.
Then, on your UI thread, you would do:
// This being your method to get the async response
GetResponseAsync(..., responseString =>
{
var searchResults = ParseXmlString(responseString);
listBox2.ItemsSource = searchResults;
})
You can see this answer, if you need some basic understanding of callbacks: Callbacks in C#

apns and asp.net

I'm building and iPhone application the use push notification, all is ok. but now i'm going to build the server side with ASP.net. can any one help mee... coz i tired to get a solution using Google but unfortunately i didn't find any thing.
....
note: i tried this link http://arashnorouzi.wordpress.com/2011/03/31/sending-apple-push-notifications-in-asp-net-part-1/
but the post not completed yet
After days of work. I chose to work with Urbanairship which provides a full push server:
Dim request As WebRequest = WebRequest.Create("https://go.urbanairship.com/api/push/broadcast/")
Dim postData As String = "{""aps"": {""badge"": ""+1"", ""alert"": ""Estez Mohamad lamaa!"",""sound"": ""default""}}"
request.Credentials = New NetworkCredential("uorecode", "uorkey")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/json"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
I saw part 4 is out with a useful sample code.
http://arashnorouzi.wordpress.com/2011/06/19/sending-apple-push-notifications-in-asp-net-and-c-%e2%80%93-part-4-apns-sharp-c-wrapper-class/
It is definitely finished.
I used it, and it works great.
However i'm not sure what's its licensing.
I use Prowl for notifications from ASP.NET:
public static void PushNotification(string header, string message)
{
new Thread(() =>
{
var prowlURL = string.Format("https://api.prowlapp.com/publicapi/add?apikey={YOURKEY}&application={0}&description={1}", header, message);
WebClient wc = null;
try
{
wc = new WebClient();
wc.UploadString(new Uri(prowlURL), "");
}
catch
{
}
finally
{
if (wc != null)
{
wc.Dispose();
wc = null;
}
}
}) { Name = "PushNotification", IsBackground = true }.Start();
}

Resources