Why doesn't my Windows Store (Metro) app appear in the Share Pane? - c#

I have made my app a Share Target (and Source), and I can successfully Share my app's content with other apps, but when I am in another app, like Mail or IE for example, I cannot share their content with my app because it doesn't appear in the Share Pane as an available Share Target app.
I have read and followed the MSDN documentation, checked out the samples, and have also setup the Share Target Declaration in the Package.AppXManifest file.
Why, and how can I fix this?
C# Code-behind:
ShareOperation shareOperation;
private string sharedDataTitle;
private string sharedDataDescription;
private string shareQuickLinkId;
private string sharedText;
private Uri sharedUri;
private IReadOnlyList<IStorageItem> sharedStorageItems;
private string sharedCustomData;
private string sharedHtmlFormat;
private IReadOnlyDictionary<string, RandomAccessStreamReference> sharedResourceMap;
private IRandomAccessStreamReference sharedBitmapStreamRef;
private IRandomAccessStreamReference sharedThumbnailStreamRef;
private void ReportStarted()
{
this.shareOperation.ReportStarted();
}
private void ReportCompleted()
{
this.shareOperation.ReportCompleted();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
RegisterForShare();
try
{
this.shareOperation = (ShareOperation)e.Parameter;
await Task.Factory.StartNew(async () =>
{
ReportStarted();
// Retrieve data package properties.
this.sharedDataTitle = this.shareOperation.Data.Properties.Title;
this.sharedDataDescription = this.shareOperation.Data.Properties.Description;
this.shareQuickLinkId = this.shareOperation.QuickLinkId;
// Retrieve data package content.
if (this.shareOperation.Data.Contains(StandardDataFormats.Text))
{
try
{
this.sharedText = await this.shareOperation.Data.GetTextAsync();
}
catch (Exception exception)
{
// NotifyUser of error.
}
}
else if(this.shareOperation.Data.Contains(StandardDataFormats.Html))
{
try
{
this.sharedHtmlFormat = await this.shareOperation.Data.GetHtmlFormatAsync();
}
catch (Exception exception)
{
}
}
else if (this.shareOperation.Data.Contains(StandardDataFormats.Uri))
{
try
{
this.sharedUri = await this.shareOperation.Data.GetUriAsync();
}
catch (Exception exception)
{
}
}
// Get back to the UI thread.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
if (this.sharedText != null)
{
// Create a Note out of shared data.
CreateNote(this.sharedDataTitle, this.sharedText, null);
this.shareOperation.ReportDataRetrieved();
}
if (this.sharedUri != null)
{
CreateNote(this.sharedDataTitle, this.sharedUri.OriginalString, null);
this.shareOperation.ReportDataRetrieved();
}
if (this.sharedHtmlFormat != null)
{
CreateNote(this.sharedDataTitle, this.sharedHtmlFormat.ToString(), null);
this.shareOperation.ReportDataRetrieved();
}
});
});
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
if (e.NavigationMode == NavigationMode.Back)
{
navigatedBack = true;
}
base.OnNavigatedTo(e);
}
App.xaml.cs:
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args.ShareOperation);
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
Any help will be greatly appreciated.

In your package manifest, make sure you add the declaration for "share target"

Related

Camera preview face detection failed

In my Xamarin.forms android app, I am using IFaceDetectionListener Doc, for detecting faces in custom camera preview. When I try to open my custom camera page I am getting error like this.
Java.Lang.RuntimeException: start face detection failed
My stack traces are
JniEnvironment+InstanceMethods.CallNonvirtualVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args)
JniPeerMembers+JniInstanceMethods.InvokeNonvirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters)
Camera.StartFaceDetection ()
CameraPreviewRenderer+<>c__DisplayClass8_0.<OnElementChanged>b__1 ()
Thread+RunnableImplementor.Run ()
mono.java.lang.RunnableImplementor.run RunnableImplementor.java:30
android.os.Handler.handleCallback Handler.java:883
This error occurs on my OnElementChanged of CameraCustomRender.
CameraCustomRender
public class CameraPreviewRenderer : ViewRenderer<App.Views.Clocking.CustomCamera.CameraPreview, App.Droid.CustomRender.Clocking.CameraPreview>, Camera.IFaceDetectionListener, Camera.IPictureCallback, Camera.IShutterCallback
{
CameraPreview cameraPreview;
String Picture_Name = "";
private CameraFacing camerainfo = CameraFacing.Front;
int DetectedFaceCount = 0;
[get: Android.Runtime.Register("getMaxNumDetectedFaces", "()I", "GetGetMaxNumDetectedFacesHandler", ApiSince = 14)]
public virtual int MaxNumDetectedFaces { get; }
public CameraPreviewRenderer(Context context) : base(context)
{
}
[Obsolete]
protected override void OnElementChanged(ElementChangedEventArgs<Centraverse.Views.Clocking.CustomCamera.CameraPreview> e)
{
try
{
base.OnElementChanged(e);
if (Control == null)
{
try
{
cameraPreview = new CameraPreview(Context);
SetNativeControl(cameraPreview);
}
catch (Exception ex)
{
}
}
if (e.OldElement != null)
{
}
if (e.NewElement != null)
{
try
{
if (Control == null)
{
cameraPreview = new CameraPreview(Context);
SetNativeControl(cameraPreview);
}
Control.Preview = Camera.Open((int)e.NewElement.Camera);
Control.CameraID = 1;
var CameraParaMeters = cameraPreview.camera.GetParameters();
if (CameraParaMeters != null)
{
if (CameraParaMeters.MaxNumDetectedFaces > 0)
{
Device.BeginInvokeOnMainThread(() =>
{
>------------------// Getting crashed at here-------------------------------------<
Control.Preview.SetFaceDetectionListener(this);
Control.Preview.StartFaceDetection();
});
}
}
}
catch (Exception ex)
{
}
}
}
catch(Exception ex)
{
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
Control.Preview.Release();
MessagingCenter.Unsubscribe<Object>(this, "CaptureClick");
MessagingCenter.Unsubscribe<Object>(this, "FlipClick");
}
Device.BeginInvokeOnMainThread(base.Dispose);
}
catch (Exception ex)
{
}
}
[Obsolete]
public void OnFaceDetection(Camera.Face[] faces, Camera camera)
{
try
{
DetectedFaceCount = faces.Length;
}
catch (Exception ex)
{
}
}
private void takepicture()
{
try
{
Control.Preview.TakePicture(this, this, this);
}
catch (Exception ex)
{
}
}
public void OnPictureTaken(byte[] data, Camera camera)
{
try
{
// Managing camera capture
}
catch (Exception ex)
{
}
}
public void OnShutter() { }
}
I am not able to isolate the issue. The app gets crash with error saying "start Face detection failed". Since I am using older camera API , will that cause this issue? Please help me to fix this issue. For the convenience I have the sample project here.sample Project
EDIT
I am able to catch the exception like this
try
{
Control.Preview.SetFaceDetectionListener(this);
Control.Preview.StartFaceDetection();
}
catch (Java.Lang.RuntimeException ex)
{
}
I test your sample,and when i don't use a mode page to open the CameraPage,it will work.
You could try to change which in your MainPage.xaml.cs :
await Navigation.PushModalAsync(new CameraPage());
to
await Navigation.PushAsync(new CameraPage());
like:
private async void Open_Camera(object sender, EventArgs e)
{
try
{
var PhotoRequeststatus = await Permissions.RequestAsync<Permissions.Camera>();
var StorageRequStatus = await Permissions.RequestAsync<Permissions.StorageWrite>();
if (PhotoRequeststatus != Xamarin.Essentials.PermissionStatus.Granted || StorageRequStatus != Xamarin.Essentials.PermissionStatus.Granted)
{
await DisplayAlert("Enable Permission", "Please allow camera permission", "Close");
}
else
{
await Navigation.PushAsync(new CameraPage());
}
}
catch(Exception ex)
{
}
}

error on wcf application when used as resource to move received data to asp.net web API

so bascially i have a console application acting as a client software receiving data from a WCF feed. this works just fine when i want to do a console.writeline and print the data i'm getting in the console. I don't control the service end of the WCF feed so i have to use this console client software to access the data.
I'm trying to build an ASP.net web api application to pass this data to my own client via REST api. There are other complex reasons i have to do it this way but when it comes down to it i have to. I've built the basic web api for doing a GET to get the information. added the console application as a resource to the web api application but get an error message when I make the GET call.
This is the URL i'm using to make the GET call.
http://localhost:60421/api/CallData?skillNumber=92
After i make this call i get the below error message
[ERROR] System.InvalidOperationException occurred
HResult=0x80131509
Message=Could not find default endpoint element that references contract 'FeedService.IFeedService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
Source=
StackTrace:
The error occurs in this cs file. I've commented at the line it occurs in.
using ScoreBoardClientTest.FeedService;
namespace ScoreBoardClientTest
{
public class FeedServiceAgent : IFeedServiceAgent, IFeedServiceCallback
{
private static FeedServiceClient _feedServiceClient;
private ConnectionStats.ConnectionStatus _connectionStatus;
private bool _retrying;
private bool _disposed;
public FeedServiceAgent() //(IEventAggregator eventAggregator)
{
//Guard.ArgumentNotNull(eventAggregator, "eventAggregator");
//_eventAggregator = eventAggregator;
InitializeServiceClient();
}
public event MessageReceivedEventHandler MessageReceived;
public void InitializeServiceClient()
{
// The error message occurs at the line right below this
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
}
private void DisposeServiceClient()
{
if (_feedServiceClient == null)
return;
try
{
_feedServiceClient.InnerChannel.Opening -= OnOpening;
_feedServiceClient.InnerChannel.Opened -= OnOpened;
_feedServiceClient.InnerChannel.Closing -= OnClosing;
_feedServiceClient.InnerChannel.Closed -= OnClosed;
_feedServiceClient.InnerChannel.Faulted -= OnFaulted;
_feedServiceClient.Abort();
}
catch
{
//Don't care.
}
finally
{
_feedServiceClient = null;
}
}
public ConnectionStats.ConnectionStatus ConnectionStatus
{
get { return _connectionStatus; }
set
{
_connectionStatus = value;
PublishConnectionStatus();
}
}
private void PublishConnectionStatus()
{
}
private void ProcessCmsData(A cmsData)
{
if (cmsData == null)
return;
var skill = new Skill();
var agents = new List<Agent>();
var cmLookupdata = new List<CmLookupData>();
// LookupData lookupdata = new LookupData();
if (cmsData.C != null && cmsData.C.Length > 0)
LookupDataTranslator.Translate(cmsData.C, cmLookupdata);
if (cmsData.AMember != null)
SkillTranslator.Translate(cmsData.AMember, skill, cmLookupdata);
if (cmsData.B != null && cmsData.B.Length > 0)
AgentTranslator.Translate(cmsData.B, agents, cmsData.AMember.A, cmsData.AMember.CmId); // passing skill params to validate the cmid to discard bad data
var mappedCmsData = new CmsData(skill, agents, cmLookupdata);
if (MessageReceived != null)
MessageReceived(this, new MessageReceivedEventArgs(mappedCmsData, null));
}
#region FeedServiceClient Channel Events
private void OnOpening(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connecting;
}
private void OnOpened(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connected;
}
private void OnClosing(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnecting;
}
private void OnClosed(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
}
private void OnFaulted(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
if (!_retrying)
ThreadPool.QueueUserWorkItem(delegate
{
Reconnect();
});
}
#endregion
private void Reconnect()
{
_retrying = true;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnecting;
// We don't want each client attempting the first reconnect all at the same time.
var random = new Random();
int randomWaitValue = random.Next(1, 10000);
Thread.Sleep(randomWaitValue);
// Try reconnecting 10 times.
for (int i = 1; i <= 10; i++)
{
try
{
DisposeServiceClient();
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.Open();
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnected;
_retrying = false;
//_logger.Info(String.Format("The Scoreboard Client was able to reconnect after {0} retries.", i)) ;
return;
}
catch (Exception exception)
{
//_logger.Error(String.Format("The Scoreboard Client is unable to reconnect: {0}", exception)) ;
// Wait 30 seconds between retries to reduce network congestion.
Thread.Sleep(30000);
}
}
//_logger.Info("The Scoreboard Client was unable to reconnect after 10 retries.") ;
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
#region Implementation of IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
if (disposing)
{
// Dispose managed resources here.
DisposeServiceClient();
}
_disposed = true;
}
#endregion
public void NotifyCmsData(A cmsData)
{
ThreadPool.QueueUserWorkItem(delegate
{
ProcessCmsData(cmsData);
});
}
public void Subscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Subscribe(eventTopic, cmId));
}
public void Unsubscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Unsubscribe(eventTopic, cmId));
}
public void RefreshCmsData()
{
throw new NotImplementedException();
}
public LookupData GetLookupData()
{
LookupData lookupdata = new LookupData();
try
{
LookupDataTranslator.Translate(_feedServiceClient.GetLookupData(), lookupdata);
}
catch (Exception e)
{
//if (_logger != null)
// _logger.Error("Exception in finding the lookup data. Exception:" + e.Message);
throw e;
}
return lookupdata;
}
private void InvokeAction(Action<IFeedService> action)
{
try
{
action(_feedServiceClient);
}
catch (Exception exception)
{
//_logger.Error(" Exception in FeedService InvokeAction:" + exception.ToString());
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
}
}
}
The console application has a properly configured config file for the console application which is what the error message suggests does not exist. also, as i said above the console application functions fully by itself.
QUESTION
How do you use a WCF console application as a resource for a web api successfully?
I had to include the FeedService web URL inside of the web api service as long as the console application

How to pause or stop "CSharpScript" running?

I'm using Roslyn's scripting API in my application, code snippet as following:
public class ScriptEngine
{
public static string CodeText;
public static event Action<string[]> CompileErrorEvent;
public static async Task<bool> RunScriptAsync(CancellationToken ct)
{
try
{
var scriptResult = await CSharpScript.RunAsync(CodeText, null, new ScriptHost(), null, ct);
return true;
}
catch (Microsoft.CodeAnalysis.Scripting.CompilationErrorException ex)
{
List<string> result = new List<string>();
foreach (var item in ex.Diagnostics)
{
result.Add(item.ToString());
}
if (result.Count > 0)
{
CompileErrorEvent?.Invoke(result.ToArray());
}
return false;
}
catch (Exception ex)
{
IMCP_Base.Dialog.Show.SimpleError("脚本运行", ex.Message, "修改脚本");
return false;
}
}
.......
}
public static CancellationTokenSource ScriptCTS;
private async void btnScriptRun_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS = new CancellationTokenSource();
if (CheckScriptEditorIsNotNull())
{
Script.ScriptEngine.CodeText = ScriptEditor.GetCode();
bool runSuccess = await Script.ScriptEngine.RunScriptAsync(ScriptCTS.Token);
}
}
private void btnScriptStop_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS?.Cancel();
}
CSharpScript.RunAsync method runs well, but when I click ScriptStop button, ScriptCTS?.Cancel() can't cancel running script.
How can I stop or pause a script running?
If you want cancellation points within your scripts, you can use globals, and pass in the CancelationToken, which you can then check in your scripts for cancellation.

Async wait until form is loaded to continue

I am trying to get my form to wait until a particular part of my _Load method is finished before continuing. I have a few methods that are async, but I cannot figure out why I am not able to get the code to wait until fakeClickCheckUpdate is finished before continuing. Here are the main methods involved:
public myForm(string args)
{
InitializeComponent();
Load += myForm_Load;
}
private void myForm_Load(object s, EventArgs e)
{
this.fakeClickCheckUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}
public void fakeClickCheckUpdate()
{
this.checkUpdateButton.PerformClick();
}
private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}
private async Task checkVersion()
{
string currVersion;
string newVersion;
using (StreamReader sr = new StreamReader(currVersionTxt))
{
currVersion = sr.ReadToEnd();
}
using (StreamReader nr = new StreamReader(versionSaveTo))
{
newVersion = nr.ReadToEnd();
}
if (!newVersion.Equals(currVersion, StringComparison.InvariantCultureIgnoreCase))
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "New version available! Please select 'Force Download'";
});
this.needsUpdate = true;
}
else
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "Your version is up-to-date. No need to update.";
});
this.needsUpdate = false;
}
}
Basically, I want it to check the current version with checkVersion and finish that before it tries to continue past loadFinished = true inside of myForm_Load. I have checkVersion set as an async Task so that the button click can use await on it. Is there any way to get the functionality I need with this code?
First, move your code out of your perform click action.
private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await CheckForUpdate();
}
private async Task CheckForUpdate()
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}
You can then call that same function in your OnLoad.
private async void myForm_Load(object s, EventArgs e)
{
await CheckForUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}

Live SDK - Try to Sign In without SignInButton

Is there any way to login to Live for an App (Silverlight, WP7 can) without having to click on SignIn button.
I want to log me dynamically, for example: when you start the app, I want to log in to me. How to do this without resorting to the button?
I figured out how to do, so I decided to share:
using System.Windows;
using Microsoft.Live;
public class LiveLogin
{
private static readonly string[] scopes =
new string[] {
"wl.signin",
"wl.basic",
"wl.calendars",
"wl.calendars_update",
"wl.contacts_calendars",
"wl.events_create" };
private LiveAuthClient authClient;
private LiveConnectClient liveClient;
public LiveLogin()
{
this.authClient = new LiveAuthClient("**your client id here**");
this.authClient.InitializeCompleted += authClient_InitializeCompleted;
this.authClient.InitializeAsync(scopes);
}
private void authClient_InitializeCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
this.liveClient = new LiveConnectClient(e.Session);
}
else
{
this.authClient.LoginCompleted += authClient_LoginCompleted;
this.authClient.LoginAsync(scopes);
}
}
private void authClient_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
this.liveClient = new LiveConnectClient(e.Session);
MessageBox.Show("Signed");
}
else
{
MessageBox.Show("Failed!");
}
}
}
Great answer Richard. This really helped a lot.
I noticed a couple of comments from people complaining that they couldn't find the InitializedCompleted event. If you're coding in .Net 4.5 then you need to follow the async/await pattern for asynchronous methods. The class above would look like this:
public class LiveLogin
{
private static readonly string[] Scopes =
new[]
{
"wl.signin",
"wl.basic",
"wl.calendars",
"wl.calendars_update",
"wl.contacts_calendars",
"wl.events_create"
};
private LiveAuthClient _authClient;
public async Task<LiveConnectClient> Login()
{
_authClient = new LiveAuthClient("**your client id here**");
LiveLoginResult result = await _authClient.InitializeAsync(Scopes);
if (result.Status == LiveConnectSessionStatus.Connected)
{
return new LiveConnectClient(result.Session);
}
result = await _authClient.LoginAsync(Scopes);
if (result.Status == LiveConnectSessionStatus.Connected)
{
return new LiveConnectClient(result.Session);
}
return null;
}
}
MS have an async await primer here
Thanks for the code example - helped me come up with the update version of code for Windows Phone 8, etc. :)
using System.Windows;
using Microsoft.Live;
public class LiveLogin : PhoneApplicationPage
{
private static readonly string[] _scopes =
new[] {
"wl.signin",
"wl.basic",
"wl.calendars",
"wl.calendars_update",
"wl.contacts_calendars",
"wl.events_create" };
private LiveConnectClient _connection;
private LiveLoginResult _login;
public LiveLogin()
{
this.Loaded += this.OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
//----------------------------------------------------------------------
// Login to skydrive
//----------------------------------------------------------------------
await SkydriveLogin();
}
private async Task SkydriveLogin()
{
try
{
//----------------------------------------------------------------------
// Initialize our auth client with the client Id for our specific application
//----------------------------------------------------------------------
LiveAuthClient authClient = new LiveAuthClient("**your client id here**");
//----------------------------------------------------------------------
// Using InitializeAsync we can check to see if we already have an connected session
//----------------------------------------------------------------------
_login = await authClient.InitializeAsync(_scopes);
//----------------------------------------------------------------------
// If not connected, bring up the login screen on the device
//----------------------------------------------------------------------
if (_login.Status != LiveConnectSessionStatus.Connected)
{
_login = await authClient.LoginAsync(_scopes);
}
//----------------------------------------------------------------------
// Initialize our connection client with our login result
//----------------------------------------------------------------------
_connection = new LiveConnectClient(_login.Session);
}
catch (Exception ex)
{
//TODO: Add connection specific exception handling
}
}
}

Categories