Thursday, December 6, 2012

Checking a Stored Procedure exists or not in database


When we keep all our stored procedures creation script in a file and want to run that whole script. It always complains about already existing stored procedure having same name.
It is better before running your Stored Proc creation script, your creation script should be smart enough that always checks the presence of same name stored procedure before.
 
Following piece of SQL Script checks the stored procedure presence. If it finds, it delets the old one and create a new one having same name (of course most of the time, the new one would be modified)
When we keep all our stored procedures creation script in a file and want to run that whole script. It always complains about already existing stored procedure having same name.

It is better before running your Stored Proc creation script, your creation script should be smart enough that always checks the presence of same name stored procedure before.

Following piece of SQL Script checks the stored procedure presence. If it finds, it delets the old one and create a new one having same name (of course most of the time, the new one would be modified)

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoredProcedureName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ StoredProcedureName]
GO

Thanks,
Hemant

Tuesday, November 27, 2012

Hangman Game (Guess the Word) in C#

This word guessing game is very similar to popular word guessing game: HANGMAN
(Only difference is that here computer is not drawing "Hangman" picture on every wrong guess by the guessing player... May be in next version, I might include that diagram...)

This game is developed as a Windows Application in C#. Feel free to download the game... and  source code of this game.


 

Screen Shots:




Rules:

This game is generally played by two persons. One player has to guess a word which is given by another player. Here you have to play this game with Computer. In order to win this game, Guessing player has to guess the word correctly. In the guessing, player can not make more then five wrong guesses.
If he suggests more than five wrong letters, he loses the game.
Initially, the word to guess is represented by a row of dashes, giving the number of letters.
If the guessing player suggests a letter which occurs in the word, the other player (in this case Computer) writes it in all its correct positions.
If the suggested letter does not occur in the word, guessing player loses his guessing attempt.
The game is over when:
  • The guessing player completes the word, or guesses the whole word correctly 
  • The guessing player makes more than five wrong guesses and unable to guess the word correctl

Friday, November 23, 2012

Image Color Detector in C#


 In this article I am going to show how we can detect any particular color in an image in C#. A sample code is also attached along with this article for your reference.



 
In this “Color Detector” application, firstly we select an image (jpeg, bmp, png etc.) and then we pick the color which we want to detect on that image. If we found the color, we display a confirmation message. The snapshot for the running application is below:


Now we go to in more detail of this application:

Source of the image:  We can take mage from any source (like Digital Camera, any stored image in PC, Mobile etc.), and keep the image somewhere in our system. Image can be in any format (i.e. jpeg, bmp, png etc.)

Image Selection: For image file selection, we include an “OpenFileDialog” control into our form. On “Choose Image” button click, we show “OpenFileDialog” to choose any image file from the system. After image file selection, we get the file path and then load the image into a picture box. For the file selection and loading into a picture box, refer to following code:
   private void ChooseImageBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //Clearing previously selected image from picture box
                ImagePathLbl.Text = "";
                pictureBox1.Image = null;
 
                //Showing the File Chooser Dialog Box for Image File selection
                DialogResult IsFileChosen = openFileDialog1.ShowDialog();
 
                if (IsFileChosen == System.Windows.Forms.DialogResult.OK)
                {
                    //Get the File name
                    ImagePathLbl.Text = openFileDialog1.FileName;
 
                    //Load the image into a picture box
                    if (openFileDialog1.ValidateNames == true)
                    {
                        pictureBox1.Image = Image.FromFile(ImagePathLbl.Text);
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

Color Selection: For color selection which we want to detect in our selected image, we include an “ColorDialog” control into our form. On “Pick Color” button click, we show “ColorDialog” to choose any color from the dialog box. After color selection, we get the color name and then display the picked color into a panel by setting Panel.BackColor property to picked color. If the picked color is a known color, we also display the color name in text. For the color selection and displaying the selected color, refer to following code:

        private void PickColorBtn_Click(object sender, EventArgs e)
        {
            try
            {
                // Clean previously selected color
                SelectedColorNameLbl.Text = "";
                panelSelectedColor.BackColor = actualColor;
 
                //Showing color choice
                DialogResult IsColorChosen = colorDialog1.ShowDialog();
 
                if (IsColorChosen == System.Windows.Forms.DialogResult.OK)
                {
                    panelSelectedColor.BackColor = colorDialog1.Color;
 
                    //If it is know color, display the color name  
                    if (colorDialog1.Color.IsKnownColor == true)
                    {
                        SelectedColorNameLbl.Text = colorDialog1.Color.ToKnownColor().ToString();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

Color Detection: For color detection, firstly we convert the loaded image in picture box to a “BitMap” class. Refer to following MSDN link for more detail:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx

Then we iterate each pixel of image and get the pixel color. We store the each pixel color into a temporary variable named “now_color”. Get the 32-bit ARGB value of this “now_color” (a Color Object) with 32-bit ARGB value of our “Picked Color”. If both values are same, we display a “Color Found!” message and come out from the iteration, otherwise we keep on looking other pixel until we cover whole image. If we don’t get success in color finding, we show “Selected Color Not Found" Message. For the color detection, refer to following code:




 private void DetectColorBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Boolean IsColorFound = false;
 
                if (pictureBox1.Image != null)
                {
                    //Converting loaded image into bitmap
                    Bitmap bmp = new Bitmap(pictureBox1.Image);
 
                    //Iterate whole bitmap to findout the picked color
                    for (int i = 0; i < pictureBox1.Image.Height; i++)
                    {
                        for (int j = 0; j < pictureBox1.Image.Width; j++)
                        {
                            //Get the color at each pixel
                            Color now_color = bmp.GetPixel(j, i);
 
                            //Compare Pixel's Color ARGB property with the picked color's ARGB property 
                            if (now_color.ToArgb() == colorDialog1.Color.ToArgb())
                            {
                                IsColorFound = true;
                                MessageBox.Show("Color Found!");
                                break;
                            }
                        }
                        if (IsColorFound == true)
                        {
                            break;
                        }
                    }
 
                    if (IsColorFound == false)
                    {
                        MessageBox.Show("Selected Color Not Found.");
                    }
                }
                else
                {
                    MessageBox.Show("Image is not loaded");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

Wednesday, November 14, 2012

A Free Download Party Game !!!


I created this party game which contains currently following games:

TELL A NAME:

In this game, some alphabets and one category will be shown on the screen and you have to tell any name from that category in which
the shown alphabets would come in the same order.
For Example: Suppose shown Alphabets are "R" and "S"
and Category is "PLACE"
So correct answer could be like: PARIS (As R comes before S)
(but not SAN FRANCISCO because in this anem S comes before R)

BINGO: 

In this game, you are given a Bingo ticket and you have to cross the same number  which is displayed here on your ticket.
Generally 5 types of prizes are kept for this game:

FIRST FIVE: Whoever crossed his first five numbers
FIRST ROW: Whoever crossed all the numbers in his first row
SECOND ROW: Whoever crossed all the numbers in his second row
THIRD ROW: Whoever crossed all the numbers in his third row
FULL HOUSE: Whoever crossed all the numbers in his ticket

___________________________

  

___________________________


Monday, November 12, 2012

Debug a WCF Service (with NetTcpBinding) hosted in a Windows Service

This article shows how we can debug a WCF Service in Visual Studio which is hosted in a Windows Service with netTcpBinding.  

As we know when we create WCF Service as a class library in visual studio and run the service. We don’t need any kind of host (Like Self-Hosting App, Windows Services, IIS OR WAS) Right? It happens because fortunately Microsoft has already included a small testing service host and a test client in order to ease development and testing of WCF services. Press F5 in Visual Studio and you are set to start debugging by setting break point anywhere in the service where we want to. You would see following message when WCF service runs:

Figure-1

But suppose we host our WCF service in a Windows Service and make Windows Service as our main start up project, then it becomes difficult to debug our WCF Service because this time Windows Service is the main driving application which doesn’t allow running the WCF Service in debugger mode.

It gives the following error message if you try to do it:

Figure-2

So what is the solution?  For this problem, we have following simple remedial options:

(1)    Through Visual Studio
(2)    Through Code

(1)    Through Visual Studio: In this option (which I am not going to discuss here), you need to open your visual studio in administrative mode and you have to have your Service attached to process. For more detail, you could see MSDN article for this:
(2)    Through Code: We are going to discuss this option in detail in this article.

To explain this, I divided article into following sections:

(1)    Creating a small WCF Service  with netTcpBinding
(2)    Creating Windows Service Host
(3)    Setting Windows Service that enables debugging in Visual Studio
(4)    Creating our own Test Client

(1)            Creating a small WCF Service with netTcpBinding:


  1. On the File menu, point to New and then click Project.
  2. In the New Project dialog box, expand the Visual C# node and click WCF, followed by WCF Service Library. Click OK to open the project.
  3. An in-built WCF Service with two operation contracts (by default) is created for you by Visual Studio. You don’t need to change any operation contract/ data contract because here our focus is not to learn creating WCF Service and their contracts (operation/Data)
  4. For  netTcpBinding , we need to change the contents of the default app.Config  file as:

<configuration>
  <system.serviceModel>
    <services>
      <service name="MyWcfService.Service1">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="MyWcfService.IService1">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/Design_Time_Addresses/MyWcfService/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>


  1. That’s it! We are done with creating our Test WCF Service.

(1)            Creating Windows Service Host:


Now we create a Windows Service project in Visual Studio:
  1. On the File menu, point to New and then click Project.
  2. In the New Project dialog box, expand the Windows node and click Window Service and Click OK to open the project.
  3. A default Window service project is created.
  4. Although this step is optional right now but eventually we would ended up following this step because we want to install our Windows Service in the system. For this, we need to add project Installer into our windows service so that we could install our windows service using “regsvr32” command. In order to do that, we go to designer of Service1.cs
    • Right click in the designer of Service1.cs. Choose “Add Installer” option from the menu.
    • Visual Studio automatically creates ProjectInstallar for us.
    • Give any name to your service in the properties window of serviceInstaller1.
    • How we can install any windows service using “installutil” coomand, we could go to following MSDN link:
  1. Add the WCF Service DLL reference into Window Service project.
  2. Add System.ServiceModel reference to Windows Service
  3. Open the Service1.cs file and create WCF Service host into OnStart() method as follows
  
  public partial class Service1 : ServiceBase
    {
        ServiceHost host;
         public Service1()
        {
            InitializeComponent();
        }
         protected override void OnStart(string[] args)
        {
            Type serviceType = typeof(MyWcfService.Service1);
            host = new ServiceHost(serviceType);
 
            host.Open();
        }
         protected override void OnStop()
        {
            host.Close();
        }
    }

  1. Add a new “app.config” file into Windows Service Project.
  2. Copy the same contents of WCF service app.config (described in section1.4) into our newly added Windows Service app.config file.

(2)            Setting Windows Service that enables debugging in Visual Studio:


1.                   Open Program.cs file of the Windows Service Host Application and replace the existing Program.cs  with the following code:
·         In the following Code, We created instance of “Service1” class of the Windows Service and calling explicitly our own methods: OnDebugMode_Start() and OnDebugMode_Stop() .
·         This portion will be run only in DEBUG Mode as we used #if DEBUG directive.
·         The portion in #else block will not be run in DEBUG Mode.
·         We also put the Main Thread into Infinite time Sleep Mode in order to make “Debugging” available for all the time till we want.
Note: When we want to install this windos service using “installutil” command, we have to comment the #if DEBUG directive and its code as following:
        
 static void Main()
          {
                               System.Threading.Thread.CurrentThread.Name = "ServiceMain";
 
                               try
                               {
          //#if DEBUG
                //// Run as interactive exe in debug mode to allow easy debugging. 
                //var service = new Service1();
                //service.OnDebugMode_Start();
                //// Sleep the main thread indefinitely while the service code runs in OnStart() 
                //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
                //service.OnDebugMode_Stop();
 
          //#else
                               ServiceBase[] ServicesToRun;
                               ServicesToRun = new ServiceBase[] 
                               { 
                                         new Service1() 
                               };
                               ServiceBase.Run(ServicesToRun);
          //#endif
                               }
                               catch (Exception exc)
                               {
                                         throw exc;
                               }
 
 
          }
         

1.                   Open the Service1.cs file and Add two more public methods in the same class, which basically calls OnStart() and OnStop() methods internally:
 

 public void OnDebugMode_Start()
        {
            OnStart(null);
        }
 
        public void OnDebugMode_Stop()
        {
            OnStop();
        }
       
2.                   Press F5 to run the service and make sure service is running properly. Since Windows Service is debugger mode, so it won’t complain as in Figure-2

3.                 Creating our own Test Client:

    1. Create any WinForm Application or Console Application to be a client of our WCF Service which will consume the WCF Service.
    2. Make sure WCF Service is running.
    3. Right click the Reference tab of your project. Click “Add a ServiceReference” .
    4. Add Service Reference Window will open
    5. Put the WCF Endpoint base address (copying from app.config)into Address bar of the Window.
    6. Click Go. It must have found out our WCF Service interfaces.
    7. Click OK. In this way, you added service reference to you client project.
    8.  Create Proxy Client Object of your WCF Service as:
  ServiceReference1.Service1Client objectProxyClient = new Service1Client();
 
    1. Access interfaces of WCF Service with “objectProxyClient” object.

So, here we learned how we can easily debug a WCF Service in Visual Studio which is hosted in a Window Service by making a small Test WCF Service with netTcpBinding, Hosting Windows Service and Test Client Tool.
Thanks
Hemant Srivastava

Friday, October 26, 2012

How to get the table size in SQL server 2008


To get the table size in SQL Server 2008, we need to use a system stored procedure viz. sp_spaceused
If we pass Table Name as an argument, it gives the disk space used by the table and some other information like: Number of rows existing in the table, Total amount of reserved space for Table, Total amount of space reserved for table but not yet used, Total amount of space used by indexes in Table.








                                                                       


Example: 
For the ADDRESS table in our database, if we run

  sp_spaceused      'TADDRS'
it will give following result:

name
rows
reserved
data
index_size
unused
TADDRS
4726
392 KB
320 KB
16 KB
56 KB


               
                                               

Friday, October 19, 2012

How to Get the Selected Cells and Rows in the Windows Forms DataGridView Control


Here basically I am showing how to get selected cells/rows in DataGridView Control and use of IEnumerator while accessing them.



                DataGridViewSelectedRowCollection m = dataGrid_ZipList.SelectedRows;
                DataGridViewRow row;
 
                IEnumerator Enumerator = m.GetEnumerator();
                Enumerator.Reset();
                while (Enumerator.MoveNext())
                {
                    row = (DataGridViewRow)Enumerator.Current;
                    lstPostalCodes.Add(row.Cells["POSTAL_CODE"].Value.ToString());                   
                }

Tuesday, October 16, 2012

SQL Query to find out the frequency of each element in a column

Suppose we have a table "Person" as:

IdLastNameFirstNameAgeCity
1SmithJohn33Newyork
2SmithMike34Boston
3PaulRyan39Chicago
4WilliamBrian45Baltimore
5RaoSunita41Dayton
6ZingSue33Owings Mills
7SmithRobert45Newyork
8PaulZean33Chicago
9SrivastavaHemant33Baltimore
10RaoVenkat45Dayton


and we need to find out the frequency of the each age.


   SELECT Age, COUNT(Age)AS Frequency    
   FROM Persons   
   GROUP BY Age   
   ORDER BY    
   COUNT(Age) DESC
 

We get following result:
Age
Frequency
33
4
45
3
34
1
39
1


Now suppose we want to get the ‘Age’ which occurs more than equal to 2. For this query, we need to add HAVING clause after GROUP BY clause.



SELECT Age, COUNT(Age)AS Frequency
FROM Persons
GROUP BY Age 
HAVING  COUNT(Age) >= 2

That gives result as:
Age
Frequency
33
4
45
3