How to close browser after creating C# WebClient class? - c#

I provide an HTTP web service and one of my users is using C# WebClient class on a Windows 2003 machine to retrieve data from my website. My user says that WebClient is creating many browser instances and needs to be closed. How can he close the browser after it's created?
His code:
Byte[] requestedHTML;
WebClient client = new WebClient();
requestedHTML = client.DownloadData("http://abcabc.com/abc");
UTF8Encoding objUTF8 = new UTF8Encoding();
string returnMessage = objUTF8.GetString(requestedHTML);
p.s. Apologies if this sounds amateur, I'm very new to C#.

WebClient does not use a browser - it it just a wrapper around the underlying protocol. You should add a using, but this has nothing to do with "many browser instances":
using(WebClient client = new WebClient())
{
return client.DownloadString("http://abcabc.com/abc");
}

The WebClient class in the .NET Framework holds onto some system resources which are required to access the network stack in Microsoft Windows. The behavior of the CLR will ensure these resources are eventually cleaned up.
However, if you manually call Dispose or use the using-statement, you can make these resources be cleaned up at more predictable times. This can improve the performance of larger programs.
using(WebClient client = new WebClient())
{
// Do your operations here...
}
You can refer this beautiful tutorial: http://www.dotnetperls.com/webclient

Related

How to define HttpClient BaseAdress dynamically

I have an Asp.Net webpage written in c#. This webpage is communicating with a host on a server. The server adress is actually hardcoded in my controller methods as
static PatientController()
{
//Create the HttpClient once and use it
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://localhost:9002/prom2etheus/v1/");
_patientList = new List<Patient>();
}
How can I configure the URI as a parameter, that a user can enter at the start of the UI? My problem is, that the host is running on a server, and my UI is running on the same server, but in a Docker container. So the IP of the host can change, and I don't want to hardcode the IP of the host in my controller method. Which is the better way to do?
It depends. If you want the url to persist, then storing it in a database or a file is a good idea.
On the other hand, if it is okay to propt user every time the app starts, it could be stored in memory. This would jave the added benefit that, it would be much faster to read/write since there's no IO. There could be othet storage options such as third party storage provides too. In both cases, you would have to think about thread safety.

C# Cant to download JDK15

I'm trying to download JDK15 but i downloading 5307 bytes but this are not the JDK15
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(new System.Uri(
"https://download.oracle.com/otn-pub/java/jdk/15.0.1%2B9/51f4f36ad4ef43e39d0dfdbaf6549e32/jdk-15.0.1_windows-x64_bin.exe"),
Path.Combine(directoryPackagesPath, "jdk.exe")
);
}
You downloaded a web page instructing you how to access the download:
You cannot directly download that file. If you open it in another browser, or a incognito/private window, you will see this message:
Sorry!
In order to download products from Oracle Technology Network you must
agree to the OTN license terms.
If you open the downloaded file, most likely it's an HTML with this message.
It is illegal, but if you want learn how to do it for some CTF etc.:
Get query what is send after accepting licence by dev tools in your browser.
Send the exact same query by HttpClient and get cookies from response.
Use this cookies to get the file.
If you want this particular version, you can attach it (if licence allows you to do that) to your program by using installer, by resources or even as normal file in output directory.

Best way to create python web service and c# client application

I am looking for a simple and reliable way to create Python Web Service and consume it from the .Net (c#) application.
I found plenty of different libraries, where one is better than another, but nobody seems to have a complete working example with Python Web Service and some simple c# client. And reasonable explanations of steps to configure and run
I am suggesting using Tornado. It is very simple to use, non-blocking web-server written in Python. I've been using it in the past and I was shocked how easy it was to learn and use it.
I am strongly encouraging you to design your API with REST in mind. It will make your API simple, and easy to consume by any language/platform available.
Please, have a look at the 'Hello World' sample - it has been taken from Torando's main site:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
As for the client part - there is nothing complicated:
string CreateHTTGetRequest(string url, string cookie)
{
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.Headers.Add("Cookie", cookie);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
In case the server is running on your local machine, the URI is: 'http://localhost:8888/'
you may start your practice by:
Install ZSI
Create a WSDL for your service
The full example
4.On client(C#) follow this tutorial

can asp.net run without .net framework

i am very new to asp.net. I would like to ask can asp.net run without the .net framework? as in can default.aspx run smoothly without the .net framework? I am asking this due to the following existing code which was runned on a web hosting server and another is a private server. I am not sure about the private server details ( going to know in a 2-3 days)...the code goes as...
try
{
WebRequest req = WebRequest.Create(General.SiteUrl + "/pages/" + page + ".htm");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
content = reader.ReadToEnd();
}
catch { content = "<html><head></head><body>Content not found.</body></html>"; }
the web hosting server manage to run the "Try" successfully whereas the private one always shows content not found....any ideas guys?
People that visit your website will not need the .NET Framework; all they'll need is a browser.
The server that runs your website will need the .NET Framework since ASP.NET is a part of it.
The .NET Framework is required on the Server side for a few reasons (these are just some examples):
Your code is compiled into an intermediate language designed to be platform agnostic. A runtime (The .NET Framework) is required to convert this intermediate language into something the machine can understand. This is accomplished by the JIT.
There are several libraries in ASP.NET; System.Web.dll; for example. These are distributed as part of the .NET Framework.
The code is hosted inside of a virtual machine (in the non-traditional sense). The virtual machine takes care of a lot of heavy lifting for you; such as security; garbage collection; etc. Again; this is all part of the .NET Framework.
EDIT:
I think you are asking the wrong question here. You ask wondering why your code is going inside of the catch block and returning Content not found. The .NET Framework is properly installed since the catch block is being called; in fact it couldn't get nearly that far without the .NET Framework.
You need to figure out what exception is being thrown inside of the try block that is causing it to go into the catch block. You can achieve this with a debugger; logging; or temporarily removing the catch block all together to get the server to let the exception bubble all the way up to the top. For example; if you change your code block to look like this:
WebRequest req = WebRequest.Create(General.SiteUrl + "/pages/" + page + ".htm");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
content = reader.ReadToEnd();
The exception details will be displayed in the browser (provided you have debugging turned on). What error is displayed without the try / catch?
No, .Net code will not run without support of the .Net framework. Because code written in .Net language will be compiled and converted to IL (Intermediate Language) Code.
The .NET framework, or some variation of, e.g. Mono, is not required on the client side. This is a requirement of the server which is serving the pages.
When data is sent to the client via HTTP, it is translated into HTML. So all the client would need would be a browser capible of consuming HTML and running any scripts associated with that site.
the .net framework is the foundation that powers this code
try
{
WebRequest req = WebRequest.Create(General.SiteUrl + "/pages/" + page + ".htm");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
content = reader.ReadToEnd();
}
catch
{
content = "<html><head></head><body>Content not found.</body></html>";
}
so in short, "no", you must have the .net framework installed on the server that is hosting your website.
On the other hand however, on the client side, your website visitors do NOT need the .net framework to "view" your website.

Difference between FileStream and WebClient

So, I'm actually trying to setup a Wopi Host for a Web project.
I've been working with this sample (the one from Shawn Cicoria, if anyone knows this), and he provides a whole code sample which tells you how to build the links to use your Office Web App servers with some files.
My problem here, is that his sample is working with files that are ON the OWA server, and i need it to work with online files (like http://myserv/res/test.docx. So when he reads his file content, he's using this :
var stream = new FileStream(myFile, FileMode.Open, FileAccess.Read);
responseMessage.Content = new StreamContent(stream);
But that ain't working on "http" files, so i changed it with this :
byte[] tmp;
using (WebClient client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
tmp = client.DownloadData(name);
}
responseMessage.Content = new ByteArrayContent(tmp);
which IS compiling. And with this sample, i managed to open excel files in my office web app, but words and powerpoint files aren't opened. So, here's my question.
Is there a difference between theses two methods, which could alter the content of the files that i'm reading, despite the fact that the WebClient alows "online reading" ?
Sorry for the unclear post, it's not that easy to explain such a problem x) I did my best.
Thanks four your help !
Is there a difference between theses two methods, which could alter
the content of the files that i'm reading, despite the fact that the
WebClient allows "online reading"
FileStream open a file handle to a file placed locally on disk, or a remote disk sitting elsewhere inside a network. When you open a FileStream, you're directly manipulating that particular file.
On the other hand, WebClient is a wrapper around the HTTP protocol. It's responsibility is to construct HTTP request and response messages, allowing you to conveniently work with them. It has no direct knowledge of a resources such as a file, or particularly where it's located. All it knows is to construct message complying with the specification, sends a request and expects a response.

Categories

Resources