Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, January 27, 2016

Microsoft OCR (Optical Character Recognization) library for Windows Runtime Apps

Microsoft recently announced that their OCR Library for Windows Runtime has been released as a NuGet package. This library enables you to add text reading capabilities to your Windows Phone 8/8.1 and Windows 8.1 Store apps.

A superb example of this great library can be seen in the Microsoft Translator apps where images are OCRd and the extracted text is then translated to the selected language.



I tested it with a newspaper in English and since I know Hindi I can say that this works perfectly !
Isn't that awesome !

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.

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 strikethrough text
So lets get started to build a basic app that uses the OCR Library. 1.Download and install the OCR Library Go to manage Nuget Packages and search for "Microsoft.Windows.Ocr" 2.Change the solution platform The solution platform is by default "AnyCPU". Change it to "ARM" or "x86". Go to Build -> Configuration Manager and change the active solution platform. 3.Write a function to select an image Obtain a reference of the FileOpenPicker class and call the PickSingleFileAndContinue() method which handles the selection of a single file.
Code:
private void PickImage_Click(object sender, RoutedEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");
    openPicker.PickSingleFileAndContinue();
}
4.Display the recognized text
Code:
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
    displayText.Text = string.Empty;
    if (args.Files.Count > 0)
    {
        StorageFile file = args.Files[0];
        ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync();
        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            WriteableBitmap bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
            bitmap.SetSource(stream);
            DisplayImage.Source = bitmap;
            // Extract text from image.
            OcrResult result = await ocrEngine.RecognizeAsync(imgProp.Height, imgProp.Width, bitmap.PixelBuffer.ToArray());
            // Check whether text is detected.
            if (result.Lines != null)
            {
                // Collect recognized text.
                string recognizedText = "";
                foreach (var line in result.Lines)
                {
                    foreach (var word in line.Words)
                    {
                        recognizedText += word.Text + " ";
                    }
                    recognizedText += Environment.NewLine;
                }
                // Display recognized text.
                displayText.Text = recognizedText;
            }
        }
    }
}
Download the source code Happy Coding !

Working with the StatusBar of the Windows Phone 8.1






Hello everyone !
This blog explains the purpose of Status Bar in Windows Phone 8.1 and how we can leverage it our apps using C# and XAML to give a good user experience.

StatusBar is that area of the phone where information related to battery, network strength is shown.
Let's a look of what the different icons on the StatusBar represent.


The StatusBar can be customized as per our needs to show information or show a progress bar for an indeterminate activity.
Practically, a progress indicator is shown on the StatusBar in every app where data is being loaded on the page or when listviews are refreshed while getting data from a web service.

The StatusBar class is in the Windows.UI.ViewManagement namespace and it provides methods and properties for interacting with status bar on a window (app view).

1. Obtain a reference of the StatusBar class and calls its ShowAsync() method
var statusBar = StatusBar.GetForCurrentView();
await statusBar.ProgressIndicator.ShowAsync();

2.Optionally you can change its background but the opacity has be set at the same time otherwise the StatusBar won't show up.
statusBar.BackgroundColor = Colors.Firebrick;
statusBar.BackgroundOpacity = 1;

3.You can also show a Progress Indicator with a text.
statusBar.ProgressIndicator.Text = "getting information";
await statusBar.ProgressIndicator.ShowAsync();

4.If you want to only show text without the progress indicator then that can be done by :
statusBar.ProgressIndicator.ProgressValue = 0;

5.To hide the ProgressIndicator :
await statusBar.ProgressIndicator.HideAsync();

6.To hide the StatusBar completely :
await statusBar.HideAsync();



Download the source code :-)

Sunday, January 24, 2016

Creating PDF files programmatically in Windows Runtime Apps





Hello everyone ! In this post I'm gonna show, how we can programmatically generate PDF files in our WinRT applications. This a typical requirement in applications like Shopping App, Inventory Management, Banking System etc.. where we may want to generate an invoice for our customers or generate a pdf to show a mini-statement in any banking or finance app and print it.

iTextSharp to the rescue !
iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF)
Generate documents and reports based on data from an XML file or a database.
I've found a lot of stuff which demonstrates the use of iTextSharp in ASP.NET applications but very few on the modern WinRT apps.
Hence, I decided to make one of my own and provide some help to you fellow developers.

Enough said ! Let's directly dive into the code and see a working sample.

1. Install iTextSharp library for Nuget Packages.


2. Next, I create a method to generate a random string to a give a name to the StorageFile object and avoid collisions on every create.

public string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray()) + ".pdf";
        }
3. Create methods for formatting the text that is going to be added to the tableview.

private static void AddCellToHeader(PdfPTable tableLayout, string cellText)
        {
            tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10,1, iTextSharp.text.BaseColor.BLACK))) 
                               { HorizontalAlignment = Element.ALIGN_CENTER, 
                                 Padding = 5, 
                                 BackgroundColor = new BaseColor(255, 255, 255) 
                               });
        }

private static void AddCellToBody(PdfPTable tableLayout, string cellText)
        {
            tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, iTextSharp.text.BaseColor.BLACK)))
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = 5,
                BackgroundColor = new BaseColor(255, 255, 255)
            });
        }

4.Add the following code to generate the pdf file.(In this sample I've demonstrated an example of Mini Statement used in a banking app.)

protected  override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                string path = RandomString(5);
                var storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var file = await storageFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
                if (file != null)
                {
                    await FileIO.WriteTextAsync(file, string.Empty);
                }

                sampleFile = await storageFolder.GetFileAsync(path);
                var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
                Document document = new Document(PageSize.A4, 25, 25, 30, 30);
                PdfWriter writer = PdfWriter.GetInstance(document, stream.AsStream());
                document.Open();

                document.Add(new Paragraph("Mini Statement"));
                document.Add(new Chunk("\n")); // to all line breaks
                document.Add(new Chunk("\n"));

                PdfPTable tableLayout = new PdfPTable(4);
                float[] headers = { 60, 60, 60, 60 };
                tableLayout.SetWidths(headers);
                tableLayout.HorizontalAlignment = Element.ALIGN_LEFT;
                tableLayout.WidthPercentage = 80;
                //Add header
                AddCellToHeader(tableLayout, "Sr no.");
                AddCellToHeader(tableLayout, "Transaction Type");
                AddCellToHeader(tableLayout, "Date");
                AddCellToHeader(tableLayout, "Amount");

                AddCellToBody(tableLayout, "1.");
                AddCellToBody(tableLayout, "Cash Withdrawal");
                AddCellToBody(tableLayout, "April 24, 2015");
                AddCellToBody(tableLayout, "2500");

                AddCellToBody(tableLayout, "2.");
                AddCellToBody(tableLayout, "Cash Deposit");
                AddCellToBody(tableLayout, "July 7, 2015");
                AddCellToBody(tableLayout, "3500");

                AddCellToBody(tableLayout, "3.");
                AddCellToBody(tableLayout, "Funds Transfer");
                AddCellToBody(tableLayout, "October 20, 2015");
                AddCellToBody(tableLayout, "930");

                AddCellToBody(tableLayout, "4.");
                AddCellToBody(tableLayout, "NEFT Transfer");
                AddCellToBody(tableLayout, "November 5, 2015");
                AddCellToBody(tableLayout, "10,000");

                AddCellToBody(tableLayout, "5.");
                AddCellToBody(tableLayout, "Cash Withdrawal");
                AddCellToBody(tableLayout, "April 24, 2015");
                AddCellToBody(tableLayout, "2500");

                AddCellToBody(tableLayout, "6.");
                AddCellToBody(tableLayout, "Cash Deposit");
                AddCellToBody(tableLayout, "July 7, 2015");
                AddCellToBody(tableLayout, "3500");

                AddCellToBody(tableLayout, "7.");
                AddCellToBody(tableLayout, "Funds Transfer");
                AddCellToBody(tableLayout, "October 20, 2015");
                AddCellToBody(tableLayout, "930");

                AddCellToBody(tableLayout, "8.");
                AddCellToBody(tableLayout, "NEFT Transfer");
                AddCellToBody(tableLayout, "November 5, 2015");
                AddCellToBody(tableLayout, "10,000");

                AddCellToBody(tableLayout, "9.");
                AddCellToBody(tableLayout, "NEFT Transfer");
                AddCellToBody(tableLayout, "November 5, 2015");
                AddCellToBody(tableLayout, "10,000");

                AddCellToBody(tableLayout, "10.");
                AddCellToBody(tableLayout, "Cash Withdrawal");
                AddCellToBody(tableLayout, "April 24, 2015");
                AddCellToBody(tableLayout, "2500");

                document.Add(tableLayout);

                // add image to the pdf
                StorageFile imgfile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\verified.jpg");
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri((imgfile.Path)));
                document.Add(img);

                document.Close();
                writer.Close();
            }
            catch (Exception) { }
        }

And that is all. You have you pdf ready which can be saved and printed.



Download the entire source code.
Happy Coding !



Wednesday, November 11, 2015

Difference between "string" and "String" in C#


Hello Folks !

Many times while writing some cool code, you also may have come across this question in your mind and it may have kept you bemused and thinking. So, let's understand the difference between the both.
string s = "Hello world";
String s = "Hello world";
Technically, there's no difference between the two. As far as the syntax is concerned it is recommended to use string whenever you're referring to an object.

string s = "Hello world"
Likewise, it is recommended to use String to call string methods like String.Format(), String.IsNullOrEmpty()


bool x = String.IsNullOrWhiteSpace(txtName.Text)

I hope that makes sense, because methods belong to classes and it is consistent with how other static methods are called.