This is my code which is returning the expected output on my friend's PC, but not on mine.
We are both working with Visual Studio 2017 Community:
enter image description here
This is the code that will return latitude and longitude of the entered address:
[enter image description here][2]
The first time it works fine but after that its throwing (403 forbidden error !!! / mainly problem is on the request.getResponse())
private static String[] x = new String[3];
public static String[] GetFirstLastName(string address)
{
try {
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
// request.Timeout = 0;
// request.Abort();
response.Close();
return x;
}
}
catch(Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
public static String[] GetFirstLastName1(string address)
{
try
{
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
//// request.Timeout = 0;
/// request.Abort();
response.Close();
return x;
}
}
catch (Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
static void Main(string[] args)
{
int i = 0;
for (;;)
{
String x = Console.ReadLine();
if (i == 0)
{
String[] y = GetFirstLastName(x);
Console.WriteLine(y[0] + " " + y[1]);
}
else
{
String[] y = GetFirstLastName1(x);
Console.WriteLine(y[0] + " " + y[1]);
}
i++;
}
//Console.ReadKey();
}
}
}
/*(Same Code above)
enter code here
///My Friends Output
/// My Output
[2]: https://i.stack.imgur.com/qeDcz.png */
Glad to see you've joined StackOverflow!
Now a 403 error occurs usually not in relation to a syntax error in your code but in relation to the response received from Google's servers.
Now Google in particular is very restrictive on how many API calls you can make a day (Google makes a lot of money off developers who pay for lots of API calls). This page contains the limits. If you've made more than the numbers in here, that's why you're getting the error and you'll have to wait until tomorrow. Do keep in mind not to send too many http requests and accidentally DOS them, as they'll blacklist you for this.
Make sure you are not caching their page or storing the js script locally as this will also cause a blacklist.
Make sure you use https: and not http: here.
Related
I'm trying to learn programming by myself the best I can but, seems like my code isn't as productive as it can be. I'm trying to learn by doing things that I would use on a normal occasion and I can't figure out how to properly manage it, so any information would be greatly appreciated.
I'm working on a discord bot for personal use at the moment, it works fine, the loadout time is just terrible when it comes to this part of the command. Maybe cause I'm trying to have it open, read, and close multiple databases? Or is there another explanation or method to doing this that can make it load within a faster time?
string NormalExp = "0";
string IronExp = "0";
string HCExp = "0";
string UIMExp = "0";
//Normal Account
try
{
WebRequest NormalScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=" + player);
WebResponse NormalResponse = NormalScore.GetResponse();
using (Stream NormalDStream = NormalResponse.GetResponseStream())
{
StreamReader NormalReader = new StreamReader(NormalDStream);
string NormalResponseFromServer = NormalReader.ReadToEnd();
var _Score = NormalResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
NormalExp = _TotalExp;
}
NormalResponse.Close();
}
catch (Exception)
{
}
//Normal Ironman
try
{
WebRequest IronScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_ironman/index_lite.ws?player=" + player);
WebResponse IronResponse = IronScore.GetResponse();
using (Stream IronDStream = IronResponse.GetResponseStream())
{
StreamReader IronReader = new StreamReader(IronDStream);
string IronResponseFromServer = IronReader.ReadToEnd();
var _Score = IronResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
IronExp = _TotalExp;
}
IronResponse.Close();
}
catch (Exception)
{
}
//Hardcore Ironman
try
{
WebRequest HCScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_hardcore_ironman/index_lite.ws?player=" + player);
WebResponse HCResponse = HCScore.GetResponse();
using (Stream HCDStream = HCResponse.GetResponseStream())
{
StreamReader HCReader = new StreamReader(HCDStream);
string HCResponseFromServer = HCReader.ReadToEnd();
var _Score = HCResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
HCExp = _TotalExp;
}
HCResponse.Close();
}
catch (Exception)
{
}
//Ultimate Ironman
try
{
WebRequest UIMScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_ultimate/index_lite.ws?player=" + player);
WebResponse UIMResponse = UIMScore.GetResponse();
using (Stream UIMDStream = UIMResponse.GetResponseStream())
{
StreamReader UIMReader = new StreamReader(UIMDStream);
string UIMResponseFromServer = UIMReader.ReadToEnd();
var _Score = UIMResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
UIMExp = _TotalExp;
}
UIMResponse.Close();
}
catch (Exception)
{
}
await ReplyAsync(
$"**Normal: ** {NormalExp}\n" +
$"**Ironman: ** {IronExp}\n" +
$"**Hardcore: ** {HCExp}\n" +
$"**UIM: ** {UIMExp}");
if (Convert.ToInt64(UIMExp) == Convert.ToInt64(NormalExp))
{
await ReplyAsync("Account is a UIM");
}
else if (Convert.ToInt64(HCExp) == Convert.ToInt64(NormalExp))
{
await ReplyAsync("Account is a HC");
}
else if (Convert.ToInt64(IronExp) == Convert.ToInt64(NormalExp) && Convert.ToInt64(IronExp) > Convert.ToInt64(UIMExp + HCExp))
{
if (Convert.ToInt32(UIMExp) > 1)
{
await ReplyAsync("Account is a ~~UIM~~ Normal Ironman");
}
else if (Convert.ToInt64(HCExp) > 1)
{
await ReplyAsync("Account is a ~~HC~~ Normal Ironman");
}
else
{
await ReplyAsync("Account is a Normal Ironman");
}
}
else
{
if (Convert.ToInt64(UIMExp) > 1 && Convert.ToInt64(IronExp) > 1)
{
await ReplyAsync("Account is a ~~UIM~~, ~~Ironman~~, normal player.");
}
else if (Convert.ToInt64(HCExp) > 1 && Convert.ToInt64(IronExp) > 1)
{
await ReplyAsync("Account is a ~~HC~~, ~~Ironman~~, normal player.");
}
else if (Convert.ToInt64(IronExp) > 1 && Convert.ToInt64(HCExp) == 0 && Convert.ToInt64(UIMExp) == 0)
{
await ReplyAsync("Account is a ~~Ironman~~ normal player.");
}
else
{
await ReplyAsync("Account is a Normal Player");
}
}
In general, sending requests is an expensive operation but you can improve it by changing your method.
Try to use HttpClient instead of WebRequest
and I suggest reading about Async/Sync operations
I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...
I am using ThreadPool.QueueUserWorkItem for threading in C# WinForms, but it makes the main UI hangs don't know why, is there any other good way for threading rather than ThreadPool which make the UI goes smooth!
ThreadPool.QueueUserWorkItem(new WaitCallback(KeywordSearch), cts);
private void KeywordSearch(object r)
{
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] alphas = (alphabet + alphabet.ToLower()).ToCharArray();
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.WaitCursor;
});
}
else
{
this.Cursor = Cursors.WaitCursor;
}
foreach (char a in alphas)
{
MessageBox.Show(a.ToString());
string correctkeywordforQuery = KeywordTxt.Text + " " + a;
var webRequest = WebRequest.Create(#"https://clients1.google.com/complete/search?client=youtube&hl=en&gl=us&sugexp=ytfdc%2Ccfro%3D1%2Cfp.dquf%3D1&gs_rn=64&gs_ri=youtube&ds=yt&cp=2&gs_id=6l&q=" + correctkeywordforQuery + "&callback=google.sbox.p50&gs_gbg=7dNuEZN941O5Tlh1iM");
string result;
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
var strContent = reader.ReadToEnd();
result = strContent.Replace("google.sbox.p50 && google.sbox.p50(", ""); ;
//text.Remove(text.ToString().LastIndexOf(character), character.Length);
result = result.Remove(result.Length - 1);
}
var jsonser = new JavaScriptSerializer();
var obj = jsonser.Deserialize<dynamic>(result);
foreach (var x in obj[1])
{
//CancellationToken token = (CancellationToken)r;
//if (token.IsCancellationRequested)
//{
// cts.Cancel();
// return;
//}
var value1 = x[0]; // bd felek
// MessageBox.Show(value1);
string thecorrectlinktogetallthedata = "https://www.youtube.com/results?search_query=" + value1+ "&hl=en";
// Process.Start(thecorrectlinktogetallthedata);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n"+thecorrectlinktogetallthedata;
});
}
else
{
richTextBox1.Text += "\r\n" + thecorrectlinktogetallthedata;
}
// Process.Start(thecorrectlinktogetallthedata);
// create the constructor with post type and few data
//show the response string on the console screen.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(thecorrectlinktogetallthedata);
string htmlcontent = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
htmlcontent = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(htmlcontent);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n" + htmlcontent;
});
}
else
{
richTextBox1.Text += "\r\n" + htmlcontent;
}
//watch?v
HtmlAgilityPack.HtmlNodeCollection Nodes = document.DocumentNode.SelectNodes("//a");
//MessageBox.Show(Nodes.Count.ToString());
foreach (HtmlAgilityPack.HtmlNode node in Nodes)
{
string ahref = node.Attributes["href"].Value;
string classname = node.GetAttributeValue("classname", string.Empty);
//MessageBox.Show(ahref);
if (ahref.Contains("watch?v"))
{
string title = node.GetAttributeValue("title",string.Empty);
if(title.Trim().ToString()!= string.Empty)
{
//newRows[0] = title;
//newRows[1] = ahref; ;
if (ResultGrid.InvokeRequired)
{
ResultGrid.BeginInvoke((MethodInvoker)delegate ()
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//MessageBox.Show(title);
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
});
}
else
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
}
}
}
}
break;
}
}
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.Default;
});
}
else
{
this.Cursor = Cursors.Default;
}
}
I'm working in a project in which I want to add list<restaurant > in a web API method and return different types of mixed between restaurant and rest_location.
The relation between restaurant and rest_location is one to many.
When I run it, the error appears:
{"Message":"The requested resource does not support http method 'GET'."}
Server web API:
[HttpPost]
[Route("api/Restaurants/res_by_locat/{x}/{res_loc}")]
[ResponseType(typeof(Restaurant))]
[ResponseType(typeof(Rest_Location))]
public HttpResponseMessage GetResturantsBylocation([FromUri]int x,[FromBody] List<Rest_Location> res_loc)
{
List<Table> table = new List<Table>();
var lstitem = from t1 in res_loc
from t2 in db.Restaurants.Where(y => y.R_ID == t1.R_ID )
.DefaultIfEmpty()
select new { t1.L_Adress, t2.R_Name };
//foreach (var item in lstitem)
//{
// table.Add(item);
//}
if (lstitem == null || !lstitem.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
else return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new { lstitem });
}
Client:
protected void btn_ddl_Click(object sender, EventArgs e)
{
if (locationddl.SelectedValue == "0")
{
lbl_result.Text = "Chose a Location First ! ";
}
else
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:10566/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var fromddl = locationddl.SelectedItem.Text;
//lbl_result.Text = fromddl;
var response = client.GetAsync("api/Locations/getid_by_name/" + fromddl).Result;
// if (Page.IsValid)
{
if (response.IsSuccessStatusCode)
{
Location ll = response.Content.ReadAsAsync<Location>().Result;
int x = ll.L_ID;
lbl_msg.Text = x.ToString();
var response2_get_ids_Rests = client.GetAsync("api/Rest_Location/res_by_locat/" + x).Result;
if (response2_get_ids_Rests.IsSuccessStatusCode)
{
List<Rest_Location> rests_locations = response2_get_ids_Rests.Content.ReadAsAsync<List<Rest_Location>>().Result;
//var items= rests_locations.FirstOrDefault(rl => rl.L_ID == x);
// GridView2.DataSource = rests_locations;
// GridView2.DataBind();
HttpResponseMessage response3_get_resturants_by = client.PostAsJsonAsync("api/Restaurants/res_by_locat/" + x , rests_locations).Result;
if (response3_get_resturants_by.IsSuccessStatusCode)
{
var news= response3_get_resturants_by.Content.ReadAsAsync<List<Restaurant>>().Result;
GridView1.DataSource = news;
GridView1.DataBind();
lbl_msg.Text = "Search succesed";
}
else
{
lbl_test.Text = " not found ";
}
}
else
{
lbl_test.Text = " not found ";
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "Couldn't Found Resaurants ! " + ex.ToString();
}
}
}
You endpoint has this attribute, [HttpPost], implying that it can only be accessed using POST
Your client is attempting to access the endpoint using GET.
You should use client.PostAsync method instead of GetAsync.
I'm a newbie using c# and i need to create an extension that goes to a directory and retrieves info about the users like username, name and email.
This is the login validation method that i created and it's working.
public void MssValidateUserLDAP(string ssHostname, string ssBaseDN, string ssUsername, string ssPassword, out bool ssOk, out string ssErrorMessage) {
ssOk = false;
ssErrorMessage = string.Empty;
String ssBaseRDN = string.Empty; // stores user RDN for authentication
LdapConnection connection = new LdapConnection(ssHostname);
connection.AuthType = AuthType.Basic;
try
{
SearchRequest searchRequest = new SearchRequest();
// Search parameters
searchRequest.Scope = System.DirectoryServices.Protocols.SearchScope.OneLevel;
searchRequest.DistinguishedName = ssBaseDN;
searchRequest.Filter = ssUsername;
// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
// enumerate the entries in the search response
foreach (SearchResultEntry entry in searchResponse.Entries)
{
ssBaseRDN = entry.DistinguishedName;
ssOk = true;
}
if (ssBaseRDN != "")
{
connection.Bind(new NetworkCredential(ssBaseRDN, ssPassword));
}
else { ssOk = false; ssErrorMessage = "User not found"; }
}
catch (Exception e)
{
ssErrorMessage = e.GetType().Name + " " + e.Message;
ssOk = false;
}
}
This is what i was able to do, but it's not working and i can't find the reason behind that. Any help would be appreciated!
public void MssSearch(string ssUsername, string ssPassword, string ssPath, out RLUserRecordList ssUsers, out string ssErrorMessage) {
ssErrorMessage = "";
ssUsers = new RLUserRecordList(null);
try
{
RLUserRecordList aux = new RLUserRecordList();
DirectoryEntry rootEntry = new DirectoryEntry(ssPath,ssUsername,ssPassword);
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
foreach(SearchResult result in searcher.FindAll())
{
RCUserRecord u = new RCUserRecord(Convert.ToString(result.Properties["cn"][0]));
aux.Append(u);
}
ssUsers = aux;
}
catch (Exception e){
ssErrorMessage = e.GetType().Name + " " + e.Message;
}
} // MssSearch