Search This Blog

Wednesday 26 September 2018

Set Custom Content on Xamarin Form (New Feature in 3.2.0) Navigation Toolbar

In Xamarin Forms 3.2.0  you can set the custom Navigation Icon & Navigation Text.




<ContentPage>
<NavigationPage.TitleView >
   <StackLayout HorizontalOptions="Start" Orientation="Horizontal">
<Image  HeightRequest="50" WidthRequest="50"  Source="Icon"></Image>
                <Label VerticalOptions="Center" Text="Pragnesh Mistry"  TextColor="White"    />
          </StackLayout>
</NavigationPage.TitleView>
</ContentPage>

Sunday 16 September 2018

Xamarin Forms Timer

Xamarin Form Timer:

Xamarin Form Timer will execute the block of code in specified time interval.


 

// Here is the example that on the click of  Start Button The timer will execute the block of code for every second and update the Label Text & On the Click of Stop Button Timer will stop.

private void btnStartTimer_Clicked(object sender, EventArgs e)
{
    if (btnStartTimer.Text == "Start")
    {
        returnValue = true;
        btnStartTimer.Text = "Stop";
    }
    else
    {
        btnStartTimer.Text="Start";
        returnValue = false;
    }
    int count = 0;
    lblTimer.Text = "";
    Device.StartTimer(TimeSpan.FromSeconds(1), () =>
    {
        // Do something
        count += 1;
        Device.BeginInvokeOnMainThread(() =>
        {
            lblTimer.Text = count.ToString() ;
        });
            return returnValue; // True = Repeat again, False = Stop the timer
    });
}

Wednesday 12 September 2018

Push Notification in Xamarin Form using OneSignal

What is OneSignal
OneSignal is a high volume and reliable push notification service for website and mobile application.

Add NuGet Package
From the solution explorer right click on your project and select Manage NuGet Package Option
then search for the OneSignal and install it.


Android/iOS SDK Setup
  • A OneSignal Account, if you do not already have one
  • Your OneSignal App ID, available in Keys & IDs
  • A Google/Firebase Server API Key
  • An iOS Push Certificate. Generate one here using our provisionator tool.
  • An iOS device (iPhone, iPad, iPod Touch) to test on. The Xcode simulator doesn't support push notifications so you must test on a real device.
  • A Mac with a new version of Xcode
Login With Google or Create Account in OneSignal Then Click on Add App Button To Add new App
Then Select the platform to configure.


For Android Google Freebase Server Key required that you will get from Google freebase console.


For iOS Generate the iOS Push Certifcate and upload it.


From the Keys & IDs you will get the OneSignal APP ID

Add the following code to your App.xaml.cs
using Com.OneSignal;

public App()
{
 InitializeComponent();
 MainPage = new OneSignalXamarinFormsExamplePage();

 OneSignal.Current.StartInit("YOUR_ONESIGNAL_APP_ID")
                 .EndInit();



//when you call the StartInit() method your device player id will register with

// the one signal you can check that from the www.onesignal.com website.

}






UserIDs (getting onesignal playerID)
The OneSignal PlayerID is a UUID (Unique Universal Identifier) that OneSignal gives all devices that use your mobile app or subscribe to your site.

Com.OneSignal.OneSignal.Current.IdsAvailable(getID); //Handle this method
private void getID(string playerID, string pushToken)
{
  // write logic for store playerID in the db
}
 you can write the logic like whenever the app start at that time player id will be stored in database.


Android Setup
<application ....>
 <receiver android:name="com.onesignal.GcmBroadcastReceiver"
           android:permission="com.google.android.c2dm.permission.SEND" >
   <intent-filter>
     <action android:name="com.google.android.c2dm.intent.RECEIVE" />
     <category android:name="${manifestApplicationId}" />
   </intent-filter>
 </receiver>
</application>

Replace all 3 of instances of ${manifestApplicationId} with your package name in AndroidManifest.xml.

iOS Setup
In your application's Info.plist, verify your Bundle Identifier matches you App Settings' Bundle ID,
Enable Background Modes, allow Remote notifications.
Sending push notification to registered device
var viewButton = new Dictionary<string, string>();
viewButton.Add("id", "openCompendium"); viewButton.Add("text", "View"); viewButton.Add("icon", "mail24"); //viewButton this button will display when the notification received in mobile. string postedBy = MasterDetailView.selectedEmail; var notification = new Dictionary<string, object>(); notification["headings"] = new Dictionary<string, string>() { { "en", "New Post Added" } }; notification["contents"] = new Dictionary<string, string>() { { "en", "Xyz Has added a new post for you" } }; notification["include_player_ids"] = new List<string>() { playerID }; //here you can specify the player id notification["buttons"] = new List<object> { viewButton }; // here you can add multiple button //by seperated by comma notification["small_icon"] = "icon20"; notification["priority"] = 10; notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(1).ToString("U"); Com.OneSignal.OneSignal.Current.PostNotification(notification);

Handle action button click in one signal

Com.OneSignal.OneSignal.Current.StartInit("OnesigalAppID"). HandleNotificationOpened(HandleNotificationOpened).EndInit(); private void HandleNotificationOpened(OSNotificationOpenedResult result) { string actionID = result.action.actionID;
// whatever the action id register while sending notification that will return here. }




Thursday 6 September 2018

How to autosize Editor height

An Editor can be made to auto-size to its content by setting the
Editor.AutoSize property to TextChanges,
which is a value of the EditoAutoSizeOption enumeration.
This enumeration has two values: Disabled indicates that automatic resizing is disabled,
and is the default value. TextChanges indicates that automatic resizing is enabled.


<Editor Text="Enter text here" AutoSize="TextChanges" />

Monday 16 July 2018

Xamarin Android: Create Circle Image using custom renderer




XAML File
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:customImage="clr-namespace:CircleImagePRoject"
             x:Class="CircleImagePRoject.MainPage">
    <StackLayout VerticalOptions="Center">
        <Label Text="Create Circle Image Using Xamarin Form" HorizontalOptions="Center" ></Label>
        <Image Source="Users"  HorizontalOptions="Center" VerticalOptions="Center"   HeightRequest="80" WidthRequest="80"></Image>
        <customImage:CircleImageRenderer  Source="Users"  HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="80" WidthRequest="80" ></customImage:CircleImageRenderer>
    </StackLayout>
</ContentPage>



In a Xamarin.Forms Project Create Renderer

CircleImageRenderer.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
 
namespace CircleImagePRoject
{
   public  class CircleImageRenderer:Image
    {
    }
}
 

Xamarin Android Renderer

CircleImage.cs
using System;
using Android.Content;
using Android.Graphics;
using CircleImagePRoject;
using CircleImagePRoject.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
 
[assembly: ExportRenderer(typeof(CircleImageRenderer), typeof(CircleImage))]
namespace CircleImagePRoject.Droid
{
    class CircleImage : ImageRenderer
    {
        public CircleImage(Context context) : base(context)
        {
 
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                if ((int)Android.OS.Build.VERSION.SdkInt < 18)
                {
                    SetLayerType(Android.Views.LayerType.Software, null);
                }
            }
        }
        protected override bool DrawChild(Canvas canvas, Android.Views.View child, long drawingTime)
        {
            try
            {
                var radius = Math.Min(Width, Height) / 2;
                var strokeWidth = 10;
                radius -= strokeWidth / 2;
 
                //Create path to clip
                var path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
                canvas.Save();
                canvas.ClipPath(path);
 
                var result = base.DrawChild(canvas, child, drawingTime);
 
                canvas.Restore();
 
                // Create path for circle border
                path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
 
                var paint = new Paint();
                paint.AntiAlias = true;
                paint.StrokeWidth = 5;
                paint.SetStyle(Paint.Style.Stroke);
                paint.Color = global::Android.Graphics.Color.White;
 
                canvas.DrawPath(path, paint);
 
                //Properly dispose
                paint.Dispose();
                path.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                // Debug.WriteLine("Unable to create circle image: " + ex);
            }
 
            return base.DrawChild(canvas, child, drawingTime);
        }
    }
}
 









Saturday 14 July 2018

How to format date and time in XAML in Xamarin application

<Label Text = “{Binding Date, StringFormat=’create at : { 0:dddd dd MMMM } ‘“} />
output : sunday 27 August

Date Format


How to start emulator through command promt





Starting the emulator



Use the emulator command to start the emulator, as an alternative to running your project or starting it through the AVD Manager.
Here's the basic command-line syntax for starting a virtual device from a terminal prompt:
emulator -avd avd_name [ {-option [value]} … ]
Or
emulator @avd_name [ {-option [value]} … ]
For example, if you launch the emulator from within Android Studio running on a Mac, the default command line will be similar to the following:
$ /Users/janedoe/Library/Android/sdk/tools/emulator -avd Nexus_5X_API_23 -netdelay none -netspeed full
You can specify startup options when you start the emulator, but not later on.
For a list of AVD names, enter the following command:
emulator -list-avds

Tuesday 10 July 2018

Xamarin IOS play and record audio

for start, play and stop recording call interface using dependency service

// write this code on the click event of button or tap gesture event of any control

start recording:
DependencyService.Get<IAudioRecorder>().StartRecording(); //click on start record button
play recording:
DependencyService.Get<IAudioRecorder>().PlayRecording(); //click on play record button
stop recording:
DependencyService.Get<IAudioRecorder>().StopRecording(); //click on stop record button
 

Create the Interface in your Xamarin Form Project 
using System;
namespace AudioRecorderProject.Interfaces
{
    public interface IAudioRecorder
    {
        void StartRecording();
        void StopRecording();
        void PlayRecording();
    }
}
 


Create the audio recorder class in your IOS Project that inherit the interface IAudioRecorder
using System;
using AudioRecorderProject.Interfaces;
using AVFoundation;
using AudioRecorderProject.iOS;
using Foundation;
using System.IO;
using UIKit;
 
[assembly:Xamarin.Forms.Dependency(typeof(AudioRecorder))]
namespace AudioRecorderProject.iOS
{
    public class AudioRecorder : IAudioRecorder
    {
 
        AVAudioRecorder recorder;
        AVPlayer player;
        NSError error;
        NSUrl url;
        NSDictionary settings;
        string audioFilePath;
 
 
        public void StartRecording()
        {
            var audioSession = AVAudioSession.SharedInstance();
            var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord); 
            string fileName = string.Format("Myfile{0}.wav", DateTime.Now.ToString("yyyyMMddHHmmss"));
            audioFilePath = Path.Combine(Path.GetTempPath(), fileName);
            url = NSUrl.FromFilename(audioFilePath);
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(44100.0f),
                NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM),//AVFormat
                NSNumber.FromInt32 (2), //Channels
                NSNumber.FromInt32 (16), //PCMBitDepth 
                NSNumber.FromBoolean (false), //IsBigEndianKey 
                NSNumber.FromBoolean (false) //IsFloatKey
            };
            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };
            settings = NSDictionary.FromObjectsAndKeys(values, keys);
            recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);
            recorder.PrepareToRecord();
            recorder.Record();
 
        }
 
 
        public void PlayRecording()
        {
            url = NSUrl.FromFilename(audioFilePath);
            var asset = AVAsset.FromUrl(url);
            var playerItem = new AVPlayerItem(asset);
            player = new AVPlayer(playerItem);
            var playerLayer = AVPlayerLayer.FromPlayer(player);
            GetController().View.Layer.AddSublayer(playerLayer);
            player.Play();
        } 
 
       public void StopRecording()
        {
            if(recorder!=null){
                recorder.Stop();
            }
        } 
       private static UIViewController GetController()
        {
            var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (vc.PresentedViewController != null)
                vc = vc.PresentedViewController;
            return vc;
        } 
   }
 
}


Note: Add the NSMicrophoneUsageDescription key value in the Source tab of the Info.plist file. This is added by selecting "Privacy – Microphone Usage Description" from the property drop down, and setting an appropriate string:









Popular Posts