Monday, 6 February 2017

How to develop your own Text to Speech (Jarvis) Application


This post demonstrates how to develop your own Text to Speech application simply a "Jarvis".

This application is written to just show how simple it is to write text to speech in C#. This application is not fully developed (no multi-threading, no asynchronous calls).

Please follow the blog for fully functional Text to Speech application.

This is how our Jarvis looks like -











Follow these steps to create your own Jarvis -

1. Create a new project of type "Windows Forms Application" targeting .NET Framework 4

Refer to this tutorial How to add a reference to a project






2. Add a reference to System.Speech library


3. Add a System.Speech.Synthesis namespace to your application




4. Modify Form1.cs code as shown below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using System.Speech.Synthesis;

namespace Text_to_Speech
{
    public partial class Form1 : MetroForm
    {        
        private static SpeechSynthesizer synth = new SpeechSynthesizer();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {

            VoiceGender voiceGender = VoiceGender.NotSet;
            int rate = trackBarRate.Value;

            //assign voice Gender based on selection
            if(rdMale.Checked)
            {
                voiceGender = VoiceGender.Male;
            }                
            else
            {
                voiceGender = VoiceGender.Female;
            }

            //set speech rate
            synth.Rate = rate;

            //set voice gender from user selection
            synth.SelectVoiceByHints(voiceGender);

            //welcome message
            synth.Speak("Welcome to Jarvis Application, Version one point oh!");                        

            //start speech
            synth.Speak(txtReadText.Text);
        }
    }
}

5. Copy some text in the text box and click the button Start. So the application starts reading the text in the selected voice type at the given rate.

At the runtime you cannot stop, change voice and rate. To support this we have to add threads in our appication. Please follow this blog for fully developed application.

Wednesday, 18 May 2016

How to add a reference to a library in Windows Forms Application


This post explains how to add a reference to a library in Windows Forms Application.

By default when we create a new Windows Forms Application, the visual studio adds references to only needed libraries to run a windows form application.





In Solution Explorer, References folder contains a list of referenced libraries.

By default, visual studio adds the list of libraries shown in the picture to win form application when you create a new project.





Depending on application requirements the application requires extra libraries (internal or external) to perform some tasks. In this case we have to add a reference to the required libraries.


Follow these simple steps to add a reference to a library for example "System.Speech". This library contains members which supports in speech related tasks.


1. Create a new project of type "Windows Forms Application" from Windows Desktop template with a name "AddSpeechRef".





2. In Solution Explorer, right-click on References folder, Click on "Add Reference" as shown here.








3. From Reference Manager dialog, enter "Speech" in search box, depending on targeted .Net Framework (here targeted .Net Framework 4.0), the corresponding library version will be shown in search results.




Select a check-box "System.Speech" and click OK.








At this point we have added a reference successfully.




4. Simply adding a reference to our application is not sufficient. To use members of added library, we have to add a namespace of library with a keyword "using".




In Form1.cs, add a line "using System.Speech.Synthesis" as shown below. Now we can use all members of the library in application.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Synthesis;  //add namespace in order to utilize members of library

namespace AddSpeechRef
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

In case of external libraries, in Reference Manager dialog, click on Browse and locate the library files (*.dll) on local machine and click on Add.

Tuesday, 17 May 2016

Change Console Foreground Color, Background Color and Title in C#


This post explains how to change foreground color, background color and title of  console window in C#.

In some cases it is required to change the text color in console window depending on the context of application. For example, green color text indicating success or red color text indicating error/warning.

Here is the sample code -

Create a new project of type console application with a name "ConsoleDemoApp" and enter the code in Program.cs as shown here.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Threading;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // We want to save the current console color and background color so we can restore it later
            ConsoleColor oldColor = Console.ForegroundColor;
            ConsoleColor oldBackgroundColor = Console.BackgroundColor;            

            // Set the new console color to Green and background color to Gray
            Console.ForegroundColor = ConsoleColor.Green;
            Console.BackgroundColor = ConsoleColor.DarkGray;
                        
            //set title of console window
            //If you don't set the title, the console window shows the fullpath of .exe in title
            Console.Title = "Console Demo Application";

            // Tell everyone what this program is when it starts
            Console.WriteLine("Welcome to Demo Application");

            Random random = new Random();
            while (true)
            {
                Console.Write("Ask any question: ");
                string question = Console.ReadLine();
                //console window exits until u enter either quit or exit
                if (question.ToLower() == "quit" || question.ToLower() == "exit")
                {
                    break;
                }
                Console.Write("Answer: ");
                switch( random.Next(4) )
                {
                    case 0:
                        Console.WriteLine("Yes!");
                        break;
                    case 1:
                        Console.WriteLine("No!");
                        break;
                    case 2:
                        Console.WriteLine("Probably.");
                        break;
                    case 3:
                        Console.WriteLine("I don't understand!!!");
                        break;
                }
            }

            // Restore the old foreground color and background color
            Console.ForegroundColor = oldColor;
            Console.BackgroundColor = oldBackgroundColor;
        }
    }
}

Output -



Monday, 12 October 2015

IMPORT CSV OR ANY DELIMITED TEXT FILE WITH UNICODE ENCODINGS IN EXCEL USING VBA


This post demonstrates how to import CSV or any delimited text file with Unicode encoded in Excel using VBA code.
By default, text files are encoded in ANSI representation on WINDOWS platform.
When you try to import the ANSI encoded text files into excel using VBA, you may not see problems with the data appearing in the excel worksheet. But there is a problem when importing a text file other than ANSI encoding.

  The Possible Encodings of a Text File – 

 The following are the available character encoding representations of a text file on WINDOWS platform.
  • ANSI (default encoding representation)
  • Unicode
  • Unicode big endian
  • UTF-8
How to know the encoding of a text file?

text encodings

1. Open a text file with notepad editor.

 2. Select File menu and click on Save As

 3. Look at the Encoding at the bottom, which tells you the current encoding of a text file.

 4. Click on Encoding drop-down list, to see the supported encoding representations of a text file on your machine.



What are these encodings?

To understand more about these encodings, please check this link – Byte Order Mark (BOM)

What happens when Unicode encoded text is imported into Excel –

The below sample text file is used for testing. The copy of this file is saved with all possible encodings.

  DelimitedtextFile 4 Rows

 3 Columns

Delimited by ‘,‘ (Comma) 





The following is the output screen when each encoded text file is imported into Excel. When the import button is clicked, the data will be imported from the active cell in a worksheet.
  text encodings
If you look at the output screen, the every first cell of each encoding contains a garbage value.

Reason –

Byte Order Mark (or BOM) is a signal that tells the computer how the bytes are ordered in a Unicode document. Because Unicode can be used in the formats of 8, 16 and 32 bits – it is important for the computer to understand which encoding has been used in the Unicode document. BOM tells exactly the same to the computer. That is why we see the garbage values.

Representation of BOM by encoding –

This table illustrates how BOMs are represented as byte sequences and how they might appear in a text editor that is interpreting each byte as a legacy encoding (CP1252).

EncodingRepresentation (hexadecimal)Representation (decimal)Bytes as CP1252characters
UTF-8[t 1]EF BB BF239 187 191
UTF-16(BE)FE FF254 255þÿ
UTF-16(LE)FF FE255 254ÿþ
As per these representations, we can see the fixed characters for each Unicode encoding when the text file is imported.

How to Resolve –

This can be resolved by replacing the Unicode representation characters with an empty string.

Import Button Code –
1
2
3
Sub DoTheImport()
    ImportTextFile FName:="D:\data.txt", Sep:=","
End Sub
ImportFile is the sub-routine which imports the data. Change the sep:= as per your requirement. In this example comma is the separator.
ImportFile Code –
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Public Sub ImportTextFile(FName As String, Sep As String)

Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer

'disable screen updates
Application.ScreenUpdating = False
'error handling
On Error GoTo EndMacro

'Importing data starts from the selected cell in a worksheet
SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row

'open the file in read mode
Open FName For Input Access Read As #1

'Read the file until End of Line
While Not EOF(1)
    'read line by line
    Line Input #1, WholeLine
    WholeLine = Replace(WholeLine, "", "", vbTextCompare)    'UTF-8
    WholeLine = Replace(WholeLine, "ÿþ", "", vbTextCompare)     'UTF-16 Unicode little endian
    WholeLine = Replace(WholeLine, "þÿ", "", vbTextCompare)     'UTF-16 Unicode big endian
    'checking if the line is empty
    If Right(WholeLine, 1) <> Sep Then
        WholeLine = WholeLine & Sep
    End If
    ColNdx = SaveColNdx
    Pos = 1
    NextPos = InStr(Pos, WholeLine, Sep)
    'finding each column data
    While NextPos >= 1
        TempVal = Mid(WholeLine, Pos, NextPos - Pos)
        Cells(RowNdx, ColNdx).Value = TempVal
        Pos = NextPos + 1
        ColNdx = ColNdx + 1
        NextPos = InStr(Pos, WholeLine, Sep)
    Wend
    RowNdx = RowNdx + 1
Wend

Close #1
Exit Sub

EndMacro:
Application.ScreenUpdating = True
MsgBox Err.Description, vbOKOnly, "Error"
Close #1

End Sub

Summary –

This way you can import any delimited text file with Unicode encodings. Make sure that the text file is not exceeding the maximum number of rows of excel worksheet.

Please share your thoughts on this post in the comments section.

Tuesday, 10 March 2015

Difference between print(null.toString()) and print(null)

This post demonstrates difference between print(null.tostring()) and print(null) in Java programming.
The difference is print(null.tostring()) throws null pointer exception but print(null) doesn't. Why?
Consider the below sample code to understand the concept clearly.

public class NPETest {
    public static void main(String[] args) {
        Object obj1 = null;
        Object obj2 = null;
        System.out.print(obj1.toString()); //throws Null Pointer Exception
        System.out.print(obj2); // prints null
    }
}
 
The statement System.out.print(obj1.toString()) causes following runtime exception.
 
Exception in thread "main" java.lang.NullPointerException
at com.org.s20150310072124635.NPETest.main(NPETest.java:5)
 
The statement System.out.println(obj2) runs fine and prints a text "null".

Why an exception is caused?


Look at the java bytecode of the program.

> javap -classpath target\test-classes -c NPETest

Compiled from "NPETest.java"
public class NPETest extends java.lang.Object{
public NPETest();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   aconst_null
   1:   astore_1
   2:   aconst_null
   3:   astore_2
   4:   getstatic       #17; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   aload_1
   8:   invokevirtual   #23; //Method java/lang/Object.toString:()Ljava/lang/String;
   11:  invokevirtual   #27; //Method java/io/PrintStream.print:(Ljava/lang/String;)V
   14:  getstatic       #17; //Field java/lang/System.out:Ljava/io/PrintStream;
   17:  aload_2
   18:  invokevirtual   #33; //Method java/io/PrintStream.print:(Ljava/lang/Object;)V
   21:  return

}

 In code column, line #8 shows the bytecode representation of calling obj1.toString(). Here obj1 is null and so any attempt on a method invocation on null results in a NullPointerException.


Why print(null) works fine?


Consider the bytecode, in code column line #18 shows the bytecode representation of calling print(obj2). Here object is passed as a parameter to the PrintStream.print() method. According to the Java documentation, the source code will tell you that why this does not result in NullPointerException.

public void print(Object obj) {
    write(String.valueOf(obj));
}

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
 
 The documentation tells that the null reference is handled if null reference is passed. If argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned. So this statement does not result in NullPointerException.

Summary -


print(null.tostring()) causes Null Pointer Exception. print(null) prints text "null".
Please share your thoughts on this post in the comments section.

Monday, 9 March 2015

System.out.println(null) ?

This post demonstrates why System.out.println(null) causes a compilation error and how to resolve.

When you run the statement System.out.println(null), you will see the following compilation error.

 
reference to println is ambiguous, 
both method println(char[]) in java.io.PrintStream and 
method println(java.lang.String) in java.io.PrintStream match

 Because there are (at least) two print methods that can accept null (one more is println(object)).
Since null can fit in both, the compiler doesn't know which method to use, leading to a compiler error.
The compiler tries to find the most specific version of an overloaded method. Both char[] and String are sub types of Object, so that's why the third method is not considered.


Why compile-time error?


The duty of compiler is to type-check the parameters to the method call. So because of ambiguity, the compiler error.


Possible Method over-loaders that accepts null -


1. public void println(String x) {}
2. public void println(char[] x) {}
3. public void println(Object x) {}
 

How to resolve?

If you replace the statement System.out.println(null); with any one of the following statements, the code works.
System.out.println((String)null);
System.out.println((Object)null);
 

Why not System.out.println((char [])null)?


you will receive the following runtime exception.

Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:110)
at java.io.PrintStream.write(PrintStream.java:453)
at java.io.PrintStream.print(PrintStream.java:603)
at java.io.PrintStream.println(PrintStream.java:742)
at com.org.s20150309105710441.MyClass.main(MyClass.java:5)
 


Why Null Pointer Exception?


According to Java documentation,
char will not handle null pointer which leads to null pointer exception. Thus println(char[] s) prints the array of characters when s is not a null pointer.

Why println(String s) and println(Object obj) works?


According to Java documentation,
both String and Object handles null pointer.
println(String s) - If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding.

println(Object obj) - The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding.


valueOf(Object obj) -


public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

 If argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.


Summary -

Thus char always leads to a null pointer exception when it encounters a null pointer reference.

Try -


public class PrintNull {
 public static void main(String[] args) {
  Object o = null;
  String s = null;
  char[] a = null;

  //System.out.println(null); // Compilation error
  System.out.println(o); // Prints "null"
  System.out.println(s); // Prints "null"
  System.out.println(a); // Throws NullPointerException
 }
 

Please share your thoughts on this post in the comments section.

Friday, 6 March 2015

SIMD in .NET

Welcome to Logically Proven blog.

This post demonstrates SIMD vector type.

What is SIMD?

SIMD stands for "Single Instruction, Multiple Data". It is a set of processor instructions that operate over vectors instead of scalars. This allows mathematical operations to execute over a set of values in parallel.

In other words, a single instruction which performs multiple operations on the data parallely.


SIMD is a technology that enables data parallelization at the CPU level.

Difference between Multi-threading and SIMD?

You might be thinking why we need SIMD when we achieve the data parallelization with multi-threading.

While multi-threading is certainly a critical part, it is important to realize that it is still important to optimize the code that runs on a single core.

Multi-threading allows parallelizing work over multiple cores while SIMD allows parallelizing work within a single core.

Hope you got answer to your question.

The next generation JIT compiler RyuJIT for .NET supports SIMD functionality.

Why do I care?

The following statistics will answer this question.

SIMD offers a significant speed-up for certain kind of applications. For example, the performance of rendering Mandelbrot (complex mathematical operations) can be improved a lot by using SIMD.

It improves up to 3 times using SSE2 capable hardware and up to 5 times using AVX (Advanced Vector Extensionscapable hardware.

SSE2 and AVX are extensions to the instruction set architecture for microprocessors from INTEL.
Click on the provided links to know more about these extensions.


Sample Code

Consider you need to increment a set of floating point numbers by a given value.
Normally, you had to write a for loop to perform this operation sequentially as shown below -

float[] values = GetValues();
float increment = GetIncrement();

// Perform increment operation as manual loop:
for (int i = 0; i < values.Length; i++)
{
    values[i] += increment;
}

SIMD allows adding multiple values simultaneously by using CPU specific instructions. This is often exposed as a vector operation:

Vector<float> values = GetValues();
Vector<float> increment = GetIncrement();

// Perform addition as a vector operation:
Vector<float> result = values + increment;


Note that there is no single SIMD specification. Rather, each processor has a specific implementation of SIMD. They differ by the number of elements that can be operated on as well as by the set of available operations. The most commonly used implementation of SIMD on Intel/AMD hardware is SSE2.

SIMD at the CPU level

1. There  are SIMD-specific CPU registers. They have a fixed size. For SSE2, the size is 128 bits.

2. The processor has SIMD-specific instructions, specific to the operand size. As far as the processor is concerned, a SIMD value is just a bunch of bits. However, a developer wants to treat those bits as a vector of, say, 32-bit integer values. For this purpose, the processor has instructions that are specific to the operation, for example consider the operand type is addition, thus 32-bit integers.

Usage

The SIMD operations are very useful in graphical and gaming applications.

Use when
  • The applications are very computation-intensive.
  • Most of the data structures are already represented as vectors.

However, SIMD is applicable to any application type that performs numerical operations on a large set of values; this also includes complex, scientific computing and finance.

How to Install?

3 steps -
  1. Download compiler.
  2. Set Environment variables.
  3. Add a reference in your project to NuGet package Microsoft.Bcl.Simd
Compiler

Download and install the latest preview of RyuJIT from http://aka.ms/RyuJIT

NuGet package

The SIMD APIs are available via NuGet package - Microsoft.Bcl.Simd

Set Environment Variables

To enable the new JIT and SIMD, we need to set some environment variables. The easiest way to do is creating a batch file that starts your application.

@echo off
set COMPLUS_AltJit=*
set COMPLUS_FeatureSIMD=1
start myapp.exe

Limitations

  • SIMD is only enabled for 64-bit processes.
  • The vector type only supports int, long, float and double.
  • Currently SIMD is taking advantage of SSE2 hardware. AVX is not supported.

SIMD Example

The example contains how to leverage SIMD from C#. Check this link from MSDN for the detailed explanation - SIMD Example from MSDN


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Ref: Thanks to MSDN

Thursday, 5 March 2015

ASP.Net vNext - A Completely New Version




This post demonstrates PROS and CONS of the ASP.Net vNext, a completely new version of ASP.Net. There is some super exciting stuff going on in the .NET community right now. I'm going to post a few entries on my favourites.


ASP.Net vNext -


This ASP version is so awesome. It is currently under development. It combines technologies like ASP.NET MVC and Web API into a single programming model and will be cross platform.
The framework will be called ASP.NET 5 when it gets ready.


PROS -


1. It is an open source. that's right. it is on github. Go make a contribution! - Github-vNext  

2. It is totally unbound to IIS, so you can host it pretty much anywhere .net can run. Since Mono allows dotnet to run pretty much anywhere, ASP can run pretty much anywhere. like on a Mac in the console, on your Linux server, on your netduino, raspi, your grandma's old 386 in the basement she refuses to throw away.  

3. It is highly customizable and extensible with dependency injection as a first class concept so you and add and remove features and functionality as you see fit.  

4. Runtime, in memory compilation, with the Roslyn compiler means way faster start-ups. Check this link for more details on the compiler - Roslyn compiler  

5. The project system is changing, dramatically so there is a learning curve here, but IMO it is much better in the long run as it promises to ease many of the pain points of the csproj files.

 6. The new project system is also likely going to be a blacklisted project system. so you must EXCLUDE files you don't care about rather than INCLUDE all the files you do. This will make merges much cleaner.  

7. Everything is based on the best data interchange format ever! json config files* and json project files and json package manifests.  

8. An entirely new "environment" or "host" aware configuration system allows you to read config settings from multiple providers like your project-local config files, host-global files, environment variables, databases, web services, etc. you can pretty much just implement your own config provider and read from anywhere.  

9. Supports Raspberry Pi which relates to the field of embedded systems.


CONS -


1. Suppose we got to learn how to do it and that is a learning curve but it looks like a not to steep of one.

 2. ASP web forms are not supported in vNext (they are too strongly tied to the System.Web). These are my favourites. Land on the github to know your favourites.


Please share your thoughts on this post in the comments section.

Tuesday, 3 March 2015

How to suppress "Save Changes" prompt when the excel workbook is closed - VBA

Welcome to Logically Proven blog.

This post demonstrates how to suppress "Save Changes" prompt when you close the excel workbook using VBA (Visual Basic for Applications).

Note - This code works only when macros are enabled.

Sometimes it is required to suppress "Save Changes" Prompt in your excel application. It will be so annoying every time when you try to close the workbook the prompt appears.


Let get into the details.

When you suppress the prompt, you have the following two choices to decide -

1. Save the changes and Close the workbook
2. Close the workbook without saving the changes

We are achieving this functionality in the Workbook_BeforeClose() event. This event triggers by the excel application when you close the excel workbook.

Save the changes and Close the workbook:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    If Application.Workbooks.Count = 1 Then
        Application.DisplayAlerts = False
        ThisWorkbook.Save
        Application.Quit
    Else
        ThisWorkbook.Close savechanges:=True
    End If
 
End Sub

In this code, if open workbooks count is one, we are saving the workbook and quitting the excel application. If open workbooks count is more than one we are saving the currently working excel workbook and closing the workbook. The other excel workbooks remains open.

Close the workbook without saving the changes:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    If Application.Workbooks.Count = 1 Then
        Application.DisplayAlerts = False
        Application.Quit
    Else
        ThisWorkbook.Close savechanges:=False
    End If
 
End Sub

This code quits the excel application if open workbooks count is one. Else it closes only the current working excel workbook without saving the changes.

In this event, you can perform some other tasks before closing your excel application. For example clearing data, setting default values etc.

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

 
biz.