Sharing an image in Windows Phone 8.1 - windows

I'd like to share an image in my app. However, the image is not located in a folder but it is "taken dynamically". Basically i have an Image object
Image i = new Image() { Source = await CreateBitmapFromElement(stackpanel1) };
where CreateBitmapFromElement is defined as follows
private async Task<RenderTargetBitmap> CreateBitmapFromElement(FrameworkElement uielement)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
return renderTargetBitmap;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
return null;
}
The Windows Phone Share Contract allows to share images located in the Picture Library (for example), but what should i use in this case?

protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested += OnShareDataRequested;
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested -= OnShareDataRequested;
base.OnNavigatedFrom(e);
}
private void OnShareDataRequested(DataTransferManager sender, DataRequestedEventArgs _dataRequestedEventArgs)
{
DataRequest request = _dataRequestedEventArgs.Request;
request.Data.Properties.Title = "KeyTreat Sticker";
request.Data.Properties.Description = "KeyTreat Sticker: " + StickerName;
// 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
{
request.Data.SetStorageItems(storageItemsObject);
request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(StorageFileObject);
request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(StorageFileObject));
}
finally
{
deferral.Complete();
}
}

Related

Admob native ads with xamarin: 'Ad failed to load : 0'

This issue only occurs with my implementation of native ads. Banner ads work fine. I adapted the custom renderers from this blog to work with native ads. I used test ad unit IDs.
Here is my custom renderer for Android:
[assembly: ExportRenderer(typeof(NativeAdView), typeof(NativeRendererAndroid))]
namespace XXX.Droid
{
public class NativeRendererAndroid : ViewRenderer<NativeAdView, AdView>
{
public NativeRendererAndroid(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<NativeAdView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
SetNativeControl(CreateAdView());
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(AdView.AdUnitId))
Control.AdUnitId = Element.AdUnitId;
}
private AdView CreateAdView()
{
var adView = new AdView(Context)
{
AdSize = new AdSize(AdSize.FullWidth, AdSize.AutoHeight),
AdUnitId = Element.AdUnitId
};
adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
adView.LoadAd(new AdRequest.Builder().Build());
return adView;
}
}
}
And for iOS:
[assembly: ExportRenderer(typeof(NativeAdView), typeof(NativeRendereriOS))]
namespace XXX.iOS
{
public class NativeRendereriOS : ViewRenderer<NativeAdView, NativeExpressAdView>
{
protected override void OnElementChanged(ElementChangedEventArgs<NativeAdView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(CreateNativeAd());
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(NativeExpressAdView.AdUnitID))
Control.AdUnitID = Element.AdUnitId;
}
private NativeExpressAdView CreateNativeAd()
{
AdSize adSize = new AdSize();
adSize.Size = new CGSize(UIScreen.MainScreen.Bounds.Size.Width, 49);
var nativeAd = new NativeExpressAdView(adSize)
{
AdUnitID = Element.AdUnitId,
RootViewController = GetVisibleViewController()
};
nativeAd.LoadRequest(GetRequest());
Request GetRequest()
{
var request = Request.GetDefaultRequest();
return request;
}
return nativeAd;
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
}
These custom renderers are very similar to the ones linked in the blog above. Perhaps there is something I need to include for native ads that is not used for banner ads?
Once I get the ad loading correctly, I would like to put it in a ListView, but for now I just have it as a View.
Edit: For clarification, when using the above custom renderers, everything builds successfully, but when the ad tries to load, 'Ad failed to load : 0' gets printed in the debug and the NativeAdView remains transparent. This is both both platforms.

When i kill the running instance and relaunch the application using Db ecncryption app is crashing

i have implemented code below scenarios
namespace Inspect.Droid
{
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
private DataBaseEncryption dbEncryption;
protected override async void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
MainAppActivity = this;
Forms.Init(this, bundle);
//to get the current device language code
var code = Locale.Default.GetDisplayLanguage(Locale.Default);
CommonInfo.Instance.DeviceCurrentLanguageCode = code.Substring(0, 2).ToUpper();
Console.WriteLine("Device lang code: " + CommonInfo.Instance.DeviceCurrentLanguageCode);
try
{
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
}
catch (Exception ex)
{
//when application coming back from background throws exception, bcz PCLAppConfig is already initialized, so as there is no change no need to change here
Console.WriteLine(ex.Message);
}
GLOBAL_CONTEXT = Android.App.Application.Context;
ACTIVITY_CONTEXT = this;
FragmentMgr = FragmentManager;
dbEncryption = new DataBaseEncryption();
//await PrepareDb();
await dbEncryption.InitiateDecryption();
//AzureMobileServices Initialization for Android
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
SessionInfo.Instance.DeviceId = Utility.GenerateGuid().ToString();
//This will set the value for _skipCount variable in all respected helper classes.
SetSkipCount();
Inspect.ScreenSize = new Xamarin.Forms.Size(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density,
Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
Inspect.AndroidDisplayMetricsDensity = Resources.DisplayMetrics.Density;
int statusBarResId = Resources.GetIdentifier("status_bar_height", "dimen", "android");
if (statusBarResId > 0)
{
Inspect.AndroidStatusBarHeight = Resources.GetDimensionPixelSize(statusBarResId);
}
Context context = this.ApplicationContext;
Acr.UserDialogs.UserDialogs.Init(this);
//allowing the device to change the screen orientation based on the rotation
MessagingCenter.Subscribe<InspectionAddNotesPage>(this, CommonConstants.AllowLandScape, sender =>
{
RequestedOrientation = ScreenOrientation.Unspecified;
});
//during page close setting back to portrait
MessagingCenter.Subscribe<InspectionAddNotesPage>(this, CommonConstants.PreventLandScape, sender =>
{
RequestedOrientation = ScreenOrientation.Portrait;
});
LoadApplication(new Inspect());
//Intializing the context for Media access
CrossCurrentActivity.Current.Activity = this;
PasscodeAuthDependency.Activity = this;
}
protected override void OnStop()
{
base.OnStop();
dbEncryption.InitiateEncryption(true);
}
protected override void OnRestart()
{
base.OnRestart();
dbEncryption.InitiateDecryption();
}
protected override void OnDestroy()
{
base.OnDestroy();
}
Please provide the solution.
Where exactly is your exception coming from? Did you manage to get the origin?
And in case you are talking about the exception from the ConfigurationManager.Initialize() method, try this.
if(Configurationmanager.AppSettings == null)
{
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
}
Its just that the ConfigurationManager throws an exception if it already finds a NameValueCollection initialized.

OnNavigatedTo in ViewModel isn't firing when page first loads

I'm trying to implement Azure Active Directory B2C in Xamarin.Forms. If I just copy their example, I can get it to work without a problem. But when I try to use Prism, I run into problems.
I took this code that was sitting in the codebehind of the XAML:
protected override async void OnAppearing ()
{
base.OnAppearing ();
App.PCApplication.PlatformParameters = platformParameters;
try {
var ar = await App.PCApplication.AcquireTokenSilentAsync(
AuthenticationInfo.Scopes, string.Empty, AuthenticationInfo.Authority,
AuthenticationInfo.SignUpSignInpolicy, false);
AuthenticationInfo.UserAuthentication = ar;
} catch {
}
}
async void OnSignUpSignIn(object sender, EventArgs e)
{
try {
var ar = await App.PCApplication.AcquireTokenAsync(
AuthenticationInfo.Scopes, string.Empty, UiOptions.SelectAccount,
string.Empty, null, AuthenticationInfo.Authority,
AuthenticationInfo.SignUpSignInpolicy);
AuthenticationInfo.UserAuthentication = ar;
} catch (Exception ex) {
if (ex != null) {
}
}
}
and moved it to the ViewModel's OnNavigatedTo:
public async void OnNavigatedTo (NavigationParameters parameters)
{
if (parameters.ContainsKey ("title"))
Title = (string)parameters ["title"];
listen2asmr.App.PCApplication.PlatformParameters = platformParameters;
try {
var ar = await listen2asmr.App.PCApplication.AcquireTokenSilentAsync(
AuthenticationInfo.Scopes, string.Empty, AuthenticationInfo.Authority,
AuthenticationInfo.SignUpSignInpolicy, false);
AuthenticationInfo.UserAuthentication = ar;
} catch {
}
}
This is in the Bootstrapper:
protected override Xamarin.Forms.Page CreateMainPage ()
{
return Container.Resolve<LoginPage> ();
}
protected override void RegisterTypes ()
{
Container.RegisterTypeForNavigation<LoginPage>();
}
OnNavigatedTo never seems to get called though. Is there some other method I should be using, or did I miss something else? The only other thing I could think of was to call the code in OnNavigatedTo from the ViewModel constructor, but the async/await does work with the constructor.
This has been fixed in the latest preview version of Prism for Xamarin.Forms. Try using these packages instead:
https://www.nuget.org/packages/Prism.Forms/6.1.0-pre4
https://www.nuget.org/packages/Prism.Unity.Forms/6.2.0-pre4
Also the bootstrapping process has changed. Read this for more information:
Prism.Forms 5.7.0 Preview - http://brianlagunas.com/first-look-at-the-prism-for-xamarin-forms-preview/
Prism.Forms 6.2.0 Preview - http://brianlagunas.com/prism-for-xamarin-forms-6-2-0-preview/
Prism.Forms 6.2.0 Preview 3 - http://brianlagunas.com/prism-for-xamarin-forms-6-2-0-preview-3/
Preview 4 Post Coming Soon
My advice is use your View events as triggers for your ViewModel.
For Instance:
View.xaml.cs
protected override async void OnAppearing () {
base.OnAppearing ();
viewModel.OnAppearing();
}
async void OnSignUpSignIn(object sender, EventArgs e) {
viewModel.OnSignUpSignIn(sender, e);
}
ViewModel.cs
protected override async void OnAppearing () {
App.PCApplication.PlatformParameters = platformParameters;
try {
var ar = await App.PCApplication.AcquireTokenSilentAsync(
AuthenticationInfo.Scopes, string.Empty,
AuthenticationInfo.Authority,
AuthenticationInfo.SignUpSignInpolicy, false);
AuthenticationInfo.UserAuthentication = ar;
} catch {
}
}
async void OnSignUpSignIn(object sender, EventArgs e) {
try {
var ar = await App.PCApplication.AcquireTokenAsync(
AuthenticationInfo.Scopes, string.Empty,
UiOptions.SelectAccount,
string.Empty, null, AuthenticationInfo.Authority,
AuthenticationInfo.SignUpSignInpolicy);
AuthenticationInfo.UserAuthentication = ar;
} catch (Exception ex) {
if (ex != null) {
}
}
}
Reasons:
View should only involve visuals, and the events your page receives. Logic should be forwarded to the ViewModel, unless it deals with representation of information (for instance, logic to use a toggle-box for 2 choices but a combo-box for 3+).
Nearly vice-versa, the ViewModel should keep track of "model state" (ex. the user still needs to enter their payment information) as opposed to "view state" (ex. the user has navigated to the payment page).

how to scan a digit and get value of it by using windows phone application

i am new bee in windows phone application. i am currently using windows phone 7.1 OS in my emulator and device.i have a sticker which contains a digit. i want to scan this code by using camera and save digit into my database. i have not a single clue about scanning value from camera.
i got the code of scan barcodes and qr codes by using cameras.
my tried code is as follows:-
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
if (e.Succeeded)
{
this.Dispatcher.BeginInvoke(delegate()
{
// Write message.
txtDebug.Text = "Camera initialized.";
// Set flash button text.
});
}
}
void CaptureImage(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}
private void ShutterButton_Click(object sender, RoutedEventArgs e)
{
WP7.ScanBarCode.BarCodeManager.StartScan(
// on success
(b) => Dispatcher.BeginInvoke(() =>
{
txtDebug.Text = b;
NavigationService.GoBack();
}),
// on error
(ex) => Dispatcher.BeginInvoke(() =>
{
txtDebug.Text = ex.Message;
NavigationService.GoBack();
})
// Default : please, decode any bar-code
);
//if (cam != null)
//{
// try
// {
// // Start image capture.
// cam.CaptureImage();
// txtDebug.Text = "Image Taken";
// }
// catch (Exception ex)
// {
// this.Dispatcher.BeginInvoke(delegate()
// {
// // Cannot capture an image until the previous capture has completed.
// txtDebug.Text = ex.Message;
// });
// }
//}
}
private int photoCounter = 0;
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
photoCounter++;
string fileName = photoCounter + ".jpg";
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving picture.";
});
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Picture has been saved to camera roll.";
});
}
You should use Aforge.NET Library for Image comparison or Image Filteration.
Aforge

How to Load images from SD CARD and Run Animation using AnimationDrawable or AnimationUtils in Android

I am having Images stored in SD Card and using that images i wish to run an animation. I am using the following code for this but my animation is not working at all.
Code Snippet
playAnimation("xxx", medid, 25);//calling method
break;
public void playAnimation(String string, int medid2, int length) {
// TODO Auto-generated method stub
animation = new AnimationDrawable();
Bitmap bitMap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
player = MediaPlayer.create(this.getApplicationContext(), medid2);
try {
for (int i = 0; i <= length; i++) {
System.out.println("File Name : - " + Environment.getExternalStorageDirectory().toString() + "/" + string + i);
bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + "/" + string + i);
Drawable bmp = new BitmapDrawable(bitMap);
animation.addFrame(bmp, DURATION);
}
animation.setOneShot(true);
animation.setVisible(true, true);
int frames = animation.getNumberOfFrames();
System.out.println("Number of Frames are - " + frames);
img.setBackgroundDrawable(animation);
img.post(new Starter());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
class Starter implements Runnable {
public void run() {
try {
if(animation.isRunning()) {
animation.stop();
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
} else {
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Using concept of Frame Animation i need to run my animation. I am able fetch images as i have done some debugging but when i click on button and this methods are called my screen is not displaying any animation. It just display black screen only. I am not getting any error in this. If anyone having idea please kindly let me know.
Thanks
An AnimationDrawable just shows black screen, may be caused by different reasons. For example, in the Android Dev Guide, Drawable Animation, the following code lets you load a series of Drawable resources.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}
However, if you set resource after getBackground() like the following code, the screen will keep black.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
}
If you want to load images from SD card, and show them as animation, you can refer to the following code. I write and test on API 8 (2.3).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showedImage = (ImageView) findViewById(R.id.imageView_showedPic);
showedImage.setBackgroundResource(R.drawable.slides);
frameAnimation = (AnimationDrawable) showedImage.getBackground();
addPicturesOnExternalStorageIfExist();
}
#Override
public void onWindowFocusChanged (boolean hasFocus){
super.onWindowFocusChanged (hasFocus);
frameAnimation.start();
}
private void addPicturesOnExternalStorageIfExist() {
// check if external storage
String state = Environment.getExternalStorageState();
if ( !(Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) ) {
return;
}
// check if a directory named as this application
File rootPath = Environment.getExternalStorageDirectory();
// 'happyShow' is the name of directory
File pictureDirectory = new File(rootPath, "happyShow");
if ( !pictureDirectory.exists() ) {
Log.d("Activity", "NoFoundExternalDirectory");
return;
}
// check if there is any picture
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jpeg") ||
name.endsWith(".jpg") ||
name.endsWith(".png") );
}
};
String[] sNamelist = pictureDirectory.list(filefilter);
if (sNamelist.length == 0) {
Log.d("Activity", "No pictures in directory.");
return;
}
for (String filename : sNamelist) {
Log.d("Activity", pictureDirectory.getPath() + '/' + filename);
frameAnimation.addFrame(
Drawable.createFromPath(pictureDirectory.getPath() + '/' + filename),
DURATION);
}
return;
}

Resources