pushpin.Location error on Bing maps for Windows store app - windows-8

I'm using C# to create a windows store app using bing maps. I am trying to store and retrieve the location of a randomly placed pushpin on a map but when I use pushpin.Location for trying to print the location for example, I get the following error:
'Bing.Maps.Pushpin' does not contain a definition for 'Location' and
no extension method 'Location' accepting a first argument of type
'Bing.Maps.Pushpin' could be found (are you missing a using directive
or an assembly reference?)
The simple code example below show what I mean a bit more clearly:
private async void pushpinTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("You are here" + pushPin.Location());
await dialog.ShowAsync();
}
It states clearly that location is a property of the the pushpin class in the API here
There's also examples of it being used for windows phone 7, like in this question.
Any ideas what I'm missing? or is this functionality not available for Windows 8?

It works like:
async void pin_Tapped(object sender, TappedRoutedEventArgs e)
{
Pushpin pin = sender as Pushpin;
Location pinLocation = MapLayer.GetPosition(pin);
MessageDialog dialog = new MessageDialog("You are here: " + pinLocation.Latitude +", " + pinLocation.Longitude);
await dialog.ShowAsync();
}

Ah nice one thank you.
I found another way to do it too. Essentially the same thing but using var x instead of Location.
private async void pushpinTapped(object sender,Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
Pushpin tappedpin = sender as Pushpin;
if (null == tappedpin) return;
var x = MapLayer.GetPosition(tappedpin);
MessageDialog dialog = new MessageDialog("You are here " + x.Latitude + ", " + x.Longitude);
await dialog.ShowAsync();
}

Related

How to fetch all the fields from ServiceFeatureTable in arcgis

I am using arcgis library 100.0.0 in android for displaying maps and information inside map.
I am using the following code to populate a ServiceFeaturetable using URL provided by arcGis. I am able to load the feature layer successfully into the mapview. I have written code that listens to the click on the symbol on the map, so that I can get some information about the specific feature on the map. I am able to get the specific feature OnClick.
Upon investigating the GetAttributes() result of the specific feature, I realize that it is not having all the fields. After investigating on internet, I found that the FeatureTable.QueryFeaturesAsync could be used to get all the fields of the feature. Even though I have written the code to get all the fields, I do not know how I link this result with the feature layer, so that the feature has all the fields that I require. Here is the code
final ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable("some URL");
ListenableFuture<FeatureQueryResult> queryresult = serviceFeatureTable.queryFeaturesAsync(null, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
// create the feature layer using the service feature table
final FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
featureLayer.setSelectionColor(Color.YELLOW);
featureLayer.setSelectionWidth(10);
// add the layer to the map
mapView.getMap().getOperationalLayers().add(featureLayer);
// set an on touch listener to listen for click events
mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(getContext(), mapView) {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// get the point that was clicked and convert it to a point in map coordinates
Point clickPoint = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
int tolerance = 10;
double mapTolerance = tolerance * mMapView.getUnitsPerDensityIndependentPixel();
// create objects required to do a selection with a query
Envelope envelope = new Envelope(clickPoint.getX() - mapTolerance, clickPoint.getY() - mapTolerance, clickPoint.getX() + mapTolerance, clickPoint.getY() + mapTolerance, mapView.getMap().getSpatialReference());
QueryParameters query = new QueryParameters();
query.setGeometry(envelope);
// call select features
final ListenableFuture<FeatureQueryResult> future = featureLayer.selectFeaturesAsync(query, FeatureLayer.SelectionMode.NEW);
// add done loading listener to fire when the selection returns
future.addDoneListener(new Runnable() {
#Override
public void run() {
try {
//call get on the future to get the result
FeatureQueryResult result = future.get();
// create an Iterator
Iterator<Feature> iterator = result.iterator();
Feature feature;
// cycle through selections
int counter = 0;
while (iterator.hasNext()){
feature = iterator.next();
counter++;
String name = feature.getAttributes().get(Constants.FIELD_NAME).toString();
Log.d(getResources().getString(R.string.app_name), "Selection #: " + counter + " Table name: " + feature.getFeatureTable().getTableName());
}
//Toast.makeText(getApplicationContext(), counter + " features selected", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e.getMessage());
}
}
});
return super.onSingleTapConfirmed(e);
}
});
Try replacing your code
from
final ListenableFuture<FeatureQueryResult> future = featureLayer.selectFeaturesAsync(query, FeatureLayer.SelectionMode.NEW);
to
final ListenableFuture<FeatureQueryResult> future = serviceFeatureTable.queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
It works for me!

How can I get the alternates of SAPI speech recognization result

On windows7 platform I can use System.Speech.Recognition.SpeechRecognitionEngine to convert voice to text.By SpeechRecognitionEngine when the SpeechRecognized event triggered I can get some alternate words,and I can show these word to users for choise.
void engine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (this.SpeechRecognized != null)
{
this.SpeechRecognized(this, new RecognizedResultEventArgs
{
Text = e.Result.Text,
Alternates = new ReadOnlyCollection<string>(e.Result.Alternates.Select(p => p.Text).ToList())
});
}
}
By the way,when I initialise SpeechRecognitionEngine instance,I want to load some specifical word instead of use "DictationGrammar".
My program need to runing on xp platform sometimes.So I want to implament a specific vertion to run on xp operating system by use sapi5.1.
I have readed a portion of sapi 5.1 document,then I get that:in sapi5.1,I can use "command and control" way to do that. but the "Result.Alternates()" method can not be used when I use "command and control".So,how can I achieve the same effect of SpeechRecognitionEngine ?
I tried the following code and there is an com Eception:
public void RecoContext_Recognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
ISpeechPhraseProperty oItem;
oItem = Result.PhraseInfo.Properties.Item(0);
if ((System.Decimal)Result.PhraseInfo.GrammarId == grammarId)
{
if (this.SpeechRecognized != null)
{
RecognizedResultEventArgs e = new RecognizedResultEventArgs();
e.Text = oItem.Name;
// The following code throws an exception
ISpeechPhraseAlternates alternates = Result.Alternates(10);
List<string> s = new List<string>();
foreach (ISpeechPhraseAlternate item in alternates)
{
s.Add(item.RecoResult.PhraseInfo.Properties.Item(0).Name);
}
e.Alternates = new ReadOnlyCollection<string>(s);
this.SpeechRecognized(this, e);
}
}
}
Is there any way to get the alternates by use sapi by way of COM?Thank you.
In SAPI (any version), command and control grammars don't have alternates. Only dictation grammars have alternates.

Trouble Attaching File Programmatically to Email in Windows Metro App C#/XAML using Share Charm

I'm simply trying to attach a file named Document.pdf in the DocumentsLibrary to an email using the Share Charm. My code below works perfectly on the Local Machine:
private async void OnDataRequestedFiles(DataTransferManager sender, DataRequestedEventArgs e)
{
List<IStorageItem> shares = new List<IStorageItem>();
StorageFile filetoShare = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync("Document.pdf");
if (filetoShare != null)
{
shares.Add(filetoShare);
filetoShare = null;
}
if (shares != null)
{
DataPackage requestData = e.Request.Data;
requestData.Properties.Title = "Title";
requestData.Properties.Description = "Description"; // The description is optional.
requestData.SetStorageItems(shares);
shares = null;
}
else
{
e.Request.FailWithDisplayText("File not Found.");
}
}
But when I run the exact same code on a Windows Surface Tablet, I get the dreaded "There's nothing to share right now." on the right in the Charms flyout area.
Here's a little more background to help:
I'm not looking to use a File Picker...I know the exact file I'm looking for
I've enabled the Documents Library Capability in the manifest
I've added a File Type Association for pdf in the manifest
and yes, the file does exist and is in the Documents Library
an email account is properly setup in the Mail App on the surface
I can successfully send text emails from the Tablet...just not emails with attachments
Like I said, this works on my Win 8 Development Machine as expected...just not on the Surface. I'm wondering if the Surface has different file or folder permissions?
Thanks for the help...this is driving me CRAZY
I finally figured it out - the problem was that my Event Handler was async (so that I could use await to set the StorageFile variable).
I solved it by setting the StorageFile variable earlier in my code so that it was already available when the Event Handler was called.
I still have no idea why it worked on my development machine, but no on the WinRT surface...
The handler can be an async method. In this case, it is critical to use DataTransferManager. Please refer to the MSDN page specifically for this scenario. For your convenience, the code from the page is copied to here:
private void RegisterForShare()
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
DataRequestedEventArgs>(this.ShareStorageItemsHandler);
}
private async void ShareStorageItemsHandler(DataTransferManager sender,
DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Share StorageItems Example";
request.Data.Properties.Description = "Demonstrates how to share files.";
// Because we are making async calls in the DataRequested event handler,
// we need to get the deferral first.
DataRequestDeferral deferral = request.GetDeferral();
// Make sure we always call Complete on the deferral.
try
{
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
request.Data.SetStorageItems(storageItems);
}
finally
{
deferral.Complete();
}
}
It is critical to place the following statement before any async method is called:
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
You only have half a second to get the whole job done (getting the file, attaching...etc.). If the half-second deadline occurs you'll get this "driving crazy" message. Consider implementing some resumable logic and replace the message with "the attachment is being prepared please try again in a few seconds" (or else).
Your WinRT device might be just slower than your development machine. The latter just does the job before the deadline...

facebook.stream.addlike is not working in silverlight

Am trying to build an application using facebook sdk in silverlight.
In my application I need to send "like" for a post, to achieve this am using the following Async call:
_fb.Stream.AddLikeAsync(_dataAccess.Session.UserId, feed.stream_post.post_id, OnLikeCompleted, null);
which is giving an exception saying
{Facebook.Utility.FacebookException: A session key must be specified
when request is signed with a session secret
at Facebook.Utility.Utilities.ParseException(String response, Boolean JSONFormat)
at Facebook.Rest.RestBase.OnRequestCompleted(Object sender, RequestCompletedEventArgs e)}
private void lnkLike_Click(object sender, RoutedEventArgs e)
{
var feed = (sender as FrameworkElement).DataContext as StreamStory;
MessageBox.Show(feed.stream_post.post_id.ToString());
_fb.Stream.AddLikeAsync(_dataAccess.Session.UserId, feed.stream_post.post_id, OnLikeCompleted, null);
}
private void OnLikeCompleted(bool result, Object state, FacebookException e)
{
if (e == null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("likes success"));
var actual = result;
}
else
{
Dispatcher.BeginInvoke(() =>MessageBox.Show("Error: " +e.Message));
}
}
Please help me resolve the above issue. Thanks in advance.
You are using code from the Facebook Developer Toolkit that is nearly 3 years old. Facebook has changed their API many times since then. You need to reference Facebook's developer documents and consider using the Facebook C# SDK which is compatible with Facebook's current API.

SharePoint 2010 Rename Document on Upload Fails in Explorer View

I'm trying to implement a customization in SharePoint 2010 so that when a document is uploaded to a library, the file name is changed to include the Document ID in the name. (I know that people shouldn't worry about file names as much any more, but we have a lot of legacy files already named and users who like to have local copies).
I was able to implement a custom Event Receiver on the ItemAdded event that renames the file by adding the Document ID before the file name. This works correctly from the web Upload.
The problem is with the Explorer View. When I try to add the file using WebDAV in the Explorer View, I get two copies of the file. It seems that when a file is uploaded via the Web the events that fire are
ItemAdding
ItemAdded
But when I copy/paste a file into Explorer View I see the following events:
ItemAdding
ItemAdded
ItemAdding
ItemAdded
ItemUpdating
ItemUpdated
The result is I have two files with different names (since the Document IDs are different).
I've found a lot of people talking about this issue online (this is the best article I found). Anyone have any other ideas? Would it make more sense to do this in a workflow instead of an event receiver? I could use a scheduled job instead, but that might be confusing to the user if the document name changed a few minutes later.
This is my code that works great when using the Web upload but not when using Explorer View:
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
SPListItem currentItem = properties.ListItem;
if (currentItem["_dlc_DocId"] != null)
{
string docId = currentItem["_dlc_DocId"].ToString();
if (!currentItem["BaseName"].ToString().StartsWith(docId))
{
EventFiringEnabled = false;
currentItem["BaseName"] = docId + currentItem["BaseName"];
currentItem.SystemUpdate();
EventFiringEnabled = true;
}
}
}
catch (Exception ex)
{
//Probably should log an error here
}
base.ItemAdded(properties);
}
I have found that using a Visual Studio workflow allows me the most flexibility to do this. A SharePoint Designer Workflow would be simpler, but would be harder to deploy to different sites and libraries.
After reading some good articles including this and this I have come up with this code which seems to work. It starts a workflow and waits until the document is not in a LockState and then processes the filename.
The workflow looks like this:
And here is the code behind:
namespace ControlledDocuments.RenameWorkflow
{
public sealed partial class RenameWorkflow : SequentialWorkflowActivity
{
public RenameWorkflow()
{
InitializeComponent();
}
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
Boolean continueWaiting = true;
private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
{
CheckFileStatus();
}
private void whileActivity(object sender, ConditionalEventArgs e)
{
e.Result = continueWaiting;
}
private void onWorkflowItemChanged(object sender, ExternalDataEventArgs e)
{
CheckFileStatus();
}
private void CheckFileStatus()
{
if (workflowProperties.Item.File.LockType == SPFile.SPLockType.None)
{
continueWaiting = false;
}
}
private void renameFile(object sender, EventArgs e)
{
try
{
SPListItem currentItem = workflowProperties.Item;
if (currentItem["_dlc_DocId"] != null)
{
string docId = currentItem["_dlc_DocId"].ToString();
if (!currentItem["BaseName"].ToString().StartsWith(docId))
{
currentItem["BaseName"] = docId + currentItem["BaseName"];
currentItem.SystemUpdate();
}
}
}
catch (Exception ex)
{
//Should do something useful here
}
}
}
}
Hope this helps someone else if they have the same problem.
Well i'd go for the workflow workaround... there are 2 options imo:
1) Create a boolean fied in your document library, then create a SPD workflow that fires when the item is added and set that field to "Changed" or something. In the EventReceiver you then check whether that field has been set..
2) Do everything with the SPD workflow - changing the title like in this example should be no problem.