How to call specific line in HTTP Get from XML - c#

Right now I get a full dump of this XML...
http://smart-ip.net/geoip-xml/68.5.63.33
What I want my program to do is just call the city and region from that XML.
I'm new to web services so I'm having trouble trying to figure out how to do this, help is much appreciated
Here is my code:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
XmlTextReader myXMLReader = null;
try
{
XPathNavigator nav;
XPathDocument docNav;
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myXMLReader = new XmlTextReader(myHttpWebResponse.GetResponseStream());
docNav = new XPathDocument(myXMLReader);
nav = docNav.CreateNavigator();
nav.MoveToRoot();
nav.MoveToFirstChild();
do
{
if (nav.NodeType == XPathNodeType.Element)
{
nav.MoveToFirstChild();
do
{
txtIPresults.Text = txtIPresults.Text + nav.Name + " - " + nav.Value + Environment.NewLine; //Display
} while (nav.MoveToNext());
}
} while (nav.MoveToNext());
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
myXMLReader = null;
}

If I understand correctly you are trying to get the values from the countryName and city elements from the XML response.
This can be done in the following way using the XDocument class from the System.Xml.Linq namespace:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
try
{
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
//---- <Added code> -------
var doc = XDocument.Load(myHttpWebResponse.GetResponseStream());
var geoip = doc.Element("geoip");
var country = geoip.Element("countryName").Value;
var city = geoip.Element("city").Value;
Console.WriteLine(country + " - " + city);
//---- </Added code> -------
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
}
It's also possible to use the XDocument.Load() method to load the XML response using the url string directly:
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
var doc = XDocument.Load(weatherURL);

I would do something like this:
try
{
WebClient wc = new WebClient();
wc.Headers.Add();//ADD ALL YOUR HEADERS IF YOU NEED
var xml = wc.DownloadString(string.Format("http://smart-ip.net/geoip-xml/{0}", txtIP.Text));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var name = doc.DocumentElement.SelectSingleNode("//countryName").Value;
txtIPresults.Text = name
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
I don´t know for sure if it have more performance than HTTP REQUEST/RESPONSE but the code is very small and easy to maintain.

Related

API Call not successful

Good day Guys,
I am trying to Use an SMS API. Everything looks fine from my end but the SMS is not delivering. If i use the URL directly on Browser, it executes.
Or is anything wrong with how i built the string?
Below is the code.
Please Note tht cbo.Title is a comobox, txtFirstname is a Textbox.
public void NewText()
{
string username = "something#gmail.com";
string password = "Password";
string urlStr;
string message=" Dear " + cbo_Title.Text + " " + txt_FirstName.Text + ", Your New Savings Account Number is " + Account_No + ".Welcome to AGENTKUNLE Global Services. Your Future is Our Priority ";
string sender = "AGENTKUNLE";
string recipient=txt_Phone.Text;
urlStr = "https://portal.nigeriabulksms.com/api/?username="+username+"+password="+password+"+sender="+sender+"+message="+message+"+ mobiles="+recipient;
Uri success = new Uri(urlStr);
}
private string SendSms(string apiUrl)
{
var targetUri = new Uri(apiUrl);
var webRequest = (HttpWebRequest) WebRequest.Create(targetUri);
webRequest.Method = WebRequestMethods.Http.Get;
try
{
string webResponse;
using (var getresponse = (HttpWebResponse) webRequest.GetResponse())
{
var stream = getresponse.GetResponseStream();
if (stream != null)
using (var reader = new StreamReader(stream))
{
webResponse = reader.ReadToEnd();
reader.Close();
}
else
webResponse = null;
getresponse.Close();
}
if (!string.IsNullOrEmpty(webResponse?.Trim()))
return webResponse.Trim();
}
catch (WebException ex)
{
ErrorHelper.Log(ex);
}
catch (Exception ex)
{
ErrorHelper.Log(ex);
}
finally
{
webRequest.Abort();
}
return null;
}
You never make a request.
The Uri object is just a container for the uri (see Microsoft Docs).
Check out the HttpClient class if you want to send a request.

Delete File in SharePoint folder using C#

I am using SharePoint ExcelService to manipulate an excel file and then save it to the Shared Documents folder using
ExcelService.SaveWorkbookCopy()
Now I want to delete those files I saved earlier. What is the best way to achieve this using C# in a Asp.Net MVC Application?
I tried it using the REST Service, but I could not really find any tutorials and as the code is now, I get a WebException "The remote server returned an error: (403) Forbidden."
I tried two versions for my REST URL, neither worked.
var fileSavePath = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/Shared%20Documents/";
var excelRestPath_1 = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/_api/web/";
var excelRestPath_2 = "http://sharepointserver/_api/web/";
public static bool DeleteExcelFromSharepoint(int id, string excelRestPath)
{
try
{
string filePath = "/Shared%20Documents/" + id + ".xlsm";
string url = excelRestPath + "GetFileByServerRelativeUrl('" + filePath + "')";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "DELETE";
request.Headers.Add(HttpRequestHeader.IfMatch, "*");
request.Headers.Add("X-HTTP-Method", "DELETE");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException(String.Format("DELETE failed. Received HTTP {0}", response.StatusCode));
}
return true;
}
}
catch (Exception ex)
{
CustomLogger.Error("Error deleting Excel from Sharepoint", ex);
return false;
}
}
Use nuget package Microsoft.SharePointOnline.CSOM:
using (var sp = new ClientContext("webUrl"))
{
sp.Credentials = System.Net.CredentialCache.DefaultCredentials;
sp.Web.GetFileByServerRelativeUrl(filePath).DeleteObject();
sp.ExecuteQuery();
}
that will ensure that file is removed - if you want to make sure the file existed during removal:
using (var sp = new ClientContext("webUrl"))
{
sp.Credentials = System.Net.CredentialCache.DefaultCredentials;
var file = sp.Web.GetFileByServerRelativeUrl(filePath);
sp.Load(file, f => f.Exists);
file.DeleteObject();
sp.ExecuteQuery();
if (!file.Exists)
throw new System.IO.FileNotFoundException();
}
If you are using REST, you can refer to the link
(https://msdn.microsoft.com/en-us/library/office/dn450841.aspx#bk_File)
My example code is:
string resourceUrl = "https://<BaseURL>/sites/<SubSite>/_api/web/GetFileByServerRelativeUrl('/sites/<SubSite>/Documents/New Folder/xyz.docx')";
var wreq = WebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.Headers.Remove("X-FORMS_BASED_AUTH_ACCEPTED");
wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
wreq.Headers.Add("X-HTTP-Method", "DELETE");
//wreq.Headers.Add("Authorization", "Bearer " + AccessToken);
wreq.UseDefaultCredentials = true;
wreq.Method = "POST";
wreq.Accept = "application/json; odata=verbose";
wreq.Timeout = 1000000;
wreq.AllowWriteStreamBuffering = true;
wreq.ContentLength = 0;
string result = string.Empty;
string JsonResult = string.Empty;
try
{
WebResponse wresp = wreq.GetResponse();}
catch (Exception ex)
{
LogError(ex);
result = ex.Message;
}
Having tried the answers above and but still not getting the files deleted I found this and it works perfectly
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(“FullSharePointURIofDocument“);
request.Timeout = System.Threading.Timeout.Infinite;
request.Credentials = new
System.Net.NetworkCredential(“SharePointUser“,”SharePointUserPassword“);
request.Method = “DELETE“;
var response = (System.Net.HttpWebResponse)request.GetResponse();
thanks to BizTalkBox

Why this method is called twice and at the first time the return doesn't work?

A flash application uses AMF message format to call the method SyncAddressBook (c#),and in this method ,it calls other two WebApis using HttpWebRequest (post and get ).
But only when calling WebApi (the method SyncAddressBook ), the method can return to flash well, when calling WebApi (the method SyncAddressBook ), the method SyncAddressBook can not return to the one which called it (i didnot write this method here) ,instead, it return itself. and for the second time, the method SyncAddressBook returned with error to flash .
here is the method (I omit something)
public AMFGreetoAddressBookResult SyncAddressBook(AMFGreetoLogin loginArgs, AMFGreetoAddressBook addressBook)
{
var result = new ........
this.PostReceiversGroups(addressBook, accessKey);
this.GetReceivers(accessKey, out receivers);
result.ResultCode = true;
return result;
}
private Boolean PostReceiversGroups(AMFGreetoAddressBook addressBook, string accessKey)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(addressBook);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(json);
httpWebRequest.ContentLength = bytes.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Account acc = JsonConvert.DeserializeObject<Account>(result);
}
}
catch (Exception e)
{
throw new Exception("住所管理サービスの更新処理でエラーが発生しました。[PostReceiversGroups] :" + e);
}
return true;
}
private Boolean GetReceivers(string accessKey, out AMFGreetoReceiver[] receivers)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
receivers = null;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
var ser = new JavaScriptSerializer();
receivers = ser.Deserialize<AMFGreetoReceiver[]>(result);
streamReader.Close();
httpResponse.Close();
}
}
catch (Exception e)
{
throw new Exception("Receivers取得処理でエラーが発生しました。[GetReceivers] :" + e);
}
return true;
}

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

I keep receiving the script say "window.location.reload()" when use httpwebrequest

<!--#R--><script>
var k ='c991130d';
var d = new Date();
d.setTime(d.getTime() + (3600*24*365*5*1000));
document.cookie = "p7c=" + k +";
expires=" + d.toGMTString();
setTimeout(function(){
window.location.reload(); },2000);
</script>
please wait....
when I use my code to get a web page I keep getting these, but I can use XMLhttp with VB to get the whole page, it's my code below:
public static string GetPage(string Url)
{
HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
WebRequest.Timeout = 5000;
WebRequest.AllowAutoRedirect = true;
WebRequest.Headers.Set("Pragma", "no-cache");
try
{
using (HttpWebResponse response = (HttpWebResponse)WebRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{ return sr.ReadToEnd(); }
}
}
}
catch (Exception ex){ return "%ERROR%" + ex.Message; }
}

Categories