HttpWebRequest memory leak issue with Newtonsoft - memory

I have an application that calls an API via the below function.
Public Function CreateWebRequest(ByVal strURL As String) As JArray
Try
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(strURL), HttpWebRequest)
request.Method="GET"
request.ContentType = "application/json"
request.Credentials = CredentialCache.DefaultNetworkCredentials
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As StreamReader
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim array As JArray = JArray.Parse(rawresp)
reader.Close()
response.Close()
Return array
End Using
Catch ex As Exception
Dim empty As New JArray
Return empty
End Try
End Function
I noticed recently that sometimes I get a timeout on my server (Taking too much time to respond). Digging more into details, I wanted to check if I have a memory leaking issue with the function I used to call the API.
Is there anything wrong in the above function? Do I need to close any connection or clear any memory that I haven't done?

Related

Storing Value in HttpCookie

Using MVC.
Function Login(ByVal token As String) As ActionResult
Using client As New WebClient
Try
Dim jsonResponse As String = client.DownloadString(URL & "/Getuser&token=" & token)
Dim obj As UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(Of UserInfo)(jsonResponse)
Response.Cookies.Add(New HttpCookie("token", token))
Response.Cookies.Add(New HttpCookie("user_id", obj.id))
Return Json(obj)
Catch ex As WebException
Return Content("ERROR")
Catch ex As Exception
Return Content("ERROR")
End Try
End Using
End Function
I am sending a token to this function.
Then Using this token to get the User Info from a certain API
Then Storing this token in a HttpCookie
All this has been working fine for almost a month,
Until it stopped working.
When I debugged, token had a value, and it stored it in the HttpCookie, but when I called Request.Cookies("token").Value it returned ''
Any help would be appreciated.
I did a trace on the Token..
I am writing the parameter "token" in a file before storing it in the cookie.
then I am writing the cookie Request.Cookies("token").Value in a file,
Function Login(ByVal token As String) As ActionResult
WriteToFile("TOKEN RECEIVED = ", token)
Using client As New WebClient
Try
Dim jsonResponse As String = client.DownloadString(URL & "/Getuser&token=" & token)
Dim obj As UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(Of UserInfo)(jsonResponse)
Response.Cookies.Add(New HttpCookie("token", token))
Response.Cookies.Add(New HttpCookie("user_id", obj.id))
WriteToFile("TOKEN COOKIE = ", Request.Cookies("token").Value)
Return Json(obj)
Catch ex As WebException
Return Content("ERROR")
Catch ex As Exception
Return Content("ERROR")
End Try
End Using
End Function
it returns the following:
TOKEN RECEIVED = X132WEeRT3AASDV
TOKEN COOKIE =
When I try to write both Request and Response Cookies:
WriteToFile("TOKEN COOKIE = ", Request.Cookies("token").Value)
WriteToFile("TOKEN COOKIE = ", Response.Cookies("token").Value)
Request.Cookies("token").Value Returns Empty String
Response.Cookies("token").Value Returns Actual Value
Maybe your cookie just expire after one month? When using cookies don't forget to set expiration date, and check web browser settings (example: if you are using "tor browser bundle" this can be an issue).
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
https://msdn.microsoft.com/en-us/library/78c837bd%28v=vs.140%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Make sure you access the cookies only during the actual Http request. Maybe you have changed the way (or place where) you call this function.
This is an old question on SO but for those interested, .NET team has created a new method to properly handle cookies.
This is available in .NET 4.7.1 and not earlier versions:
See under the section ASP.NET HttpCookie parsing here
https://blogs.msdn.microsoft.com/dotnet/2017/09/13/net-framework-4-7-1-asp-net-and-configuration-features/

Issue with uploading Preview image on Ooyala

I am using Ooyala sdk for C# and got a problem with uploading image for specific content. Here is my code. will be happy to get some help:
OoyalaAPI o = new OoyalaAPI(apikey, secretkey);
byte[] bytess = File.ReadAllBytes(#"C:\Users\Daniel\Desktop\FIRE2.jpg");
Hashtable booody = new Hashtable();
string exception = "";
object p = o.postBytes("assets/I2ZDlzbjrIFtbAxzrkJ3NLzEDR30jFYh/preview_image_urls", new Dictionary<string, string>(), bytess, out exception, null); //Upload File
booody.Add("type", "uploaded_file");
o.put("assets/I2ZDlzbjrIFtbAxzrkJ3NLzEDR30jFYh/primary_preview_image", new Dictionary<string, string>(), booody, out exception); //Pick The Thumbnail File
The Exception i get is (400) Bad Request from the function response = request.GetResponse()
as HttpWebResponse;
I will appreciate some help with this issue.
Changed preview_image_urls to preview_image_files...
Works good now.

Posting Data Unix WebAPI using asp.net mvc

I am trying to post data to a Unix API, where it first will verify username and password, and then save the data which was sent.
The code I am using as of now is:
string strUrl = string.Format("http://moktrp.com/inf0/?username=fds- Sale003&password=CBA203&type=0&dlr=1&destination={0}&itemCode=1003);
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readstream = new StreamReader(s);
string datastring = readstream.ReadToEnd();
response.Close();
s.Close();
readstream.Close();
return true;

download google fusion table using c#

I'm trying to download a Fusion table programatically using C# only not .NET. I'm having trouble finding a decent API or C# example code to do so. Is that even possible?
HttpWebRequest request = WebRequest.Create(this.url2 + "?sql=SELECT * FROM 'table id'") as HttpWebRequest;
request.Method = "GET";
request.Headers.Add("Authorization", "GoogleLogin auth=" + this.token);
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
return reader.ReadToEnd();
}
What am I doing wrong?

Sending Jagged Array as parameter to WCF Service using KSOAP2 in android

I am having an issue with sending a jagged Array to a wcf webservice. The method is expecting a studentId and jaggedArray of information related to the student. Here is the method signature in c#
String[][] SearchStudent(string studentId, String[][] additionalInformation);
According to KSOAP wiki page, the below piece of code should have worked. I've also tried it with Hashtable; it returned the same error message.
SoapObject additionalInformation = new SoapObject(NAMESPACE, "SearchStudent");
additionalInformation.addProperty("StudentFirstName", "John");
additionalInformation.addProperty("StudentLastName", "Doe
additionalInformation.addProperty("StudentDOB", "06101990");
SoapObject request = new SoapObject(NAMESPACE, "Authenticate");
request.addProperty("sessionId", params[0]);
request.addProperty("additionalInformation ", AuthParams);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.bodyOut = request;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;
(new MarshalHashtable()).register(envelope);
androidHttpTransport.call(SOAP_ACTION + "SearchStudent", envelope);
SoapObject sResult = (SoapObject)envelope.getResponse();
I am getting the message Invalid argument error message.
What am I doing wrong here?
I was able to get it to work with envelope.version 10 and not 11. Here is the link to my other post where you can find the solution.

Resources