Codes

Zip(Archive) API’s in .NET Framework 4.5 – ZipArchive Class

October 22, 2012 .NET, .NET Framework, .NET Framework 4.5, All, Back-2-Bascis, C#.NET, Codes, CodeSnippets, General, Help Links, KnowledgeBase, Microsoft, Samples, VB.NET, VisualStudio, VS2012 1 comment

With release of .NET Framework 4.5, Microsoft has introduced new classes in to System.IO.Compression namespace. These classes will add the necessary programming support for Zipping(Achiving), and Extracting support for Zip Files in your .NET Source Code.

Below are the newly introduced classes as part of .NET Framework 4.5:

ZipArchive – Represents a package of compressed files in the zip archive format.

ZipArchiveEntry – Represents a compressed file within a zip archive.

ZipFile – Provides static methods for creating, extracting, and opening zip archives.

ZipFileExtensions – Provides extension methods for the ZipArchive and ZipArchiveEntry classes.

In this blog post I am going to discuss about ZipArchive class which will help you with most of the important tasks in Archiving a file or folder using .NET.

The ZipArchive class enables you to work with a package of compressed files. The package contains an entry for each compressed file. You can:

  • Retrieve an entry by using the GetEntry method.
  • Retrieve the entire collection of entries by using the Entries property.
  • Create a new entry in the package by calling the overloaded CreateEntry method.

If you add reference for the System.IO.Compression.FileSystem assembly in your project, you can access three extension methods (from the ZipFileExtensions class) for the ZipArchive class: CreateEntryFromFile, CreateEntryFromFile, and ExtractToDirectory. These extension methods enable you to compress and decompress the contents of the entry to a file.

The System.IO.Compression.FileSystem assembly is not available for Windows Store apps.

In Windows Store apps, you can compress and decompress files by using the DeflateStream or GZipStream class, or you can use the Windows Runtime types Compressor and Decompressor.

Here is the quick sample that would help you to understand how to use ZipArchive class. Code is self explanatory – hope that helps. There are three methods ZipFiles – zip all files in a folder, ExtractFile – to extract files with specificname, ExtractFiles – extract multiple files.

Please go through the below code snippet. If you need additional information: visit MSDN Ref on System.IO.Compression, and in later posts we might discuss about the ZipFile class in more detail.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO.Compression;
using System.IO;

namespace ConsoleApp01
{
    class Program
    {
        static void Main(string[] args)
        {
            string targetZip = AppDomain.CurrentDomain.BaseDirectory + "\" + System.Guid.NewGuid().ToString() + ".zip";

            string sourceFolder = AppDomain.CurrentDomain.BaseDirectory + "\Sample01" ; //We are going to zip the whole contents of the folder. 

            Console.WriteLine(String.Format("Now Archiving the folder/file {0}, to target zip:{1} ", sourceFolder, targetZip));

            //Zipping the folder 
            ZipFiles(sourceFolder, targetZip);



            string extractFolder = AppDomain.CurrentDomain.BaseDirectory + "\" + Path.GetFileNameWithoutExtension(targetZip);

            Console.WriteLine(String.Format("Now Extracting the file {0}, to location:{1} ", targetZip, extractFolder));

            //Extract the entire Zip file 
            ExtractFiles(targetZip, extractFolder);



            //Extract files based on search pattern such as *.txt
            string extractFolder2 = AppDomain.CurrentDomain.BaseDirectory + "\" + Path.GetFileNameWithoutExtension(targetZip) + "12";

            Console.WriteLine(String.Format("Now Extracting the selected file(s) {0}, to location:{1} ", targetZip, extractFolder2));
            
            //Extract the entire Zip file 
            ExtractFiles(targetZip, extractFolder2, "*.txt");

            Console.WriteLine("Press any key to exit");

            Console.ReadKey();
        }

        /// <summary>
        /// Zips the files from the source folder - for now single level - assuming that we will be zipping all the files in a folder. 
        /// not the child folders and files in it, we will ignore it.
        /// </summary>
        /// <param name="sourceFilesFolderPath">The source files folder path.</param>
        /// <param name="targetZipFilePath">The target zip file path.</param>
        /// <param name="searchPattern">The search pattern.</param>
        public static void ZipFiles(string sourceFilesFolderPath, string targetZipFilePath, string searchPattern = "")
        {
            //if Source Directory exists. 
            if (Directory.Exists(sourceFilesFolderPath))
            {
                using (FileStream zipToOpen = new FileStream(targetZipFilePath, FileMode.OpenOrCreate))
                {
                    //Open Archieve for update
                    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                    {
                        //Getting directory info
                        DirectoryInfo dInfo = new DirectoryInfo(sourceFilesFolderPath);


                        //Getting all files list in the folder 
                        FileInfo[] filesList = dInfo.GetFiles(searchPattern);

                        if (String.IsNullOrEmpty(searchPattern)) //fail safe to retrieve all
                            filesList = dInfo.GetFiles();

                        if (filesList != null && filesList.Length > 0)
                        {
                            //Creating archieve entry for each file in the folder 
                            foreach (FileInfo file in filesList)
                            {
                                archive.CreateEntryFromFile(file.FullName, file.Name);
                            }
                        }


                    }

                }
            }
            else
            {
                throw new DirectoryNotFoundException(String.Format("Source folder: {0} not found",sourceFilesFolderPath);
            }

        }




        /// <summary>
        /// Extracts the files.
        /// </summary>
        /// <param name="sourceZipPath">The source zip path.</param>
        /// <param name="targetExtractPath">The target extract path.</param>
        /// <param name="conditionalExtractPattern">The conditional extract pattern.(OPTIONAL)</param>
        public static void ExtractFiles(string sourceZipPath, string targetExtractPath, string conditionalExtractPattern = "")
        {
            string zipPath      = sourceZipPath;  //Source Zip File 
            string extractPath  = targetExtractPath; //Path to Extract

            if (!Directory.Exists(targetExtractPath))
            {
                Directory.CreateDirectory(targetExtractPath);
            }

            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {

                //STEP 1
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    //Conditional extract
                    if (!String.IsNullOrEmpty(conditionalExtractPattern))
                    {
                        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName),true);
                        }
                    }
                    else // extract all..
                    {
                        entry.ExtractToFile(Path.Combine(extractPath, entry.FullName),true);
                    }

                    
                }

                //Or EXTRACT ALL USING 

                //STEP 2
                //archive.ExtractToDirectory(targetExtractPath);

            } 

        }




        /// <summary>
        /// Extracts the file.
        /// </summary>
        /// <param name="sourceZipPath">The source zip path.</param>
        /// <param name="targetExtractPath">The target extract path.</param>
        /// <param name="extractFileName">Name of the extract file.</param>
        public static void ExtractFile(string sourceZipPath, string targetExtractPath, string extractFileName)
        {
            string zipPath = sourceZipPath;  //Source Zip File 
            string extractPath = targetExtractPath; //Path to Extract

            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                //STEP 1
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    //Conditional extract
                    if (!String.IsNullOrEmpty(extractFileName))
                    {
                        //Extract the file.
                        if (entry.FullName.EndsWith(extractFileName, StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), true);
                        }
                    }

                }

            }

        }

    
    }
}


Windows Phone Development–Background Agents in Windows Phone

April 26, 2012 .NET, All, Codes, KnowledgeBase, Microsoft, Microsoft SDKs, Mobile-Development, Silverlight, VisualStudio, VS2010, Windows, Windows Phone, Windows Phone "Mango", Windows Phone "Tango", Windows Phone 7, Windows Phone 7.0, Windows Phone 7.5, Windows Phone Development, Windows Phone SDK No comments

Windows Phone came through long way after it’s initial release on Oct 21st 2010.  Windows Phone 7.5 update release called as “MANGO” brought lots of improvements including Multi tasking capabilities etc. With the introduction of multi-tasking ( it is not true multi tasking, but an efficient application switching which ensures that only one application will reside in memory and remaining running applications will be in deactivated stage. Since the application is not killed, it can be launched faster – that gives the capability similar to true multi tasking).

What is Background Agents?

Background agents feature allows you to run certain code in a background thread and scheduled tasks  are that runs periodically.

Scheduled Tasks and background agents allow an application to execute code in the background, even when the application is not running in the foreground. The different types of Scheduled Tasks are designed for different types of background processing scenarios and therefore have different behaviors and constraints.

Note: that Background agents are not supported in 256MB devices. Only initial 512MB devices with Windows Phone “MANGO” would be able to run background agents

 

There are types of scheduled tasks or Background Agents and they are:

1. Periodic Task Agents- Periodic task agents will run for a short period of time and does a certain predefined operations defined by you. It also have the capability to run based on certain time interval.

A typical example would be checking whether device is having network connectivity periodically or checking any mails available with mail server etc.

2. Resource Intensive Task Agents- Resource Intensive tasks agents will run for a long period if all your network connectivity(if you need some network processing while doing the task) and power and resource usage etc.

A Typical example of scenario would be your phone receiving some application data updates and additional feature set update etc.

 

Using Background Agents:

1. To start with Scheduled tasks agents are part of Microsoft.Phone.Scheduler namespace

2. Create a new Windows Phone Scheduled Task project in your Windows Phone solution

image

3. Click on “OK” and Now I created a Windows Phone Scheduled Task project called  “ScheduledTaskAgent1

and this is how the initial code generated by Visual Studio will appear

using System.Windows;
using Microsoft.Phone.Scheduler;

namespace ScheduledTaskAgent1
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        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();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background

            NotifyComplete();
        }
    }
}

Now you can see there is an OnInvoke(ScheduledTask task) method, inside that method we will define our Periodic or Resource Intensive tasks implementation.

 

4. Now it is the time for us to do our implementation.  (This sample I have taken from MSDN Reference on How to: Implement Background Agents for Windows Phone)

         a.) Scheduled Task Code Implementation (this code will send toast messages, so that you can see that when your application is running in background. )

 /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {

              //TODO: Add code to perform your task in background
              string toastMessage = "";

              // If your application uses both PeriodicTask and ResourceIntensiveTask
              // you can branch your application code here. Otherwise, you don't need to.
              if (task is PeriodicTask)
              {
                // Execute periodic task actions here.
                toastMessage = "Periodic task are running.";
              }
              else
              {
                // Execute resource-intensive task actions here.
                toastMessage = "Resource-intensive task are running.";
              }

              // Launch a toast to show that the agent is running.
              // The toast will not be shown if the foreground application is running.
              ShellToast toast = new ShellToast();
              toast.Title = "Background Agent Sample";
              toast.Content = toastMessage;
              toast.Show();

              // If debugging is enabled, launch the agent again in one minute.
            #if DEBUG_AGENT
              ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
            #endif

              // Call NotifyComplete to let the system know the agent is done working.


            NotifyComplete();
        }

     

     b.) MainPage.xaml  markup

<span style="color: blue">&lt;</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage 
    </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Class</span><span style="color: blue">=&quot;PhoneApp1.MainPage&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">x</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">phone</span><span style="color: blue">=&quot;clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">shell</span><span style="color: blue">=&quot;clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">d</span><span style="color: blue">=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">mc</span><span style="color: blue">=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    </span><span style="color: red">mc</span><span style="color: blue">:</span><span style="color: red">Ignorable</span><span style="color: blue">=&quot;d&quot; </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignWidth</span><span style="color: blue">=&quot;480&quot; </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignHeight</span><span style="color: blue">=&quot;768&quot;
    </span><span style="color: red">FontFamily</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontFamilyNormal</span><span style="color: blue">}&quot;
    </span><span style="color: red">FontSize</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontSizeNormal</span><span style="color: blue">}&quot;
    </span><span style="color: red">Foreground</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneForegroundBrush</span><span style="color: blue">}&quot;
    </span><span style="color: red">SupportedOrientations</span><span style="color: blue">=&quot;Portrait&quot; </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Portrait&quot;
    </span><span style="color: red">shell</span><span style="color: blue">:</span><span style="color: red">SystemTray.IsVisible</span><span style="color: blue">=&quot;True&quot;&gt;

    </span><span style="color: green">&lt;!--LayoutRoot is the root grid where all page content is placed--&gt;
    </span><span style="color: blue">&lt;</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;LayoutRoot&quot; </span><span style="color: red">Background</span><span style="color: blue">=&quot;Transparent&quot;&gt;
        &lt;</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">&gt;
            &lt;</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">=&quot;Auto&quot;/&gt;
            &lt;</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">=&quot;*&quot;/&gt;
        &lt;/</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">&gt;

        </span><span style="color: green">&lt;!--TitlePanel contains the name of the application and page title--&gt;
        </span><span style="color: blue">&lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;TitlePanel&quot; </span><span style="color: red">Grid.Row</span><span style="color: blue">=&quot;0&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;12,17,0,28&quot;&gt;
            &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;ApplicationTitle&quot; </span><span style="color: red">Text</span><span style="color: blue">=&quot;Craziness App&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextNormalStyle</span><span style="color: blue">}&quot;/&gt;
            &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;PageTitle&quot; </span><span style="color: red">Text</span><span style="color: blue">=&quot;Tasks Sample&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;9,-7,0,0&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle1Style</span><span style="color: blue">}&quot;/&gt;
        &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;

        </span><span style="color: green">&lt;!--ContentPanel - place additional content here--&gt;
        </span><span style="color: blue">&lt;</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;ContentPanel&quot; </span><span style="color: red">Grid.Row</span><span style="color: blue">=&quot;1&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;12,0,12,0&quot;&gt;

            &lt;</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;</span><span style="color: #a31515">StackPanel  </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Vertical&quot; </span><span style="color: red">Name</span><span style="color: blue">=&quot;PeriodicStackPanel&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;0,0,0,40&quot;&gt;
                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;Periodic Agent&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}&quot;/&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;name: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is enabled&quot; </span><span style="color: red">VerticalAlignment</span><span style="color: blue">=&quot;Center&quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">=&quot;PeriodicCheckBox&quot; </span><span style="color: red">IsChecked</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}&quot; </span><span style="color: red">Checked</span><span style="color: blue">=&quot;PeriodicCheckBox_Checked&quot; </span><span style="color: red">Unchecked</span><span style="color: blue">=&quot;PeriodicCheckBox_Unchecked&quot;/&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is scheduled: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last scheduled time: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;expiration time: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last exit reason: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;</span><span style="color: #a31515">StackPanel  </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Vertical&quot; </span><span style="color: red">Name</span><span style="color: blue">=&quot;ResourceIntensiveStackPanel&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;0,0,0,40&quot;&gt;
                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;Resource-intensive Agent&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}&quot;/&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;name: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is enabled&quot; </span><span style="color: red">VerticalAlignment</span><span style="color: blue">=&quot;Center&quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox&quot; </span><span style="color: red">IsChecked</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}&quot; </span><span style="color: red">Checked</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox_Checked&quot; </span><span style="color: red">Unchecked</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox_Unchecked&quot;/&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is scheduled: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last scheduled time: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;expiration time: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last exit reason: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
            &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;


        &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
 
    </span><span style="color: green">&lt;!--Sample code showing usage of ApplicationBar--&gt;
    &lt;!--&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
        &lt;shell:ApplicationBar IsVisible=&quot;True&quot; IsMenuEnabled=&quot;True&quot;&gt;
            &lt;shell:ApplicationBarIconButton IconUri=&quot;/Images/appbar_button1.png&quot; Text=&quot;Button 1&quot;/&gt;
            &lt;shell:ApplicationBarIconButton IconUri=&quot;/Images/appbar_button2.png&quot; Text=&quot;Button 2&quot;/&gt;
            &lt;shell:ApplicationBar.MenuItems&gt;
                &lt;shell:ApplicationBarMenuItem Text=&quot;MenuItem 1&quot;/&gt;
                &lt;shell:ApplicationBarMenuItem Text=&quot;MenuItem 2&quot;/&gt;
            &lt;/shell:ApplicationBar.MenuItems&gt;
        &lt;/shell:ApplicationBar&gt;
    &lt;/phone:PhoneApplicationPage.ApplicationBar&gt;--&gt;

</span><span style="color: blue">&lt;/</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage</span><span style="color: blue">&gt;
</span>

and this is how my application screen would look like

image

   c. MainPage.xaml.cs implementation

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
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 Microsoft.Phone.Tasks;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        PeriodicTask periodicTask;
        ResourceIntensiveTask resourceIntensiveTask;

        string periodicTaskName = "PeriodicAgent";
        string resourceIntensiveTaskName = "ResourceIntensiveAgent";
        public bool agentsAreEnabled = true;
        bool ignoreCheckBoxEvents = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
         
        }



        private void StartPeriodicAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);
                PeriodicStackPanel.DataContext = periodicTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in 30 seconds.
             //   #if(DEBUG_AGENT)
                    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
                //#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                    PeriodicCheckBox.IsChecked = false;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }
                PeriodicCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
                PeriodicCheckBox.IsChecked = false;
            }
        }


        private void StartResourceIntensiveAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule.
            if (resourceIntensiveTask != null)
            {
                RemoveAgent(resourceIntensiveTaskName);
            }

            resourceIntensiveTask = new ResourceIntensiveTask(resourceIntensiveTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            resourceIntensiveTask.Description = "This demonstrates a resource-intensive task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(resourceIntensiveTask);
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
                //#if(DEBUG_AGENT)
                    ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(60));
                //#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;

                }
                ResourceIntensiveCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
                ResourceIntensiveCheckBox.IsChecked = false;
            }


        }

        private void PeriodicCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartPeriodicAgent();
        }
        private void PeriodicCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent(periodicTaskName);
        }
        private void ResourceIntensiveCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartResourceIntensiveAgent();
        }
        private void ResourceIntensiveCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent(resourceIntensiveTaskName);
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ignoreCheckBoxEvents = true;

            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            if (periodicTask != null)
            {
                PeriodicStackPanel.DataContext = periodicTask;
            }

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;
            if (resourceIntensiveTask != null)
            {
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;
            }

            ignoreCheckBoxEvents = false;

        }




        private void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
            }
        }

    }
}

             

 d.) and Hit “F5” Smile

 

and below are some screen shots for reference.

  1. App is running and Periodic Agent is enabled to run on every 30 seconds.

image

now after 30 seconds scheduled tasks run and called the Scheduled Task implementation

image

 

and can see that last run status is updated and last run reason is completed.

image

 

Apologies for the Poor formatting.

Hope the code is self explanatory and since the Post is so big after the code blocks and screen shots, I am not including much explanations of this sample. You can read MSDN Reference on How to: Implement Background Agents for Windows Phone, which includes clear cut explanation of the above sample.

References:

Background Agents Overview for Windows Phone

How to: Implement Background Agents for Windows Phone

Apple Push Notifications Service API & C#

July 6, 2011 .NET, All, C#.NET, Codes, General, KnowledgeBase, Microsoft, Snippets No comments

To start with Apple Push notifications I would have to first explain what is Push Notifications?

In normal mobiles Push services are often based on information preferences expressed in advance. This is called a publish/subscribe model. A client might "subscribe" to various information "channels". Whenever new content is available on one of those channels, the server would push that information out to the user. For Example: the “Mobile Network location” displayed on your mobile, which keeps on changing based on the tower you are connected.

Push notification allows an application to notify you of new messages or events without the need to actually open the application, similar to how a text message will make a sound and pop up on your screen. This is a great way for apps to interact with us in the background, whether it be a game notifying us of some event occurring in our game world or simply the iPad’s mail application beeping as a new message appears in our inbox.

In addition to pushing messages to the screen, push notification allows apps to display a number or ‘badge’ on the app’s icon. For example, the Mail icon will show the number four when we have four unread messages.

The Apple Push Notification Service is a mobile service created by Apple Inc. that was released with iOS 3.0 on June 17, 2009. It uses push technology through a constantly-open IP connection to forward notifications from the servers of third party applications to the iPhone, iPod Touch and iPad; such notifications may include badges, sounds or custom text alerts.

This is a small information quoted from Apple

Apple Push Notification Service requires iOS 3.0 or later and a connection to the Internet, either via a cellular data network or Wi-Fi, and at least one application that supports notifications.

  • If the Settings > Notifications menu does not appear on your device, you don’t have an application installed that supports notifications.
  • You need to open an application at least once to get any notifications from that app.
  • When the iPod touch screen is on and has a Wi-Fi connection, push notifications are received at any time. If the iPod touch screen is asleep, it will check every 15 minutes for a notification.
  • If you want to disable notifications from an application, turn off all notifications for that application in Settings > Notifications.
  • When you restore a backup to a different iPhone or iPod touch, apps will need to be opened again to get notifications.
  • If the device is connected over Wi-Fi and is still unable to receive notifications, the Wi-Fi network you’re using might have a firewall that is blocking port 5223. This port must be open to TCP traffic for notifications to work.

Few days before writing this article I was in an assumption that since iOS is a closed platform, we cannot utilize other java/.NET server components to make calls to Apple Push notifications API. But recent explorations I figured out we can send out push notifications with help of .NET Library (APNS Sharp), read more on my previous article Sending Apple iOS Push notifications using C# . I successfully tested this in iPhone 3G, by sending push notifications from a .NET application.

 

Apple has provided two gateway interfaces, one for development/sandbox and another for production use.

Production environment is available through gateway.push.apple.com, port 2195 ; the binary interface of the sandbox (development) environment is available through gateway.sandbox.push.apple.com, port 2195.

.. keep reading more on Local and Push Notification Programming Guide

 

Quick Note: Make sure your port 2195 is not blocked by your firewall, incase you are getting issues.

Using External Configuration Files in .NET Applications (C#)

August 31, 2010 .NET, All, Back-2-Bascis, C#.NET, Codes, KnowledgeBase, Microsoft 3 comments

This post is about making a small code snippet which read from an external configuration file and get the custom configuration entries from it.

I went through the solutions. My target was to checkout how we can use the external configuration files in an ASP.NET Web.config. The idea is that there are more than one web application is there in my own Virtual Organization. I thought of keeping a common configuration file for all those web application. So that I have to change configuration only in one place, from time to time changes.

1. Scenario 1 :- ASP.NET Application

Here is the solution I came across.

External configuration file(External.config), which will have some set of AppSettings key value pairs.

<?xml version="1.0"?>

<appSettings>

  <add key="Web_App_Name" value="Dream Works India"/>
  <add key="Web_App_ID" value="E1635BA6-0714-4496-A852-18868A0EB591"/>
</appSettings>

ASP.NET Web.config (Which refering to an external config file with name “External.config”)

<?xml version="1.0"?>
<configuration>
	<appSettings configSource="External.config"> <!-- Refering to an External Config File, You should specify the relative path -->
    
	</appSettings>
  
	<system.web>
		<compilation debug="true"/>
  </system.web>

</configuration>


Note: One thing you should make sure is that, in ASP.NET you have to mention the External config file’s relative path. It will not accept if i keep like “C:External.config”

ASP.NET – C# Code (for reading from external config file)

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace DreamWebSiteMain
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string Web_App_Name = WebConfigurationManager.AppSettings["Web_App_Name"];
            string Web_App_Id   = WebConfigurationManager.AppSettings["Web_App_ID"];


            string str = string.Empty;
        }
    }
}

That’s it. We are ready, here is the output i captured while debugging.

2. Scenario 2 :- Console/Windows Application

Here case is bit different from ASP.NET, you cannot simply specify in App.config file. Windows/Console Application would n’t work that way.

You will receive an exception if you try the same in console/windows application.

Error:- “Unable to initialize the configuration entries”
.

So what is other option we have. I came across a code-project article(link Specify a Configuration File at Runtime for a C# Console Application. That was really informative and thoughtful.

So i made slight changes to the code and implemented for my scenario.

External configuration file(C:External.config), which will have some set of AppSettings key value pairs.

<?xml version="1.0"?>

<appSettings>

  <add key="Web_App_Name" value="Dream Works India"/>
  <add key="Web_App_ID" value="E1635BA6-0714-4496-A852-18868A0EB591"/>
</appSettings>

Console Executable App.config (Which will not refering to an external config file with name “External.config”, leave it empty)

<?xml version="1.0"?>
<configuration>
	<appSettings > <!-- forget about linking external config here -->
    
	</appSettings>
  
	<system.web>
		<compilation debug="true"/>
  </system.web>

</configuration>


Note: One thing you should make sure is that, in ASP.NET you have to mention the External config file’s relative path. It will not accept if i keep like “C:External.config”

Console Application – C# Code (for reading from external config file)

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DreamConsoleApp
{
    class Program
    {
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        static void Main(string[] args)
        {
            SetConfigFileAtRuntime(@"C:External.config");  

            string Web_App_Name = ConfigurationManager.AppSettings["Web_App_Name"];
            string Web_App_Id = ConfigurationManager.AppSettings["Web_App_ID"];
            

            string str = string.Empty;
        }


        /// <summary>
        /// Sets the config file at runtime.
        /// </summary>
        /// <param name="configFilePath"></param>
        protected static void SetConfigFileAtRuntime(string configFilePath)
        {
            string runtimeconfigfile;

            if (configFilePath.Length == 0)
            {
                Console.WriteLine("Please specify a config file to read from ");
                Console.Write("> "); // prompt
                runtimeconfigfile = Console.ReadLine();
            }
            else
            {
                runtimeconfigfile = configFilePath;
            }

            // Specify config settings at runtime.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //Similarly you can apply for other sections like SMTP/System.Net/System.Web etc..
            //But you have to set the File Path for each of these 
            config.AppSettings.File = runtimeconfigfile;

            //This doesn't actually going to overwrite you Exe App.Config file.
            //Just refreshing the content in the memory.
            config.Save(ConfigurationSaveMode.Modified);

            //Refreshing Config Section
            ConfigurationManager.RefreshSection("appSettings");
        }

    }
}

That’s it. We are ready to go, here is the output i captured while debugging.

Voila!!!! Everything working as expected. I got the implementations for ASP.NET and Windows/Console App.

Hope this helps. I couldn’t get much time to do proper formatting. Hope you folks don’t mind the beauty of the code.

Happy Learning !!!!