Google Api is not giving location - google-maps

I am using google API to get location in my project. It gives location sometimes but most of the time it does not give any location. and from today it is giving server return an error 403 forbidden.
When i am hitting the URL in my browser it is giving location.
I am not using any key for my API can it cause this issue.
Just to add-
I get the lat and long from my api and then i get the location from google api and stores it in my database.
What i am doing is:-
public static string getGoogleLocationByLogLat(string log, string lat)
{
try
{
if (log == "")
{
log = "0.0";
}
if (lat == "")
{
lat = "0.0";
}
XmlTextReader xReader;
bool element = false;
string location = "", time, GL, parentEmail, respDateTime;
string parentElementName = "";
string childElementName = "";
string childElementValue = "", prmryCntact = "";
string url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + lat + "," + log + "&sensor=true";
xReader = new XmlTextReader(url);
while (xReader.Read())
{
if (xReader.NodeType == XmlNodeType.Element)
{
if (element)
{
parentElementName = parentElementName + childElementName + "<br>";
}
element = true;
childElementName = xReader.Name;
}
else if (xReader.NodeType == XmlNodeType.Text | xReader.NodeType == XmlNodeType.CDATA)
{
element = false;
childElementValue = xReader.Value;
if (childElementName == "formatted_address")
{
location = childElementValue;
break;
}
}
}
if (location.Trim() == "")
{
location = "Location not found";
}
return location;
}
catch (Exception ex)
{
return "LOCATION NOT FOUND";
}
}

Add your API key
&key=yourkey
With the latest policy updates to the maps api, i believe this must be the case that you're hitting...
Also use https ... It's permitted only over https

Related

How to send JSON objects to another computer?

Using Websockets, I am able to use 1 computer and 1 kinect v2.0 to generate JSON objects of the joints x,y, and z coordinates in real-time. The next steps is to have this data transferred to another computer, using possibly TCP/IP network. My question is to anyone who knows how this is done. Having this data transferred to another computer.
Output that needs to be transferred to another computer in real-time
namespace WebSockets.Server
{
class Program
{
// Store the subscribed clients.
static List<IWebSocketConnection> clients = new List<IWebSocketConnection>();
// Initialize the WebSocket server connection.
static Body[] bodies = new Body[6];
//static KinectSensor kinectSensor = null;
static CoordinateMapper _coordinateMapper;
static Mode _mode = Mode.Color;
static void Main(string[] args)
{
//const string SkeletonStreamName = "skeleton";
//SkeletonStreamMessage skeletonStreamMessage;// = new SkeletonStreamMessage { stream = SkeletonStreamName };
KinectSensor kinectSensor = KinectSensor.GetDefault();
BodyFrameReader bodyFrameReader = null;
bodyFrameReader = kinectSensor.BodyFrameSource.OpenReader();
ColorFrameReader colorFrameReader = null;
colorFrameReader = kinectSensor.ColorFrameSource.OpenReader();
_coordinateMapper = kinectSensor.CoordinateMapper;
kinectSensor.Open();
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
server.Start(socket =>
{
socket.OnOpen = () =>
{
// Add the incoming connection to our list.
clients.Add(socket);
};
socket.OnClose = () =>
{
// Remove the disconnected client from the list.
clients.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "get-video")
{
int NUMBER_OF_FRAMES = new DirectoryInfo("Video").GetFiles().Length;
// Send the video as a list of consecutive images.
for (int index = 0; index < NUMBER_OF_FRAMES; index++)
{
foreach (var client in clients)
{
string path = "Video/" + index + ".jpg";
byte[] image = ImageUtil.ToByteArray(path);
client.Send(image);
}
// We send 30 frames per second, so sleep for 34 milliseconds.
System.Threading.Thread.Sleep(270);
}
}
else if (message == "get-bodies")
{
if (kinectSensor.IsOpen)
{
if (bodyFrameReader != null)
{
bodyFrameReader.FrameArrived += bodyFrameReader_FrameArrived;
}
}
}
else if (message == "get-color")
{
if (kinectSensor.IsOpen)
{
if (colorFrameReader != null)
{
colorFrameReader.FrameArrived += colorFrameReader_FrameArrived;
}
}
}
};
});
// Wait for a key press to close...
Console.ReadLine();
kinectSensor.Close();
}
private static void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame()) {
if (colorFrame != null) {
var blob = colorFrame.Serialize();
foreach (var client in clients)
{
if (blob != null)
{
client.Send(blob);
Console.WriteLine("After color Blob sent");
}
}
}
}
}
private static void bodyFrameReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (bodies == null)
{
bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(bodies);
dataReceived = true;
}
}
if (dataReceived)
{
foreach (var client in clients)
{
var users = bodies.Where(s => s.IsTracked.Equals(true)).ToList();
if (users.Count>0){
string json = users.Serialize(_coordinateMapper, _mode);
Console.WriteLine("jsonstring: " + json);
Console.WriteLine("After body serialization and to send");
}
}
}
}
}
}
Try changing it from
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
to
WebSocketServer server = new WebSocketServer(" ws://192.168.X.X:8001");
on the client end. Enter the IP address of the client computer and make sure both server and client are on the same network.

Get Thumbnail in Vimeo

Is there any way to get the thumbnail from server side call?
The only method that I researched is:
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoId + '.json?callback=?', { format: "json" }, function (data) {
$(".thumbnail").attr('src', data[0].thumbnail_medium);
});
Is there a way to make the same call from code behind? or is there a single URL call like in youtube
img.youtube.com/vi/{0}/0.jpg
List item
I found a way to do this from code behind:
public static string GetVimeoPreviewImage(string videoId)
{
var imageUrl = string.Empty;
try
{
var doc = new XmlDocument();
doc.Load("http://vimeo.com/api/v2/video/" + videoId + ".xml");
var root = doc.DocumentElement;
if (root != null)
{
var selectSingleNode = root.FirstChild.SelectSingleNode("thumbnail_medium");
if (selectSingleNode != null)
{
var vimeoThumb = selectSingleNode.ChildNodes[0].Value;
imageUrl = vimeoThumb;
return imageUrl;
}
}
}
catch (Exception ex)
{
var message = string.Format("{0} Exception: {1}", typeof(VideoHelper).FullName, ex.Message);
Log.Error(message, typeof(VideoHelper));
}
return imageUrl;
}

No results in Australia using Bing Maps SOAP

I'm creating an app for WP8 and i've been using the Bing Maps tutorial. However I don't get any results in Australia. Do I need to use a completely different API? geolocale contains a string such as "20.002, -150.2222" even if I change it to just "California" it gets results. What am I doing wrong?
I've tried to find answers in a lot of places but can't seem to find anything that's relevant.
try
{
searchService.SearchCompleted += new EventHandler<SearchService.SearchCompletedEventArgs>(MySearchCompleted);
SearchService.SearchRequest mySearchRequest = new SearchService.SearchRequest();
mySearchRequest.Credentials = new SearchService.Credentials();
mySearchRequest.Credentials.ApplicationId = "key";
SearchService.StructuredSearchQuery ssQuery = new SearchService.StructuredSearchQuery();
ssQuery.Keyword = "coffee";
ssQuery.Location = geolocale;
mySearchRequest.StructuredQuery = ssQuery;
searchService.SearchAsync(mySearchRequest);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Coordinate 20.002, -150.2222 is in the middle of the Pacific ocean. Also, the Bing Maps SOAP services are an old legacy API. The Bing Spatial Data Services should be used.
http://msdn.microsoft.com/en-us/library/ff701734.aspx
http://rbrundritt.wordpress.com/2012/01/17/dynamically-updating-data-in-bing-maps-v7/
To use the Bing Spatial Data Services in WP8 first copy the Response, ResultSet, and Result classes from this project: http://code.msdn.microsoft.com/Augmented-Reality-with-bcb17045/sourcecode?fileId=85735&pathId=1819751232
You can then use the following code to generate your search query.
string baseURL;
//Switch between the NAVTEQ POI data sets for NA and EU based on where the user is.
if (Longitude < -30)
{
//Use the NAVTEQ NA data source: http://msdn.microsoft.com/en-us/library/hh478192.aspx
baseURL = "http://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/NavteqPOIs";
}
else
{
//Use the NAVTEQ EU data source: http://msdn.microsoft.com/en-us/library/hh478193.aspx
baseURL = "http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs";
}
//Search radius should be converted from meters to KM.
string poiRequest = string.Format("{0}?spatialFilter=nearby({1:N5},{2:N5},{3:N2})&$format=json&$top={4}&key={5}",
baseURL, Latitude, Longitude, SearchRadius / 1000, MaxResultsPerQuery, BingMapsKey);
You will need a method to pass this query to and serialize the results. Use the following:
private void GetResponse(Uri uri, Action<Response> callback)
{
System.Net.WebClient client = new System.Net.WebClient();
client.OpenReadCompleted += (s, a) =>
{
try
{
using (var stream = a.Result)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
if (callback != null)
{
callback(ser.ReadObject(stream) as Response);
}
}
}
catch (Exception e)
{
if (callback != null)
{
callback(null);
}
}
};
client.OpenReadAsync(uri);
}
Finally you will need to call the GetResponse method to make your query like this:
GetResponse(new Uri(poiRequest), (response) =>
{
if (response != null &&
response.ResultSet != null &&
response.ResultSet.Results != null &&
response.ResultSet.Results.Length > 0)
{
//Do something with the results
}
});

EWS Managed API with pull subscriptions

I am writing a bridge to synchronise our client application with EWS via the managed API.
I'm running into a lot of problems caused by the fact that I don't know who has last updated the appointment I'm working with(Outlook client/owa/My bridge).
There are certain appointments (tagged with a category[0] = 'Booking') that I don't want the user to modify, but I cant tell whether it was updated by the user or my bridge.
is there a way I can create the appointment as Read-only, or get the old info for the appointment and revert it back ?
I've tried to kind of show what I mean below :
public void TimerCallback(object source, ElapsedEventArgs e)
{
FPollTimer.Enabled = false;
try
{
GetEventsResults notificationEvents = FCalendarSubscription.GetEvents();
EWSMethods.monitorFRM.log("Notification count = " + FEWSUser + ":" + notificationEvents.AllEvents.Count.ToString());
if (notificationEvents.AllEvents.Count > 0)
{
foreach (ItemEvent itemEvent in notificationEvents.ItemEvents)
{
// -- check to see if this is a valid appointment -- //
// -- Echange creates two appts and deletes one of -- //
// -- them for any appointment creation -- //
try
{
//Folder tempFolder = Folder.Bind(FEWSService, itemEvent.ParentFolderId.ToString());
EWSMethods.monitorFRM.log("Notification-" + FEWSUser + " : " + itemEvent.EventType.ToString());
// -- Is this item in the stack? -- //
if (NeedPingPongcheck(itemEvent))
{
CheckPingPong(itemEvent);
}
else
{
Appointment o_appointment = Appointment.Bind(FEWSService, itemEvent.ItemId.ToString());
if (o_appointment != null) WriteEventToDB(itemEvent);
}
}
catch (Exception exc2)
{
EWSMethods.monitorFRM.log("TimerCallBack inner " + exc2.Message);
}
}
}
}
catch (Exception exc)
{
EWSMethods.monitorFRM.log("timercallback outer " + exc.Message);
//MessageBox.Show(e.Message);
}
FPollTimer.Enabled = true;
}
public void WriteEventToDB(ItemEvent item)
{
try
{
EWSMethods.monitorFRM.log("Attempting write to DB ");
string s_allday;
string s_appointmentid;
//MessageBox.Show(item.ItemId.ToString());
// -- use the old item id for deleted (moved) appointments -- //
if (item.EventType == EventType.Moved)
{
s_appointmentid = item.OldItemId.ToString();
}
else
{
s_appointmentid = item.ItemId.ToString();
}
// Get all properties of email message
PropertySet pset = new PropertySet(BasePropertySet.FirstClassProperties);
// Get the body in text
pset.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;
// -- set up allDay flag -- //
Appointment o_appointment = Appointment.Bind(FEWSService, item.ItemId.ToString(),pset);
if ((o_appointment.IsAllDayEvent) & (o_appointment != null))
{
s_allday = "Y";
}
else
{
s_allday = "N";
}
// --
if (o_appointment.Categories[0] != "Booking")
{
AddInterimEntry(o_appointment,
item,
s_allday,
s_appointmentid,
item.EventType.ToString());
}
else
{
if ((item.EventType == EventType.Modified) || (item.EventType == EventType.Moved)) {
EWSMethods.monitorFRM.log("Booking item skipped." + item.OldItemId.ToString());
}
}
}
catch (Exception e)
{
EWSMethods.monitorFRM.log(e.Message);
}
}
Thanks in advance.

StackOverflow exception

I am using DDE client to attach and listen stock market prices. That client has a callback method I implemented what to do when it receives price changes. The problem is that I get StackOverflowException (periodically and not at the same time interval). I found something about Thread.BeginCriticalRegion(), but I'm not sure if it would help. I have a few more hours until market opening when I can test it.
I would be more than greatful if someone could give me an idea how to override this exception.
Thanks in advance,
Aleksandar
IList<SymbolObject> _symbols; //initialized when the app runs for the first time
void _ddeClient_Advise(object sender, DdeAdviseEventArgs args)
{
if (!IsReady)
return;
if (string.IsNullOrEmpty(args.Text))
{
_logMessages.LogMessagesAdd("advise dde symbol", string.Format("args.Text is empty or NULL for {0}", args.Item), true);
return;
}
try
{
string[] argsArray = args.Text.Replace("\0", "").Replace('\0'.ToString(), "").Split(' '); // sometimes happens here
var list = _symbols.Where(s => s.DDESymbol == args.Item).ToList();
if (list.Count == 0)
return;
decimal? val = null;
try
{
var stringParts = StringUtils.CleanProphitXUrl(argsArray[0]).Split('.');
argsArray = null;
if (stringParts.Length >= 2)
val = decimal.Parse(stringParts[0] + "." + (stringParts[1].Length > 2 ? stringParts[1].Substring(0, 2) : stringParts[1]));
else
val = decimal.Parse(stringParts[0]);
stringParts = null;
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call Price Alerts application service", ex.Message, true);
return;
}
foreach (var l in list)
{
if (_lastPrices[l.DDESymbol] == null)
continue;
if (_lastPrices[l.DDESymbol].ToString() != val.ToString())
{
try
{
_quotePublishingService.PublishQuote(l.DDESymbolId, l.Symbol, args.Item, val, WebSyncPublisherUrl,
PublishingChannel); // a call to wcf service
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call the service", ex.Message, true); // save to sql db
return;
}
_lastPrices[l.DDESymbol] = val.ToString();
}
}
list = null;
val = null;
}
catch
{
}
}
public static string CleanProphitXUrl(string value) // StringUtils.CleanProphitXUrl snippet
{
StringBuilder sb = new StringBuilder();
sb.Append(value.Substring(0, value.LastIndexOf(".") + 1));
try
{
value = value.Replace('\r'.ToString(), "").Replace('\t'.ToString(), "").Replace('\n'.ToString(), "");
for (int i = sb.Length; i < value.Length; i++)
{
if (char.IsNumber(value[i]))
sb.Append(value[i]);
}
}
catch
{
}
return sb.ToString();
}
A StackOverflowException is caused by making to many method calls usually resulting from unintended recursion. Based on a cursory check of the code you posted I do not believe it is the culprit. The problem likely lies somewhere else.