Chủ Nhật, 30 tháng 11, 2014

Chơi nhạc remote bằng BackgroundWorker và mediaElement

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.Threading;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
namespace PhoneApp9
{
    public partial class Page3 : PhoneApplicationPage
    {
        private BackgroundWorker bw = new BackgroundWorker();
        double Duration;
        public Page3()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
            mainBar.Minimum = 0;
            mainBar.Maximum = 100;
            
            mediaPlayer.BufferingProgressChanged += new RoutedEventHandler(mediaPlayer_BufferingProgressChanged);
            mediaPlayer.CurrentStateChanged += new RoutedEventHandler(mediaPlayer_CurrentStateChanged);
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = false;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            
        }


        private void timelineSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaPlayer.Position = TimeSpan.FromSeconds(timelineSlider.Value);
        }
        private void mediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            TimeSpan ts = mediaPlayer.NaturalDuration.TimeSpan;
            timelineSlider.Maximum = ts.TotalSeconds;
            timelineSlider.SmallChange = 1;
            timelineSlider.LargeChange = Math.Min(10, ts.Seconds / 10);
        }
        private void seekBar_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            
        }

        void mediaPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            if (mediaPlayer.CurrentState == MediaElementState.Playing)
            {
                Duration = mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
                if (!bw.IsBusy)
                {
                    bw.RunWorkerAsync();
                }
            }
        }
        void mediaPlayer_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            MediaElement m = (MediaElement)sender;
            System.Diagnostics.Debug.WriteLine("Progress change:" + m.BufferingProgress);
            if (m.BufferingProgress == 1)
                System.Diagnostics.Debug.WriteLine(m.NaturalDuration);
        }
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            double Progress = mediaPlayer.Position.TotalSeconds * 100 / Duration;
            mainBar.Value = Progress;
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                Thread.Sleep(1);
                worker.ReportProgress(1);
            }
            
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Source = new Uri("http://k003.kiwi6.com/hotlink/00wm0efwme/Anh_Nho_Em_Nguoi_Yeu_Cu_-_Minh_Vuong_M4U.mp3", UriKind.Absolute);
            mediaPlayer.Play(); 
            
        }

      
    }
}


File giao diện:

<phone:PhoneApplicationPage
    x:Class="PhoneApp9.Page3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Slider Name="timelineSlider" Margin="5,5,5,5" ValueChanged="timelineSlider_ValueChanged"  Grid.Row="0" />
            <MediaElement Name="mediaPlayer" Grid.Row="1" MediaOpened="mediaPlayer_MediaOpened"></MediaElement>
            <ProgressBar x:Name="mainBar" Height="20" Width="400" Grid.Row="2"></ProgressBar>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>






Thứ Ba, 25 tháng 11, 2014

Đăng kí PeriodicTask update 30 minute

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using System.Threading;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using App4.Resources;

namespace App4
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        private void StartPeriodicTask()
        {
            PeriodicTask periodicTask = new PeriodicTask("PeriodicTaskDemo");
            periodicTask.Description = "Are presenting a periodic task";
            try
            {
                ScheduledActionService.Add(periodicTask);
                ScheduledActionService.LaunchForTest("PeriodicTaskDemo", TimeSpan.FromSeconds(3));
                MessageBox.Show("Open the background agent success");
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("exists already"))
                {
                    MessageBox.Show("Since then the background agent success is already running");
                }
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background processes for this application has been prohibited");
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type has already been added."))
                {
                    MessageBox.Show("You open the daemon has exceeded the hardware limitations");
                }
            }
            catch (SchedulerServiceException)
            {

            }
        }
        private void StopPeriodicTask()
        {
            try
            {
                ScheduledActionService.Remove("PeriodicTaskDemo");
                MessageBox.Show("Turn off the background agent successfully");
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("doesn't exist"))
                {
                    MessageBox.Show("Since then the background agent success is not running");
                }
            }
            catch (SchedulerServiceException)
            {

            }
        }
        private void StartPeriodicTask_Click(object sender, RoutedEventArgs e)
        {
            StartPeriodicTask();
            SetData();
        }
        private void StopPeriodicTask_Click(object sender, RoutedEventArgs e)
        {
            StopPeriodicTask();
        }
        public void SetData()
        {
            Mutex mutex = new Mutex(false, "ScheduledAgentData");
            mutex.WaitOne();
            IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
            if (!setting.Contains("ScheduledAgentData"))
            {
                setting.Add("ScheduledAgentData", "Foreground data");
            }
            mutex.ReleaseMutex();
        }
    }
}


File ScheduledAgent.cs:


using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Threading;
using System.IO.IsolatedStorage;

namespace App4
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        int i = 0;
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        protected override void OnInvoke(ScheduledTask task)
        {
            if (task.Name.Equals("PeriodicTaskDemo", StringComparison.OrdinalIgnoreCase))
            {
                ShellToast toast = new ShellToast();
                //Mutex mutex = new Mutex(true, "ScheduledAgentData");
                //mutex.WaitOne();
                //IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
                toast.Title = "dsdsdd";
                //mutex.ReleaseMutex();
                toast.Content = "Task Running";
                toast.Show();
            }
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
            NotifyComplete();
        }
    }
}




Nhớ thêm vào WMAppmanifest.xml:
<Tasks>
      <DefaultTask Name="_default" NavigationPage="Page2.xaml" />
      <ExtendedTask Name="BackgroundTask">
        <BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="PeriodicTaskDemo" Source="App4" Type="App4.ScheduledAgent" />
      </ExtendedTask>
 </Tasks>




Download file trong window phone

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage.Pickers;
using Windows.Storage;


namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

        }
        private async void StartDownload_Click(object sender, RoutedEventArgs e)
        {
            var files = (await KnownFolders.MusicLibrary.GetFilesAsync()).ToList();
            try
            {
                Uri source = new Uri("http://dl2.org.mp3.zdn.vn/fsdd1131lwwjA/eba826900e83db77da96c3436248a097/54747d50/2014/08/14/3/3/33708eefc30639ec79bd70a7c6009ddc.mp3?filename=Su%20That%20Sau%20Mot%20Loi%20Hua%20-%20Chi%20Dan.mp3");
                string destination = "okok";

                if (destination == "")
                {

                    return;
                }

                //StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                //   destination, CreationCollisionOption.GenerateUniqueName);
                //StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("dd.mp3",CreationCollisionOption.ReplaceExisting);
                StorageFile file1 = await KnownFolders.MusicLibrary.CreateFileAsync("dd2.mp3", CreationCollisionOption.ReplaceExisting);
                /*
                StorageFolder SDDevice = Windows.Storage.KnownFolders.RemovableDevices;
                StorageFolder sdCard = (await SDDevice.GetFoldersAsync()).FirstOrDefault();
                await sdCard.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
                */
                // StorageFile file = await sdCard.GetFileAsync("test.txt"); // for D:\xyz.mp3

               

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(source, file1);



                // Attach progress and completion handlers.
                HandleDownloadAsync(download, true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Download Error", ex);
            }
        }
        private async void HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {

                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

            }
            catch (TaskCanceledException)
            {

            }
            catch (Exception ex)
            {

            }
            finally
            {

            }
        }
        private void DownloadProgress(DownloadOperation obj)
        {
            double progress
                = ((double)obj.Progress.BytesReceived / obj.Progress.TotalBytesToReceive);
            DownloadProgressbar.Value = progress * 100;
            System.Diagnostics.Debug.WriteLine("Thong tin download:" + (progress * 100));
            if (progress >= 1.0)
            {

            }
        }
    }
} 


File xaml:
<phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- LOCALIZATION NOTE:
            To localize the displayed strings copy their values to appropriately named
            keys in the app's neutral language resource file (AppResources.resx) then
            replace the hard-coded text value between the attributes' quotation marks
            with the binding clause whose path points to that string name.

            For example:

                Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"

            This binding points to the template's string resource named "ApplicationTitle".

            Adding supported languages in the Project Properties tab will create a
            new resx file per language that can carry the translated values of your
            UI strings. The binding in these examples will cause the value of the
            attributes to be drawn from the .resx file that matches the
            CurrentUICulture of the app at run time.
         -->

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Download" Margin="0,150,0,0"
            HorizontalAlignment="Center"  VerticalAlignment="Center" 
            Height="58" Width="145" FontSize="17" 
            Click="StartDownload_Click"/>
            <ProgressBar HorizontalAlignment="Center"
                 Height="30" Margin="0,-30,0,0" 
                 VerticalAlignment="Center" 
                 Width="400" x:Name="DownloadProgressbar"/>
        </Grid>

        <!--Uncomment to see an alignment grid to help ensure your controls are
            aligned on common boundaries.  The image has a top margin of -32px to
            account for the System Tray. Set this to 0 (or remove the margin altogether)
            if the System Tray is hidden.

            Before shipping remove this XAML and the image itself.-->
        <!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
    </Grid>

</phone:PhoneApplicationPage>