Jumat, 22 Agustus 2014

WindowsPhone :Get X and Y coordinates of user tap/touch relative to screen(C#-XAML)

Introduction:

This article is explained about "how to get the X Y coordinates of a touch/tap on a touchscreen device powered by WindowsPhone".And we are very lucky,there are tons of guides on how to add a touch handle to a specific screen windows,but I would like to take advantage of "Touch.FrameReported" event is defined in the namespace "System.Windows.Input" and the event occurs when a touch message is sent from the UI.

Note:Manipulation events are the recommended way to handle user input. Unless you have a specific need, you should avoid using mouse events in your Silverlight applications for Windows Phone for performance and hardware compatibility reasons. Instead, you should use manipulation events.

Realtime Example:
Suppose we are trying to develop a handwriting recognition for an application.And we would like to know are there any api or libraries through which we could recognize which alphabet is traced on the screen or which gesture is drawn on the screen other than the prefixed ones like drag, slide, etc....(Example something like InkPresenter is for windowsphone 8)

Touch.FrameReported event is available in windowsphone 7.0 , windowsphone 7.1, windowsphone 8.0.Below is a sample code snippet demonstrating how to get the position where the user clicked on the screen using Touch.FrameReported event.


C#

 public partial class MainPage : PhoneApplicationPage 
    { 
        // Constructor 
        public MainPage() 
        { 
            InitializeComponent(); 
            Touch.FrameReported += Touch_FrameReported; 
        } 
        void Touch_FrameReported(object sender, TouchFrameEventArgs e) 
        { 
            TouchPoint touchPoint = e.GetTouchPoints(this.ContentPanel).FirstOrDefault(); 
            if (touchPoint.Action == TouchAction.Up) 
            MessageBox.Show("Selected coordinates:"+touchPoint.Position.X + "," + touchPoint.Position.Y);//Displaying x&y co-ordinates of Touch point 
        } 
    }
Output:


WpTouchSample
FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)



Kamis, 21 Agustus 2014

WindowsPhone 8.1 Optical Character Recognition(OCR) Library :Read Text from Images (C#-XAML)

1.Introduction:

Wow! the most wanted library is now supported for windowsphone 8.1.lot of developers waiting for this library,And finally it was released by Microsoft in last "Preview Program".Optical Character Recognition(OCR) library is helpful to read text from images and returns the text and layout information . 
OCR library features:
  • Ability to recognize patterns (Ex: email,phone,URI's) from Image text
  • Launching Above patterns(Ex:Making Phone Call,Sending Mail,Visit Website)
OCR Limitations:
  • Image dimension should be  >= 40*40 pixels and <= 2600*2600 pixels
  • Image text lines must have written in same orientations and same directions.Fortunately OCR can able to correct rotation up to ±40 degrees.
An inaccurate reading may be caused by the following:
  • Blurry images
  • Handwritten or cursive text
  • Artistic font styles
  • Small text size (less than 15 pixels for Western languages, or less than 20 pixels for East Asian languages)
  • Complex backgrounds
  • Shadows or glare over text
  • Perspective distortion
  • Oversized or dropped capital letters at the beginnings of words
  • Subscript, superscript, or strike-through text and please read more from here

2.Building the sample:

  • Make sure you’ve downloaded and installed the Windows Phone SDK. For more information, see Get the SDK.
  • I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
  • This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows.

3.Download and install the OCR Library:

This library is not included in Windows Software Development Kit (SDK).And it is distributed as a NuGet package,so to install this library  right click on your project=>Click on "Manage NuGet Packages" =>Online=>and search for "Microsoft.Windows.Ocr."  => Click on "Install" button.See below image for your reference

"Any CPU" problem:

This library does not work on "AnyCPU" target platform, to change the build configuration of your project from AnyCPU to x86, x64, or ARM Right click on the Solution -> Click on Configuration Properties -> Configuration Manager and change the active solution platform to x86 (If you are using an emulator) or ARM (If you are using a Windows Phone device).

After you install the OCR library into your project, "OcrResources" folder will be add to your project which is having "MsOcrRes.orp" file

When you install the package, the file <solution_name>\packages\Microsoft.Windows.Ocr.1.0.0\OcrResources \MsOcrRes.orp is copied and injected into your project in the location <solution_name>\<project_name>\OcrResources\MsOcrRes.orp. This file is consumed by the OcrEngine object for text recognition in a specific language.

4.OCR supported languages:

There are 21 supported languages. Based on recognition accuracy and performance, supported languages are divided into three groups:
  • Excellent: Czech, Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Polish, Portuguese, Spanish and Swedish.
  • Very good: Chinese Simplified, Greek, Japanese, Russian and Turkish.
  • Good: Chinese Traditional and Korean.
Note:By default English language resources are included in the target project.If you want to use a custom group of languages in your app, use the OCR Resources Generator tool to generate a new OCR resources file, and replace the resources that were injected into your project when you installed the package

To generate OCR resource files

  • Launch the OCR Resources Generator tool located at <solution_name>\packages\Microsoft.Windows.Ocr.1.0.0\OcrResourcesGenerator\OcrResourcesGenerator.exe.And you would be found following dialog box


  • Use the buttons in the center of the tool to create a list of the required languages.
  • Click the Generate Resources button. Pick a location to save the new resources file.
  • Replace the existing file <solution_name>\<project_name>\OcrResources\MsOcrRes.orp with the new file that you just generated.

5.How to extract text from an image?

Step1:In page constructor, create and initialize a global instance of the OcrEngine. Also declare two unsigned integer variables to store the width and height of the image.

Step2:Load the your image,convert it to WriteableBitmap to get image pixels height and width

Step3:Check image dimension should be  > 40*40 pixels and < 2600*2600 pixels

Step4:Call the RecognizeAsync method of the OcrEngine class. This method returns an OcrResult object, which contains the recognized text and its size and position. The result is split into lines, and the lines are split into words.

Step5:So after following above steps your code is like this for extract text from image.

C#

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 
using System.Threading.Tasks; 
using Windows.Foundation; 
using Windows.Foundation.Collections; 
using Windows.Storage; 
using Windows.Storage.FileProperties; 
using Windows.UI; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Media.Imaging; 
using Windows.UI.Xaml.Navigation; 
using WindowsPreview.Media.Ocr; 
 
 
 
namespace OCRImgReadText 

    
    public sealed partial class MainPage : Page 
    { 
        // Bitmap holder of currently loaded image. 
        private WriteableBitmap bitmap; 
        // OCR engine instance used to extract text from images. 
        private OcrEngine ocrEngine; 
 
        public MainPage() 
        { 
            this.InitializeComponent(); 
            ocrEngine = new OcrEngine(OcrLanguage.English); 
            TextOverlay.Children.Clear(); 
        } 
 
         
        protected override async void OnNavigatedTo(NavigationEventArgs e) 
        { //Get local image
            var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("TestImages\\SQuotes.jpg"); 
            await LoadImage(file); 
        } 
        private async Task LoadImage(StorageFile file) 
        { 
            ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); 
 
            using (var imgStream = await file.OpenAsync(FileAccessMode.Read)) 
            { 
                bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); 
                bitmap.SetSource(imgStream); 
                PreviewImage.Source = bitmap; 
            } 
        } 
        private async void ExtractText_Click(object sender, RoutedEventArgs e) 
        { 
            //// Prevent another OCR request, since only image can be processed at the time at same OCR engine instance. 
            //ExtractTextButton.IsEnabled = false; 
 
            // Check whether is loaded image supported for processing. 
            // Supported image dimensions are between 40 and 2600 pixels. 
            if (bitmap.PixelHeight < 40 || 
                bitmap.PixelHeight > 2600 || 
                bitmap.PixelWidth < 40 || 
                bitmap.PixelWidth > 2600
            { 
                ImageText.Text = "Image size is not supported." + 
                                    Environment.NewLine + 
                                    "Loaded image size is " + bitmap.PixelWidth + "x" + bitmap.PixelHeight + "." + 
                                    Environment.NewLine + 
                                    "Supported image dimensions are between 40 and 2600 pixels."
                //ImageText.Style = (Style)Application.Current.Resources["RedTextStyle"]; 
 
                 return
            } 
 
            // This main API call to extract text from image. 
            var ocrResult = await ocrEngine.RecognizeAsync((uint)bitmap.PixelHeight, (uint)bitmap.PixelWidth, bitmap.PixelBuffer.ToArray()); 
 
            // OCR result does not contain any lines, no text was recognized.  
            if (ocrResult.Lines != null
            { 
                // Used for text overlay. 
                // Prepare scale transform for words since image is not displayed in original format. 
                var scaleTrasform = new ScaleTransform 
                { 
                    CenterX = 0
                    CenterY = 0
                    ScaleX = PreviewImage.ActualWidth / bitmap.PixelWidth, 
                    ScaleY = PreviewImage.ActualHeight / bitmap.PixelHeight, 
                }; 
 
                if (ocrResult.TextAngle != null
                { 
                  
                    PreviewImage.RenderTransform = new RotateTransform 
                    { 
                        Angle = (double)ocrResult.TextAngle, 
                        CenterX = PreviewImage.ActualWidth / 2
                        CenterY = PreviewImage.ActualHeight / 2 
                    }; 
                } 
 
                string extractedText = ""
 
                // Iterate over recognized lines of text. 
                foreach (var line in ocrResult.Lines) 
                { 
                    // Iterate over words in line. 
                    foreach (var word in line.Words) 
                    { 
                        var originalRect = new Rect(word.Left, word.Top, word.Width, word.Height); 
                        var overlayRect = scaleTrasform.TransformBounds(originalRect); 
 
                        var wordTextBlock = new TextBlock() 
                        { 
                            Height = overlayRect.Height, 
                            Width = overlayRect.Width, 
                            FontSize = overlayRect.Height * 0.8
                            Text = word.Text, 
                           
                        }; 
 
                        // Define position, background, etc. 
                        var border = new Border() 
                        { 
                            Margin = new Thickness(overlayRect.Left, overlayRect.Top, 00), 
                            Height = overlayRect.Height, 
                            Width = overlayRect.Width, 
                            Background=new SolidColorBrush(Colors.Orange),Opacity=0.5,HorizontalAlignment=HorizontalAlignment.Left,VerticalAlignment=VerticalAlignment.Top, 
                            Child = wordTextBlock, 
                           
                        }; 
                        OverlayTextButton.IsEnabled = true
                        // Put the filled textblock in the results grid. 
                        TextOverlay.Children.Add(border); 
                        extractedText += word.Text + " "
                    } 
                    extractedText += Environment.NewLine; 
                } 
 
                ImageText.Text = extractedText; 
                
            } 
            else 
            { 
                ImageText.Text = "No text."
                
            } 
        } 
 
        private void OverlayText_Click(object sender, RoutedEventArgs e) 
        { 
            if(TextOverlay.Visibility==Visibility.Visible) 
            { 
                TextOverlay.Visibility = Visibility.Collapsed; 
            } 
            else 
            { 
                TextOverlay.Visibility = Visibility.Visible; 
            } 
        } 
    } 
Step6:And your UI might be like this

XAML

<Grid
        <Grid.RowDefinitions
            <RowDefinition Height="Auto"/> 
            <RowDefinition Height="Auto"/> 
            <RowDefinition Height="*"/> 
        </Grid.RowDefinitions> 
        <StackPanel Grid.Row="1" x:Name="ControlPanel"  Orientation="Vertical"
        <StackPanel   Orientation="Horizontal" Margin="10,0,10,0" 
                <Button x:Name="ExtractTextButton" Content="Extract Image Text" FontSize="15" MinWidth="90" Click="ExtractText_Click"  Margin="0,0,5,0"/> 
                <Button x:Name="OverlayTextButton" IsEnabled="False" Content="Overlay Image Text" FontSize="15" MinWidth="90" Click="OverlayText_Click"  Margin="0,0,5,0"/> 
            </StackPanel> 
        <StackPanel Grid.Row="1" Orientation="Horizontal"/> 
        </StackPanel> 
        <ScrollViewer Grid.Row="2" VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto" Margin="0, 10, 0, 0"
            <!-- This StackPanel changes its Orientation depending on the available width of the window. --> 
            <StackPanel x:Name="Output" Margin="10,0,10,0" Orientation="Vertical" Visibility="Visible"
 
                <StackPanel x:Name="Content" Orientation="Vertical" Visibility="Visible"
 
                    <Grid x:Name="Image"
                        <Image x:Name="PreviewImage" Margin="0,0,10,10"  Source="" Stretch="Uniform" Width="300" HorizontalAlignment="Left" VerticalAlignment="Top"/> 
                        <Grid x:Name="TextOverlay" Visibility="Collapsed" Margin="0,0,10,10"  HorizontalAlignment="Left" VerticalAlignment="Top"/> 
                     </Grid> 
 
                    <!-- This StackPanel contains all of the image properties output. --> 
                    <Grid x:Name="Result" HorizontalAlignment="Left" VerticalAlignment="Top"
                        <Grid.RowDefinitions
                            <RowDefinition Height="Auto"/> 
                            <RowDefinition Height="Auto"/> 
                        </Grid.RowDefinitions> 
                        <TextBlock Grid.Row="0" FontSize="25" Text="Extracted image text:" /> 
                        <TextBlock Name="ImageText" Grid.Row="1" Foreground="#FF1CD399" FontSize="25" Text="Text not yet extracted."/> 
 
                    </Grid> 
 
                </StackPanel> 
 
            </StackPanel> 
        </ScrollViewer> 
    </Grid>

6.Output:


WpOCRSample
Note:When you run this downloaded sample ,you will get following error ,So you must install OCR library from "Manage NuGet Packages" 

FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)


Rabu, 13 Agustus 2014

WindowsPhone Dev centre:Wow! now most of app "Publishers" can respond to app customers reviews in windowphone store:

Introduction:

How it is sweet to listen?and i am very happy to share this info to my blog visitors.Microsoft again one step forward is now most of developers/publishers can respond to reviews of our WindowsPhone apps directly from Dev Center. And this feature appeared in the Google Play Store last year and has been highly popular with developers, so it's good to see it coming to Microsoft's app stores as well. So far the main concern is to help you maintain closer contact with users to inform them of new features, bugs you’ve addressed, as well as get feedback and ideas to improve your app.
More Windows Phone developers are now able to respond to comments and reviews from customers in the Windows Phone Store. Since April, certain developers had the ability to answer inquiries related to a specific app. The rollout of this feature has been taking place slowly, with more developers supported each month, and is now proceeding at a quicker pace.


Note1:
  • Developers can respond to reviews written by Windows Phone 7, and Windows Phone 8 users, only if the writer of the review had his country and region set to the U.S.
  •  Any review written by someone using Windows Phone 8.1 can be responded to, regardless of country and region setting. 
Note2:This feature should not be used for marketing purposes. Note that Microsoft respects customer preferences and won’t send review responses to customers who have informed us that they don’t want to receive them. Also note that you won’t receive the customer’s personal contact information as part of this feature; Microsoft will send your response directly to the customer.

How to respond to customer reviews?

Microsoft has left a set of instructions for developers to follow: 
  1. Sign into the Dev Center and then into the Dashboard
  2. Go to the Apps section and select an app.
  3.  Select Reviews and pick the one that you want to respond to. 
  4. Click on Respond, write your message, and then click on Send.
Step1:Make sure you entered your supporting mail id when app store submission.To add your "Support email address" metadata you will found "More options for a language" in right side when the time of app store submission like this .

Otherwise you will get an warning message when you trying to open your "Reviews" from your app section like this 
Step2:Now you can found screen like this.Type your respond message below and press send button
Step3:
Once you create a response, users will receive the comment via email from Microsoft and can even contact you directly if you included your support email address in the app submission 'Support email address' metadata.
Remembering Note:
A customer can report an inappropriate review response from a developer through the Report Concern link in the Details section of an app’s Store description. As noted earlier, Microsoft retains the right to revoke developer access to this feature.
FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

Windows Phone 8 Battery API:Retreiving the Remaining time of device battery c#

Introduction:

The Battery class is available from "Windows.Phone.Devices.Power" namespace which includes the property "RemainingDischargeTime" which is a read only property that gets the time left for the windows phone device battery to be fully discharged.Get the access to the Battery instance with the Battery.GetDefault() and then use the property RemainingDischargeTime to retreive the time left.The Battery API makes a nice addition to the WP8 SDK.I can see in the near future that some applications will display the battery metrics on a Live Tile or in the application that hides the System Tray.
The Battery API is pretty easy to use:
  • Get the Battery instance with Battery.GetDefault().
  • Bind to the event RemainingChargePercentChanged.
The battery properties are:
  • RemainingChargePercent: gets a value that indicates the percentage of the charge remaining on the phone’s battery.
  • RemainingDischargeTime: gets a value that estimates how much time is left until the phone’s battery is fully discharged. 
With the following code:
using Windows.Phone.Devices.Power;

namespace BatteryApp
{
public partial class MainPage
{
private readonly Battery _battery;

public MainPage()
{
InitializeComponent();

_battery =
Battery.GetDefault();

_battery.RemainingChargePercentChanged += OnRemainingChargePercentChanged;

UpdateUI();
}

private void OnRemainingChargePercentChanged(object sender, object e)
{
textBlockRemainingCharge.Text = string.Format("{0} %", _battery.RemainingChargePercent); textBlockDischargeTime.Text = string.Format("{0} minutes", _battery.RemainingDischargeTime.TotalMinutes);
}

}
}
Output:

Note: When running this on the emulator, it will show 100% and an infinite discharge time. The above values are fake.

FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

Sabtu, 09 Agustus 2014

WindowsPhone 8.1 Update (GDR 1) SDK:New Updates & More Emulators for Developers :)

Introduction:

Finally the day is arrived and good news for developers is "now windowsphone 8.1 update(GDR1) sdk is available for development".Microsoft published new sdk on this August(i.e "8/1/2014") in "Preview for Developers" program.So this new sdk will be makes developer can able to use few new latest features with respect to existing wp8.1 sdk.I want to be post those latest new features in next article of my blog.However in this post i am going to explained about  "How to install new sdk?" and "How to get new sdk GDR1 emulators?"


Download & Install New SDK:

Step1:First you must need to install Microsoft Visual Studio Express 2013 for Windows with Update 2 or later in your IDE.

Step2:
Download new sdk from Windows Phone 8.1 Update sdk download.Which adds additional emulator images to an existing installation of Visual Studio 2013 Update 2 or later.

See above image in "Introduction" section.This sdk contains two files
  • MobileTools_EmulatorWP81GDR1.exe(1.2 MB)
  • windowsphone81sdkupdate1.iso (940.7 MB)
So right click on "MobileTools_EmulatorWP81GDR1.exe" file =>Choose "Run as administrator",then you will be prompt like this,check agree check and then press install.
After your new SDK installation process will be start like this.

After some time you may prompt like this "Failed to add current user to Hyper-V administrators group"
To resolve this Just Open visual studio as "Run as Administrator". and it resolved problem.

So finally you will be prompt like "Setup Sucessful!"

Step3:After installation, check the available emulators listed in your visual studio , You will be found bunch of new additional emulators are available as 'Emulator 8.1 U1' extension like this.

FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)