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.
Related
I need to call a web service on an old legacy system and I pilfered some code to do that from an old Silverlight app (which I didn't write) that is targeting .NET 4. I verified the code works. However when I put that code in my app targeting .NET Core 3.1 I get the following error when calling ReadToEnd() on the StreamReader:
System.IO.IOException: 'The response ended prematurely, with at least 185 additional bytes expected.'
I created two identical console apps, one targeting .NET 4.7, the other targeting .NET Core 3.1, and sure enough, it worked on 4.7 but not on Core 3.1. I know code page 1252 is not supported in .net Core and I played around with other values to see if that was the issue with no luck.
I've found what I would consider a hacky workaround, spinning it byte by byte and using the Peek() method (ReadLine() doesn't work either) so I know I'm actually getting data back but I'm hoping the brilliant minds out there can help me understand 1) why ReadToEnd() is throwing in .NET Core and 2) whether there's a better way to do this, keeping in mind I have no control of the web service on the legacy system.
Thanks in advance for your help!
WebRequest requestGetPODetails = WebRequest.Create(myURL);
requestGetPODetails.Method = "POST";
var postContentsBuffer = Encoding.GetEncoding(1252).GetBytes(someXML);
requestGetPODetails.ContentLength = postContentsBuffer.Length;
using (Stream sfdDataStream = requestGetPODetails.GetRequestStream())
sfdDataStream.Write(postContentsBuffer, 0, postContentsBuffer.Length);
// Retrieve the results
using (WebResponse responseGetPODetails = requestGetPODetails.GetResponse())
{
Encoding enc = Encoding.GetEncoding(1252);
using (StreamReader sfdDataStreamReader = new StreamReader(responseGetPODetails.GetResponseStream(), enc))
{
string stringResponse = sfdDataStreamReader.ReadToEnd(); // Error occurs here in .NET Core
}
}
Huge thanks to Alexei Levenkov! You were exactly right--the service was incorrectly reporting the length of the stream. I reached out to the legacy developer and he was able to fix that and now all is well.
The weird thing is that this was working under .NET Framework but not Core so something apparently changed with Core as it now cares that the length is reported accurately.
Thanks again!
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
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
I'm a C# game programmer with little web development experience.
I need to upload a small file (25-100 or so bytes, depending on it's content) to a server. This is on the Windows Phone 7 using XNA. The target server is fairly limited and only supports PHP and classic ASP.
Since the CF on the WP7 only has access to a limited subset of networking commands, it's looking like an HttpWebRequest GET aimed at a script that saves the file will be the best option. The data I'm sending is small in size, and should be able to be passed as a parameter in the url.
I've been searching but have yet to find a complete example of this, which handles both the client and server side script (mainly the latter). This is close to what I'm looking for, except it has no mention of the server side script: Upload files with HTTPWebrequest (multipart/form-data)
The closest that I got was this: http://www.johny.org/2007/08/upload-using-c-as-client-and-php-as-server/
But when attempting to use it I get an unhandled exception: "The remote server returned an error: (405) Method Not Allowed". This method seems the most promising so far, but I've yet to be able to debug this.
Unfortunately, I have a short amount of time to implement this, and as I said only a passing familiarity with web development. I'm not worried about maximum security or scalability as this is a temporary measure to collect feedback internally. Basically, I just need the quickest thing that works. ;)
Any help would be fantastic!
I've solved it. First off, PHP wasn't supported on my server (just now learning that PHP and ASP are can't be used on the same server, depending on whether it's on Linux or Windows - like I said, web development noob here!). I switched to ASP and, after digging through the docs, wrote this script:
<%
dim theData, theFileName
set theData=Request("data")
set theFileName=Request("filename")
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile(Server.MapPath(theFileName+".txt"))
tfile.WriteLine(theData)
tfile.Close
set fname=nothing
set fs=nothing
set theData=nothing
set theFileName=nothing
%>
This C# code uploads the file:
const string cAddress = "http://site.com/folder/upload.asp";
string fileName = foo;
string data = bar;
string address = cAddress + "?filename=" + fileName + "&data=" + data;
uploadRequest = (HttpWebRequest) HttpWebRequest.Create(address);
uploadRequest.Method = "GET";
uploadRequest.GetResponse();
Hope this helps someone else looking for an example of how to do this!
But you have the METHOD as GET instead of POST. You can't upload a file to a website by passing the file path to the Query String.
I would like to have an offline ClickOnce application (they can run it from Start menu), but I would like my application to function similar to an online one (make sure the web page / server is there to run). This way I can take off (uninstall) a ClickOnce application, and it will stop working for end users without having to go to 1000's of desktops. This is for an internal corporate environment, so we have total control over the servers, end clients, etc.
There are a lot of clients out there world wide. Essentially, I would like to give them a message like "This applications functionality has been moved to XXX application, please use it instead." Or "This application has been retired." If I could get the install folder URL from code, I could have a message.xml file sitting in that directory that would have some logical tags in it for accomplishing this. If that message isn't there (server offline) I could have the application fail gracefully and instruct the user to contact their local IT for assistance.
Or can this same thing be accomplished in a different way?
I've used the following code to solve part of your problem:
try
{
// The next four lines probe for the update server.
// If the update server cannot be reached, an exception will be thrown by the GetResponse method.
string testURL = ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
HttpWebRequest webRequest = WebRequest.Create(testURL) as HttpWebRequest;
webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
// I discard the webResponse and go on to do a programmatic update here - YMMV
}
catch (WebException ex)
{
// handle the exception
}
There may be some other useful exceptions to catch as well -- I've got a handful more in the code I use, but I think the rest all had to do with exceptions that the ClickOnce update can throw.
That handles the missing server case -- though it does require you to have been proactive in putting this in place well before the server is retired.
You can only get the deployment provider URL if the application is online-only. Otherwise it's not available.
Aside from moving a deployment, you can programmatically uninstall and reinstall the application.
You deploy the new version (or whatever you want to install instead) to another URL. Then you add uninstall/reinstall code to the old version and deploy it. When the user runs it, he will get an update, and then it will uninstall itself and call the new deployment to be installed.
The code for uninstalling and reinstalling a ClickOnce application can be found in the article on certificate expiration on MSDN, Certificate Expiration in ClickOnce Deployment.
You could create a new version of your application which only contains a messagebox saying "This application is retired" and deploy it.
The next time a user starts the application the new version will be downloaded showing your messagebox.
What I did was to combine the comments on this question, and some sprinkling of my own to come out with this answer below.
XML Document saved as an HTML (our web servers don't allow XML transfers):
<?xml version="1.0" encoding="utf-8"?>
<appstatus>
<online status="true" message="online"/>
</appstatus>
Then I have the following code read from the above, and use it to see if the application should close or not:
string testURL = "";
try
{
// Probe for the update server.
// If the update server cannot be reached, an exception will be thrown by the GetResponse method.
#if !DEBUG
testURL = ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString() + "online.html";
#else
testURL = "http://testserver/appname/online.html";
#endif
HttpWebRequest webRequest = WebRequest.Create(testURL) as HttpWebRequest;
webRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
XmlDocument xmlDom = new XmlDocument();
xmlDom.Load(reader);
if (xmlDom["usdwatcherstatus"]["online"].Attributes["status"].Value.ToString() != "true")
{
MessageBox.Show(xmlDom["usdwatcherstatus"]["online"].Attributes["message"].Value.ToString());
this.Close();
return;
}
}
catch (WebException ex)
{
// handle the exception
MessageBox.Show("I either count not get to the website " + testURL + ", or this application has been taken offline. Please try again later, or contact the help desk.");
}