How to save image from remote URL using C# asp.net? - asp.net

I am working on asp.net C# website in that I getting problem when I try to save image from remote URL.
I have tried with below c# code ...
// C# code
string remoteImageUrl= "http://www.bitpixels.com/getthumbnail?code=83306&url=http://live.indiatimes.com/default.cms?timesnow=1&size=200";
string strRealname = Path.GetFileName(remoteImageUrl);
string exts=Path.GetExtension(remoteImageUrl);
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImageUrl,Server.MapPath("~/upload/")+strRealname + exts);
When I fetch image from above remoteImageUrl then I getting error "An exception occurred during a WebClient request."
How can I fetch and save remote url image and store it my website upload directory.
or any other way to get remote url image.

I solved that problem The exception comes due to the extension..
When I getting extension of the remoteImageUrl Path.
string exts = Path.GetExtension(remoteImageUrl);
string strRealname = Path.GetFileName(remoteImageUrl);
It returns ".cms" so exception throws at that point,
I avoid the ".cms" extension from the remoteImageURL and then call
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImageUrl,Server.MapPath("~/upload/")+strRealname + exts);
It works fine.

Yout code is just fine. Make sure your application pool identity, has access to "upload" folder with write access.
And if you are using a proxy server you should also specify this in web.config file.
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>
</system.net>

Are you running under anything less than full trust? If so, you can't make arbitrary web requests either.

Related

difference between launch site from iis and iis express

So i have tiny asp.net application containing the only page.
It is code from Page_Load method (it is only code in code-behind):
string url = "https://api.vkontakte.ru/oauth/access_token?client_id=123&client_secret=123&code=123&redirect_uri=mysite.com";
var webRequest = (HttpWebRequest)WebRequest.Create(url);
/*
if i comment this line
i get exception an exception with following message
The remote server returned an error: (407) Proxy Authentication Required
*/
webRequest.Proxy = null;
using (var response = (HttpWebResponse)webRequest.GetResponse()) //
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string str = reader.ReadToEnd();
TokenBox.Text = str;
}
}
So what is my problem? This application is deployed in iis 7.5. When i ise it as iis site i get an exception WebException with message "Unable to connect to the remote server". But if i press F5 button in Visual Studio and debug my web application with IIS Express this code works fine.
What is the reason of this weird behavior? How can i fix it and make my app to work properly from IIS site?
https://blog.lextudio.com/2015/04/web-application-differences-in-visual-studio-and-iis/
To make a request out, .NET/Windows requires proper networking settings (such as proxy, authentication and so on), which might be OK for your account to run the code in VS. However, IIS obviously won't guarantee the code to work, because you did not yet set the application pool identity with the same networking settings.

Silverlight app inside of a asp.net page - The remote server returned and error: NotFound

I've embedded my Silverlight app inside of an asp.net page (of a different project) with the following code:
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="SilverlightApplication1.xap"/>
</object>
And it loads up the GUI just fine. However, when the first call to a database is made I receive the error "CommunicationException was unhandled by user code. The remote server returned and error: NotFound."
The Silverlight app works just fine when I run it alone, but when embedded in this page on this other project it doesn't work correctly. I've included both the ProjectView.Web and the Silverlight App itself in the second projects solution, and I changed the output path of the app to the folder where the .aspx file of the page is located.
I've been looking around for awhile and haven't really found anything that helps, it seems that the error is generic and could be anything. I'm thinking it's not able to find the services references because the paths have changed but I'm not entirely sure.
I like Entity Framework for my back end. In the designer it automatically assigns the connection string to the Db on the host computer(development) then when I deploy I use the overload for the container when initialized which is the Connection String to the server Db.
Public Shared Function ModelConnStr() As String
Dim sqlcon As New System.Data.SqlClient.SqlConnectionStringBuilder
sqlcon.DataSource = "tcp:{domain}.com"
sqlcon.InitialCatalog = "db"
sqlcon.UserID = "id"
sqlcon.Password = "pswd"
Dim mdlcon As New System.Data.EntityClient.EntityConnectionStringBuilder
mdlcon.Metadata = "res://*/BMModel.csdl|res://*/BMModel.ssdl|res://*/BMModel.msl"
mdlcon.Provider = "System.Data.SqlClient"
mdlcon.ProviderConnectionString = sqlcon.ConnectionString
Return mdlcon.ConnectionString
End Function
So the same concept applies, use localhost for testing, then before you upload/publish you change the connection string.

Get application root from Request object that works locally and remotely

Let's say that I have my ASP.NET web application in a directory called "MyApp" both locally and on a remote server. I'm trying to build an onclick response to a link. The response calls a Javascript function, passing it the URL of an .aspx page in my web app. The Javascript pops out a new window displaying the page. My C# code looks like this:
link = new HyperLink();
link.Text = product_num_str;
link.NavigateUrl = "#";
string url = "Javascript:My_NewWindow('http://" +
HttpContext.Current.Request.Url.Authority +
"/ProductInfo.aspx?_num=" + product_num_str + "')";
link.Attributes.Add("onclick", url);
I started using the Request's Authority property because I was having problems running locally on the Visual Studio web server when I used the Host property. The problem was that Host only returned "localhost" instead of the host and port number.
When tested locally, the code works because the "authority" maps to my app root folder. The URL generated is, e.g.,
http://localhost:52071/ProductInfo.aspx?_num=123
If I run on a remote server, however, I end up with something like:
http://company-server/ProductInfo.aspx?_num=123
This fails to find the page, because in this case the "MyApp" root folder must be included.
There is probably an easier way - putting an entry in the web.config or something. My motivation originally was to allow the app to be published to a folder of any name and work as is.
I could hack my approach and search the string for "localhost" or something, but that's ugly. So how do I build a string that will work everywhere?
I'm assuming you're doing this from within a Page or Control. If that's the case you should do this instead:
string fullUrl = this.ResolveClientUrl("~/ProductInfo.aspx?_num=" + product_num_str + ");
That will give you the proper URL no matter where the application is deployed.

show webservice soapexception response in the client in ASP.NET

I am trying to make a Test Webservice and throw a SoapException. But when I open the service through browser, it shows Internal server error - 500.
If i try to consume it manually by sending a manually created SoapRequest (in stringbuilder), I get the same error "Servererror - 500" in Visual Studio itself in the line "WebResponse response = req.GetResponse()"
Is there anyway I can actually see the "fault in response XML".
It sounds like there is something wrong with the service and you need to debug it on the server side rather than the client side. I come to this conclusion because you have a problem with your client code and a web browser.
Assuming you are using .NET have you enabled display of ASP.NET errors on the server? See this article for info.
Update:
So you are throwing an error on the server and want to get the error text on the client? An error on the server is supposed to result in a 500 error message and is unlikely to return any XML to the client. Perhaps you can pass something to the SoapException constructor?
Have you looked at the docs for SoapException? They have some examples of passing information using the Detail property of SoapException.
Can you get to the asmx (assuming you are using asmx) in the browser to see if it is working at all?
after surfing through for 5-6 hours finally got it......here it is:
When you are getting the response manually, use the following:
try
{
WebResponse response = req.GetResponse();
Stream str = response.GetResponseStream();
StreamReader rdr = new StreamReader(str);
Response.Write(rdr.ReadToEnd());
Response.End();
}
catch (WebException webEx)
{
Stream str = webEx.Response.GetResponseStream();
StreamReader rdr = new StreamReader(str);
Response.Write(rdr.ReadToEnd());
Response.End();
}

ASP.NET Image uploading from URL

I have an aspx page,where the user will enter a valid image url(ex : https://stackoverflow.com/Content/Img/stackoverflow-logo-250.png).
I need the program to upload this image to the Server.
How can i do this ?
System.Net.WebClient webClient = new WebClient();
webClient.DownloadFile(#"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png",
#"c:\path\localfile.png");
You can use Server.MapPath to get physical directory on the server corresponding to the relative or virtual path, for example Server.MapPath("~/Images")

Resources