Saturday, August 27, 2016

How to create login Windows Form in c# windows application with database

How to create login Windows Form in c# windows application with database 



In this article, I'm gonna share about how to make login and register form with MS SQL database;

1. Flow Chart Logic
Windows form login application
1. Create a New Windows Form Application.
Create Windows Form Application
2. Add New Database (I have created a database named as MyDatabase.mdf). Add a table (named as tbl_Login). The following is the table schema for creating tbl_Login.

Table Structure

How to Create a Simple MP4 Player C# Tutorial

How to Create a Simple MP4 Player C# Tutorial

How to Create a Simple MP4 Player C# Tutorial

Building the Sample

 Audio/Video Player
  
Any audio or video files supported by the Windows Media Player can be played in my application. Therefore the first and most important one is to add the Windows Media Player COM Component to our project.
 
The following describes how to add the Windows Media Player COM Component to our Windows application:
  • Create your Windows application.
  • From the Tools Windows click Choose Items.
  • Select the COM Components Tab.
  • Search for "Windows Media Player" and click OK. 

Now you can see the Windows Media Player will be added to your Tools windows. Just drag and drop the control to your Windows Forms.
Here you can see my Audio/Video Player screen.

My Audio/video Player has the following features:
  • Load audio/video File and add to playlist.
  • Play audio/video File
  • Pause audio/video File
  • Stop audio/video File
  • Play previous Song
  • Play Next Song
  • Play First Song of Play List
  • Play Last Song of Play List
YouTube Player
To play any YouTube URL video in our Windows application we can use the Shockwave Flash Object COM Component.
  • How to add Shockwave Flash Object COM Component to our Windows application
  • Create your Windows application
  • From the Tools Windows click Choose Items
  • Select the COM Components Tab
  • Search for "Shockwave Flash Object" and click OK
You will then see the Shockwave Flash Object added to your Tools window. Just drag and drop the control to your Windows Forms. Here you can see my YouTube screen.

Note: To play the YouTube video in our Shockwave Flash Object the YouTube URL should be edited.
For example we have the YouTube URL https://www.youtube.com/watch?v=Ce_Ne5P02q0
To play this video we need to delete "watch?" from the URL and also we need to replace the "=" next to "v" as "/".
So here for example the actual URL should be edited to be like "http://www.youtube.com/v/Ce_Ne5P02q0" .
If we do not edit the URL as in the preceding then it will not play in Shockwave.
Description
Audio/Video Player Code
Load Audio and Video file to our Play List. Here using the Open File Dialog we can filter all our audio and video files. Add all the file names and paths to the String Array and bind them to the List Box. 

C#
//Load Audio or Vedio files  
        private void btnLoadFile_Click(object sender, EventArgs e) 
        { 
            Startindex = 0; 
            playnext = false; 
            OpenFileDialog opnFileDlg = new OpenFileDialog(); 
            opnFileDlg.Multiselect = true; 
            opnFileDlg.Filter = "(mp3,wav,mp4,mov,wmv,mpg,avi,3gp,flv)|*.mp3;*.wav;*.mp4;*.3gp;*.avi;*.mov;*.flv;*.wmv;*.mpg|all files|*.*";   
            if (opnFileDlg.ShowDialog() == DialogResult.OK) 
            { 
                FileName = opnFileDlg.SafeFileNames; 
                FilePath = opnFileDlg.FileNames; 
       for (int i = 0; i <= FileName.Length - 1; i++) 
                { 
                    listBox1.Items.Add(FileName[i]); 
                } 
                Startindex = 0; 
                playfile(0); 
            } 
        } 
        #endregion 
 This method will be called from First, Next, Previous, Last and from the List Box Selected Index Change event with passing the “selectedindex” value. In this method from the array check for the selected file and play using the " WindowsMediaPlayer.URL"as in the following:


C#
// To Play the player 
        public void playfile(int playlistindex) 
        { 
            if (listBox1.Items.Count <= 0) 
            { return; } 
            if (playlistindex < 0) 
            { 
                return; 
            } 
            WindowsMediaPlayer.settings.autoStart = true; 
            WindowsMediaPlayer.URL = FilePath[playlistindex]; 
            WindowsMediaPlayer.Ctlcontrols.next(); 
            WindowsMediaPlayer.Ctlcontrols.play(); 
        } 
 This is a Windows Media Player event that will be triggered whenever the player plays, pauses, stops and so on. Here I have used this method to check for the song or video file when the playing finishes or ends. If the song ends then I set the  "playnext = true". In my program I used the Timer control that checks for the "playnext = true"status and plays the next song.


C#
#region This is Windows Media Player Event which we can used to fidn the status of the player and do our actions. 
        private void WindowsMediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) 
        { 
            int statuschk = e.newState;  // here the Status return the windows Media Player status where the 8 is the Song or Vedio is completed the playing . 
 
            // Now here i check if the song is completed then i Increment to play the next song 
 
            if (statuschk == 8) 
            { 
                statuschk = e.newState; 
 
                if (Startindex == listBox1.Items.Count - 1) 
                { 
                    Startindex = 0; 
                } 
                else if (Startindex >= 0 && Startindex < listBox1.Items.Count - 1) 
                { 
                    Startindex = Startindex + 1; 
                } 
                playnext = true; 
            } 
        } 
         #endregion 
 The Windows Media Player has the methods like Play, Pause and Stop for the player. 
C#
WindowsMediaPlayer.Ctlcontrols.next(); 
 WindowsMediaPlayer.Ctlcontrols.play(); 
WindowsMediaPlayer.Ctlcontrols.Stop(); 
 YouTube Video Player: This is a simple and easy to use object. The Shockwave object has a Movie property. Here we can provide our YouTube video to play.
Here in the button click I provide the input of the TextBox to the Shockwave Flash objectmovie property.
C#
 private void btnYoutube_Click(object sender, EventArgs e) 
        { 
            ShockwaveFlash.Movie = txtUtube.Text.Trim(); 
        } 
 Using the Audio and Video Player in our Main Form
I have created the Audio and Video player as the User Control. In my project file you can find both “AudioVedioCntl.cs” and “YouTubeCntl.cs” inside the PlayerControls folder. Create the object for the user controls and add the controls to our form or Panel. In the form load I called a method “LoadPlayerControl”. To this method I passed the parameter as 0 and 1, 0 for adding and displaying the Audio Player to the panel and 1 for adding and displaying the YouTube player.


C#
private void frmMain_Load(object sender, EventArgs e) 
        { 
            LoadPlayerControl(0); 
        } 
        private void LoadPlayerControl(int playerType) 
        { 
            pnlMain.Controls.Clear(); 
 
            if (playerType == 0) 
            { 
                SHANUAudioVedioPlayListPlayer.PlayerControls.AudioVedioCntl objAudioVideo = new PlayerControls.AudioVedioCntl(); 
                pnlMain.Controls.Add(objAudioVideo); 
                objAudioVideo.Dock = DockStyle.Fill; 
            } 
            else 
            { 
                PlayerControls.YouTubeCntl objYouTube = new PlayerControls.YouTubeCntl(); 
                pnlMain.Controls.Add(objYouTube); 
                objYouTube.Dock = DockStyle.Fill; 
            } 
        } 
 Source Code Files


Code for login page in c# with sql database



Step 1
Open Visual Studio and create a new Windows Forms project.

Step 2
Make a simple form having the 2 text fields username and password and a login button.

Step 3
Now go to the menu bar, select the view option and there you can see “Server Explorer”. Just click on that and the Server Explorer will be opened.

server explorer

Step 4
Now add your connection. There you can see an option of server name. Here you need to write the name of your server, the same as in your SQL. When you provide the server name, just go to the select option, there you'll see the entire database name that you have made. You can create your new database too. 

type server name

Step 5
It'll ask for permission and click Yes.

Step 6
Now you'll be able to see your DB in your Server Explorer tab.

Step 7
Click on it. There you'll see tables. To create a new one, right-click on that and add a new table. 

add new table

Step 8
Now you need to add some data in it. To do so just follow the figure:

add data

Step 9
Now your database is created, we only need to connect it with our form. To do this open your form and double-click on the button you have made. It"ll take you to the code of that button. Here write the following code:
  1. public void button1_Click(object sender, EventArgs e)  
  2. {  
  3.    SqlConnection con = new SqlConnection(@"Data Source=USER;Initial Catalog=admin;Integrated Security=True"); // making connection   
  4.    SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE username='"+ textBox1.Text +"' AND password='"+ textBox2.Text +"'",con);  
  5.         /* in above line the program is selecting the whole data from table and the matching it with the user name and password provided by user. */  
  6.    DataTable dt = new DataTable(); //this is creating a virtual table  
  7.    sda.Fill(dt);  
  8.    if (dt.Rows[0][0].ToString() == "1")  
  9.    {  
  10.       /* I have made a new page called home page. If the user is successfully authenticated then the form will be moved to the next form */   
  11.       this.Hide();  
  12.       new home().Show();  
  13.    }  
  14.    else  
  15.    MessageBox.Show("Invalid username or password");  
  16.   
  17. }  
Step 10
Don't forget to import it's library file.
  1. using System.Data.SqlClient;  
After this just debug your code. 

library file

I hope you have gotten all this. Thank you.

Friday, August 26, 2016

Speech Recognition

Speech Recognition


Speech Recognition

Introduction

In this article, I tell you how to program speech recognition, speech to text, text to speech and speech synthesis in C# using the System.Speech library.

Image result for Speech Recognition in c#

Speech recognition in C#

To create a program with speech recognition in C#, you need to add the System.Speech library. Then, add thisusing namespace statement at the top of your code file:
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
Then, create an instance of the SpeechRecognitionEngine:
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
Then, we need to load grammars into the SpeechRecognitionEngine. If you don't do that, the speech recognizer will not recognize phrases. For example, add a grammar with the phrase "test" and we give the grammar the name "testGrammar":
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test")) { Name = "testGrammar" }); // load a grammar "test"
Or:
Grammar gr = new Grammar(new GrammarBuilder("test"));
gr.Name = "testGrammar";
_recognizer.LoadGrammar(gr);
If you don't want to give a name to the grammar, do this:
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test"))); // load a "test" grammar
Adding a name is only necessary if you want to unload a grammar in your program. To load grammars asynchronous, use the method LoadGrammarAsync. If you want to load a grammar while the recognizer is running, call the RequestRecognizerUpdate method[^] before loading the grammar, and load the grammar(s) in a RecognizerUpdateReached[^] event handler.
Then, add this event handler:
_recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
If the speech is recognized, the method _recognizer_SpeechRecognized will be invoked. So, we need to create the method. What you can do, is when the program recognized the phrase "test", that you write "The test was successful!". To do that, use this:
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
     if (e.Result.Text == "test") // e.Result.Text contains the recognized text
     {
         Console.WriteLine("The test was successful!");
     } 
} 
As you can see in the comment line, e.Result.Text contains the recognized text. That's useful if you've more then one grammar. But, the speech recognizer wasn't started. To do that, add this code after the_recognizer.SpeechRecognized += _recognizer_SpeechRecognized line:
_recognizer.SetInputToDefaultAudioDevice(); // set the input of the speech recognizer to the default audio device
_recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
Now, if we merge all methods, we get this:
static void Main(string[] args)
{
     SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
     _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test")) Name = { "testGrammar" }); // load a grammar
     _recognizer.SpeechRecognized += _recognizer_SpeechRecognized; 
     _recognizer.SetInputToDefaultAudioDevice(); // set the input of the speech recognizer to the default audio device
     _recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
} 
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
     if (e.Result.Text == "test") // e.Result.Text contains the recognized text
     {
         Console.WriteLine("The test was successful!");
     } 
} 

Image result for Speech Recognition in c#

If you run that, it will not work. The program will be ended immediately. So, we must ensure that the program does not stop before the speech recognition is completed. We need to create a ManualResetEvent(System.Threading.ManualResetEvent), with the name _completed, and if the speech recognition is completed, we will call the Set method, and then the program will end. I loaded also a "exit" grammar. If the user says "exit", we will call the Set method. Because there're two threads, the Main thread and the speech recognition thread, we can pause the Main thread until the speech recognition thread isn't completed. And after the speech recognition is completed, we dispose the speech recognition engine (can take 3 seconds time at worst, at best 50 milliseconds):
static ManualResetEvent _completed = null;
static void Main(string[] args)
{
     _completed = new ManualResetEvent(false);
     SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
     _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test")) Name = { "testGrammar" }); // load a grammar
     _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("exit")) Name = { "exitGrammar" }); // load a "exit" grammar
     _recognizer.SpeechRecognized += _recognizer_SpeechRecognized; 
     _recognizer.SetInputToDefaultAudioDevice(); // set the input of the speech recognizer to the default audio device
     _recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
     _completed.WaitOne(); // wait until speech recognition is completed
     _recognizer.Dispose(); // dispose the speech recognition engine
} 
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
     if (e.Result.Text == "test") // e.Result.Text contains the recognized text
     {
         Console.WriteLine("The test was successful!");
     } 
     else if (e.Result.Text == "exit")
     {
         _completed.Set();
     }
}
If you're programming a Windows application, you don't need to create a ManualResetEvent, because the UI thread ends only if the user closes the form.
To unload a grammar, use the method UnloadGrammar in the speech recognition engine, and to unload all grammars use the method UnloadAllGrammars. Don't forget to invoke the methodRequestRecognizerUpdate and to load the grammars in a RecognizerUpdateReached event handler if the recognizer is running.
Unloading the "test" grammar for example:
foreach (Grammar gr in _recognizer.Grammars)
{
       if (gr.Name == "testGrammar")
       {
             _recognizer.UnloadGrammar(gr);
             break;
       }
} 
  1. Create a grammar and load the grammar like this:
    Grammar testGrammar = new Grammar(new GrammarBuilder("test"));
    _recognizer.LoadGrammar(testGrammar);  
    
  2. Then, you can unload the grammar like this:
  3. _recognizer.UnloadGrammar(testGrammar);
If you unload a grammar with the second way, then you must ensure that all access modifiers are right. The first way is the easiest way, because if you use the first way, the access modifiers don't matter.

Speech rejected

If you add a SpeechRecognitionRejected event handler to the SpeechRecognitionEngine, you can show candidate phrases found by the speech recognition engine. First, add a SpeechRecognitionRejected event handler:
_recognizer.SpeechRecognitonRejected += _recognizer_SpeechRecognitionRejected;  
Then, create the _recognizer_SpeechRecognitionRejected function:
static void _recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
   if (e.Result.Alternates.Count == 0)
   {
     Console.WriteLine("Speech rejected. No candidate phrases found.");
     return;
   }
   Console.WriteLine("Speech rejected. Did you mean:");
   foreach (RecognizedPhrase r in e.Result.Alternates)
   {
    Console.WriteLine("    " + r.Text);
   }
}
This function shows all candidate phrases found by the speech recognition engine if the speech recognition was rejected.