Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved - asp.net

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

Related

HttpWebRequest Exception

I try to do httprequest with asp.net and C#. And I get an exception with message "The Web server refused the connection. The Web server refused the connection"
This is my code:
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Proxy = proxy; // Proxy's credentials have login and password
try
{
using (var response = (HttpWebResponse) webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
string str = sr.ReadToEnd();
}
}
return null;
}
And in method webRequest.GetResponse() I get WebException that I read in catch block. str variable contains html-code that looks like this:
http://i.stack.imgur.com/3QIn3.png
Unfortunatelly I can not post images.
How can I fix this error?
P.S. If it is important I use Forefront TMG but I dont know whether it can affect

The remote server returned an error: (400) Bad Request. When try to login with facebook in asp.net

I am try to login with a user with Facebook account in my website, but the applcation gives me error that The remote server returned an error: (400) Bad Request.
Below is my code:
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "[You user agent]";
webRequest.Timeout = 50000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
*It gives me error in this method:*
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
Ooo been a while since Iv'e played with webRequest but I think your problem might be
webRequest.GetResponse().GetResponseStream().Close();
in the finally block. Since you've already called
webRequest.GetResponse().GetResponseStream()
in the body of try block. Documentation states:
The GetResponse method sends a request to an Internet resource and
returns a WebResponse instance. If the request has already been
initiated by a call to GetRequestStream, the GetResponse method
completes the request and returns any response.
Therefore as I read it, the response had already been returned in the try block and then when you call it again in the finally block, it fails...since it's already been retrieved. Just comment out that line and see how you go. The StreamReader should close the underlying connection when you close it.
So try:
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
responseReader.Close();
}
return responseData;
}

Problems sending and receiving JSON between ASP.net web service and ASP.Net web client

You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks
Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .
I use this code .
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request =
System.Net.HttpWebRequest.Create("http://spsdev2:1009");
System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();
//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();
I get error in myReq.GetResponse();
Error :The remote server returned an error: (401) Unauthorized.
Edit
This code work for me :)
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I add credentials for HttpWebRequest.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}

Request a page with server code

I need to request a series of pages and want to do from the server code as if you were doing with Ajax, I can do?, thanks
You're looking for the WebClient class.
Use this c# function. Add using System.Net; top of your page.
private string MakeWebRequest(string url) {
string retValue = String.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
StreamReader stReader = new StreamReader(response.GetResponseStream());
retValue = stReader.ReadToEnd();
stReader.Close();
response.Close();
stReader.Dispose();
stReader = null;
response = null;
request = null;
}
catch (Exception ex) {
}
return retValue;
}

Resources