QR code for my blog

Hi there!

Check out the new QR code for my blog!

qr code
Posted in General | Leave a comment

Selecting all unique rows from duplicate rows in table in SQL Server

Hi,

This post will show how you can write a select query to select only unique rows from a table that has many duplicate rows. In other words, this post will show the query to select distinct rows from a table that has duplicate rows.

Let’s say we have a table duplicated_table that has the following rows.

Initial Table
ID Name Email Age
1 Amogh amogh@example.com 24
1 Amogh amogh@example.com 24
2 Uday uday@example.com 23
2 Uday uday@example.com 23
3 Pati pati@example.com 24
3 Pati pati@example.com 24
3 Pati pati@example.com 24
and so on

Now, we can see that all the rows are repeated at least once and we need the output as shown below:

Expected Output
ID Name Email Age
1 Amogh amogh@example.com 24
2 Uday uday@example.com 23
3 Pati pati@example.com 24
and so on — Only unique rows will appear here — no duplicates

First thing to observe here is that there is no unique column in the table. So we need something to uniquely identify the column in the duplicated table. For this, we can use the ROW_NUMBER() function of SQL server. ROW_NUMBER() returns a unique row number for the current row.

So now, the logic that we can use for our purpose is:

  1. Create a data source that will select all the required data that is grouped together by a column, along with a row number to each row
  2. From this dynamically created data source, select those columns that are required but with a row number of “1″

It is important to understand point number 2 above. The output of point number 1 will be as shown below:

Table with Row Numbers
Row Number ID Name Email Age
1 1 Amogh amogh@example.com 24
2 1 Amogh amogh@example.com 24
1 2 Uday uday@example.com 23
2 2 Uday uday@example.com 23
1 3 Pati pati@example.com 24
2 3 Pati pati@example.com 24
3 3 Pati pati@example.com 24
and so on

The above table will be the output of the first point mentioned above. That is, create a data source that selects all the data along with the row number. Observe the “Row Number” column in the above table. Though the table has duplicate rows, each duplicate row has a unique row number.

Now, the only thing left to do is to select those rows from the above table that have row number = 1. And you will end up with the desired output.

Now let’s see the queries for both the steps.

For step – 1: Create a data source that selects all the data along with row number.

;with dataSrc as 
( 
     select ROW_NUMBER() over(partition by Name order by Name) as RowNum,
     ID, Name, email, age from duplicated_table 
)

For step – 2: Selecting those rows with row number = 1;

select Id, Name, email, age from dataSrc where RowNum = 1;

Final Complete Query :

;with dataSrc as 
( 
    select ROW_NUMBER() over(partition by Name order by Name) as RowNum,
    ID, Name, email, age from duplicated_table 
) 
select Id, Name, email, age from dataSrc where RowNum = 1;

Hope this helps!

Posted in SQL Server | Tagged , , , , , , , , , , , , | Leave a comment

Restricting to only one running instance of an application in C#

Hi,

We all must have observed some time or the other that when you try to open an application that is already running, you get a pop up that says, “Another instance of the same application is already running” or something like that.

This post will show how you can implement that in your windows application using C#.

The main class used here is the Process class that is a part of System.Diagnostics namespace. Process class provides access to some local and also remote processes and can be used to start/stop these processes. Some static methods provided by Process class are GetCurrentProcess() and GetProcessesByName(string process_name).

These methods pretty much do exactly what they are named.

  • GetCurrentProcess() basically gets a Process component and links it to the current running process from which this method was called. That means that if we call this method from our app (which is what we’ll do shortly), the method returns a Process component that is linked to our app’s process.
  • GetProcessesByName(string process_name) returns an array of Process components that are currently running in the local system with the specified process name, process_name. So for example, if you have chrome browser running with multiple tabs open, then you can see in Task Manager that there are as many number of “Chrome.exe” processes running as there are tabs in your browser. Now if you call this method for “Chrome.exe”, you will get an array of Process components each having all the details of one chrome.exe process each.

NOTE : It is very important to note here that these methods simply GET the already existing and running instances of the processes. They DO NOT create new instances of Process class. Note the words “gets/returns” in the above bullet points.

So to implement this functionality, all you need to do is before you create a new instance of your application, get all the running processes and check the names of those processes with the currently running process. If you find such a process, it means that there is an instance already running and you should not create another instance for the same application. If not, just create a new instance for the application.

Check the below code. I have created a Windows Forms application with a very basic form with a label. In the Program.cs file, I have created a static method that performs the above mentioned check and returns either true or false based on whether it finds a process with the same name or not.

[STAThread]
 static void Main()
 {
     if (AnotherInstanceExists())
     {
           MessageBox.Show("You cannot run more than one instance of this application.", "Only one instance allowed to run", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
           
           return;
     }

     Form1 objMyForm = new Form1();
     objMyForm.ShowDialog();
 }
public static bool AnotherInstanceExists()
{
    Process currentRunningProcess = Process.GetCurrentProcess();
    Process[] listOfProcs = Process.GetProcessesByName(currentRunningProcess.ProcessName);
 
    foreach (Process proc in listOfProcs)
    {
       if ((proc.MainModule.FileName == currentRunningProcess.MainModule.FileName) && (proc.Id != currentRunningProcess.Id))
               return true;
    }
    return false;
 }

The method AnotherInstanceExists() initially makes a call to GetCurrentProcess() to get a Process component associated with the currently running process. Then it makes a call to GetProcessesByName() and passes the currently running process’s name as parameter. With the array of Process components that are returned from this method, it checks whether the current process ID and process module’s filename are the same. Basically it checks whether both these processes are same or not.

If the method returns true, the user is shown an error message that only one instance can be running for this application.

That’s all there is to do.

Hope this helps!

Posted in .NET, C#, General | Tagged , , , , , , , , , , , , , , , , , | Leave a comment

State Management using Cookies.

What are Cookies?

Cookies are nothing but a small piece of information that are stored at the client’s browser by the server. This small piece of information about the user is then sent by the browser in all subsequent requests to the same URL in the request. We can store anything in a cookie; General example of cookie usages are to store the user preferences, password remembering, storing user options, etc.

Generally cookies are stored a plain text files in the local disk of the user. Cookies can be accessed from anywhere in the application. Generally Cookies are lost after the user closes the browser but we can also have cookies that will persist even after browser is closed.

Cookies are mainly classified into two types:

  1. persistant
  2. non-persistant.

Persistant cookies:

As the name itself suggests, these cookies remain persistant in the client’s memory even after the browser is closed. They remain permanently in memory till they are explicitly removed or their expiration is reached.

Non-persistant cookies: These cookies do not remain in the client’s memory and are lost after browser is closed.

How to create cookies from code:

Generally we use the HttpCookie class to create an instance of a cookie for that session, then add the values that we want to be included in the cookie as key-value pairs. The below code explains this more clearly.

HttpCookie userCookie = new HttpCookie("infoCookie");
userCookie["username"] = "Amogh";
userCookie["City"] = "Hyderabad";
userCookie["Country"] = "India";

//adding the cookie to the Response object. This will be sent to the client on first request from the client.
Response.Cookies.Add(userCookie);

The example shown above is that of a NON-persistent cookie as it doesn’t specify any expiration time for the cookie. If we add an expiration to the cookie object, the cookie will become a persistent cookie. Example code is shown below.

HttpCookie userCookie = new HttpCookie("infoCookie"); 
userCookie["username"] = "Amogh";
userCookie["City"] = "Hyderabad";
userCookie["Country"] = "India";

//adding an expiration to the cookie
userCookie.Expires = DateTime.Now.AddDays(1);

//adding the cookie to the Response object. This will be sent to  the client on first request from the client.

Response.Cookies.Add(userCookie);

The “Expires” property of the HttpCookie object specifies that the cookie will expire after 1 day of its creation.

Reading values from cookie: Values from cookie can be read directly by using the Request object of the current HttpContext.

HttpCookie infoCookie = Request.Cookies["infoCookie"];
string city = infoCookie["City"];

Advantages of Cookies :

  1. Very easy to use.
  2. Browser takes care of sending and maintaining cookies from multiple sites

Disadvantages of cookies:

  1. Not secure as data is stored as plain text
  2. cookie size is limited to 4KB
  3. Some browsers may not support cookies. So care needs to be taken while using cookies in code.

Hope this helps!!

Posted in .NET, ASP.NET, C#, General | Tagged , , , , , , , , , , , , , , | Leave a comment

Genesis Take Two: The Birth of Geekdom — #Copied

1. In the beginning GOD created the Bit and the Byte. And from those he created the Word.

2. And there were two Bytes in the Word; and nothing else existed. And God separated the One from the Zero; and he saw it was good.

3. And God said – Let the Data be; And so it happened. And God said – Let the Data go to their proper places. And he created floppy disks and hard disks and compact disks.

4. And God said – Let the computers be, so there would be a place to put floppy disks and hard disks and compact disks. Thus God created computers and called them hardware.

5. And there was no Software yet. But God created programs; small and big… And told them – Go and multiply yourselves and fill all the Memory.

6. And God said -I will create the Programmer; And the Programmer will make new programs and govern over the computers and programs and Data.

7. And God created the Programmer; and put him at Data Center; And God showed the Programmer the Catalog Tree and said You can use all the volumes and subvolumes but DO NOT USE Windows.

8. And God said – It is not Good for the programmer to be alone. He took a bone from the Programmer’s body and created a creature that would look up at the Programmer; and admire the Programmer; and love the things the Programmer does; And God called the creature: the User.

9. And the Programmer and the User were left under the naked DOS and it was Good.

10. But Bill was smarter than all the other creatures of God. And Bill said to the User – Did God really tell you not to run any programs ?

11. And the User answered – God told us that we can use every program and every piece of Data but told us not to run Windows or we will die.

12. And Bill said to the User – How can you talk about something you did not even try. The moment you run Windows you will become equal to God. You will be able to create anything you like by a simple click of your mouse.

13. And the User saw that the fruits of the Windows were nicer and easier to use. And the User saw that any knowledge was useless – since Windows could replace it.

14. So the User installed the Windows on his computer; and said to the Programmers that it was good.

15. And the Programmer immediately started to look for new drivers.

And God asked him – What are you looking for? And the Programmer answered – I am looking for new drivers because I can not find them in the DOS. And God said – Who told you need drivers? Did you run Windows?

And the Programmer said – It was Bill who told us to !

16. And God said to Bill – Because of what you did you will be hated by all the creatures. And the User will always be unhappy with you.

And you will always sell Windows.

17. And God said to the User – Because of what you did, the Windows will disappoint you and eat up all your Resources; and you will have to use lousy programs; and you will always rely on the Programmers help.

18. And God said to the Programmer – Because you listened to the User you will never be happy. All your programs will have errors and you will have to fix them and fix them to the end of time.

19. And God threw them out of the Data Center and locked the door and secured it with a password.

20. GENERAL PROTECTION FAULT

 

Source – Unknown (Found this on the internet)
Posted in General | Tagged | Leave a comment

[Solution]configuration system failed to initialize – C# Exception

Hi,

Today I encountered an exception while working on an application. The exception was “configuration system failed to initialize”. The problem that I was having in my application configuration file was that I declared the <appSettings> tag immediately after the root tag <configuration>.

The schema of a configuration file mandates the “<configSections>” tag to be the first child of the root tag. Thus, if you put any other tag as the first child of root <configuration> tag, the application would throw an exception. So, ALWAYS, the <configSections> tag should immediately follow root <configuration> tag.

Correct Format:

<?xml version="1.0"?>
<configuration>
   <configSections>
      <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="your_project_name.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </sectionGroup>

Wrong Format:

<?xml version="1.0"?>
<configuration>
   <appSettings>
       ...
       ...
       ...
   </appSettings>
   <configSections>
      .....
    </configSections>

This is just one of the reasons for which the exception is thrown. There are more than one reasons for it. For me, this solution worked out. Hope it works out to you as well! :)

Hope this helps!!

Posted in .NET, ASP.NET, C# | Tagged , , , , , , , , , , , , , , | Leave a comment

From Windows 1.0 to Windows 8. Check out the evolution of Windows.

From Windows 1.0 to Windows 8. Check out the evolution of Windows.

Check out the above link. It shows the evolution of Windows operating system from the initial MS-DOS days to current Metro-UI of Windows 8 OS. Today, exactly 30 years ago, windows Operating system was announced by the then Microsoft CEO, Bill Gates. The operating system was then officially released 2 years later.

Posted in General | Tagged , , , , , , , , | Leave a comment