Sunday, April 6, 2014

Love for Powershell!

This is a quick blog entry, to appreciate my love for powershell. I have been running into Low disk space on my work computer, and I wanted to fix this issue.

Powershell to the rescue!

Simple powershell command and I was able to get the files which is occupying max disk space and then go from there.

Get-ChildItem -Path C:\ -Recurse | Where-Object {$_.PSIsContainer -eq $false} | 
sort-Object -Property Length -Descending |
Select-Object -First 10 | 
Format-List -Property FullName,Length,
@{name = "SizeInMB";expression = {$_.Length / 1MB}}

I have always been a commadline guy and I really enjoy writing small useful scripts!


Thanks,
Yash

Saturday, January 11, 2014

AutoResetEvent And ManualResetEvent


AutoResetEvent and ManualResetEvent are one of the low-level Thread signaling mechanism in C#. The main reason for writing this blog entry is to differentiate between these 2 WaitHandles.

AutoResetEvent is the like the devices you see in Airport parkings, where you punch you card, and then you can get in, but as soon as you get in, entry closes. The next person has to again punch the card.
You can see from the output of the program, there are 2 Threads and both are waiting on a Set Signal. Since only 1 set signal is received, only one thread can resume the operation while the second thread continues to wait.

ManualResetEvent are like a door. Once you open the door, the door is kept open till someone closes it. So in the code below, both theads are waiting on a Set signal to resume there operation. As soon as the Set Singnal is received, both the thread resume there operations.
       
        static void Main(string[] args)
        {
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);

            Thread t1 = new Thread(() =>
            {
                Thread.Sleep(1000); for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                    if (i == 5)
                    {
                        Console.WriteLine("Waiting to be signalled -- Thread 1");
                        //manualResetEvent.WaitOne();
                        autoResetEvent.WaitOne();
                        Console.WriteLine("Signal Received, continuing -- Thread 1" );
                    }
                }
            });
            t1.Start();

            Thread t2 = new Thread(() =>
            {
                Thread.Sleep(1000); for (int i = 101; i < 120; i++)
                {
                    Console.WriteLine(i);
                    if (i == 110)
                    {
                        Console.WriteLine("Waiting to be signalled -- Thread 2");
                        //manualResetEvent.WaitOne();
                        autoResetEvent.WaitOne();
                        Console.WriteLine("Signal Received, continuing -- Thread 2");
                    }
                }
            });
            t2.Start();


            Thread.Sleep(1000);
            Console.WriteLine("In the Main function");
            Thread.Sleep(1000);
            //manualResetEvent.Set();
            autoResetEvent.Set();
            //autoResetEvent.Reset();
            Console.ReadLine();
        }

Tuesday, December 10, 2013

Saturday, September 14, 2013

LogParser and IIS Logs

Sometimes in production environment, when you are debugging some issue and you want to get something from a  IIS logs it becomes difficult to get it because you have so many machines in prod.

I use logparser and powershell together to get the results from all the machines like below. Logparser is a great tool and it pretty fast!!.

IIS Logs are stored by the Site Id. i.e if you go to the advancesSettings of a particular website, you can see a ID column. that's how the folders are arranged in IIS log directory.



$machines = @('Yash000226','Yash000227','Yash000228','Yash000229','Yash000220',
'Yash000231','Yash000232','Yash000226')

foreach ($machine in $machines)
{
$path = "\\$($machine)\d$\data\Logs\IISLogs\W3SVC1\u_ex*.log"

.\LogParser.exe -i:IISW3C -e:50 -o:CSV file:..\Query.sql?path=$($path)+url=/admin/services/configdelta.aspx -stats:off >> output.csv
 
}


Queries ::  Put the below query in a separate file.

sc -->  Server to Client
cs --> Client to Server

date  -- Date
time  -- Time
s-ip  -- Server IP Address
 cs-method -- Client to server Method
 cs-uri-stem  -- Client to server uri stem  for eg /a.aspx etc
cs-uri-query  -- Client to Server Uri query string
s-port -- server port
cs-username -- client to server username
 c-ip -- client ip address
cs(User-Agent) -- client user agent string
 sc-status -- server to client HTTP Status code
sc-substatus  -- server to client HTTP Sub status code
sc-win32-status -- server to client win32 status code
 time-taken -- timetaken to process the request

select sc-status as httpstatusCode,sc-substatus as httpSubStatusCode
from %path%
where (to_lowercase(cs-uri-stem) = to_lowercase('%url%'))
Hope it helps someone!

-Yash

Sunday, September 8, 2013

Random Stuff worth remembering

These are just something's you need to keep in mind while coming up with a SQL query and not just run for joins :)

1) While doing aggregates (SUM,COUNT,AVG), and if you are doing SQL Joins, you need to careful about getting duplicate rows.
2) Figure out the tables that will give you information, then figure out if you need joins, pay attention to inner or outer joins.
3) Pay attention to GroupBy and Ranking Functions in SQL.
4) You can use different techniques like
    a) Sub Query
    b) Correlated Subquery in the Where Clause or Select Clause
    c) Temp Table approach
    d) Derived Table approach

-------------------------------------------------------------------------------------------------------------

Triggers are an very useful feature provided by SQL Server. These can be used to great effect for Auditing purpose.  For eg : To find out who changed a certain value. In this case you can use an Trigger and insert the previous and new values in the Auditing table etc.

-------------------------------------------------------------------------------------------------------------

Performance Counter ::

When you are debugging an esoteric issue , you can take the help of Performance Counter.  Add the required set of performance counter that you need for debugging the issue for eg: Page Splits, Cache Hits, CPU usage, Memory counters and see for any unusual behaviors.

-------------------------------------------------------------------------------------------------------------

When you are doing SQL updates on a table, which is heavily used always try to do it in batches, this will help avoid SQL Deadlocks. 

Something like this might help to put it in a loop.
Declare @Some Table
(
  SomeId int
)

-- Extract the data and put it in temp table
 INSERT INTO @Jobs
Select X from Y where X.A= B

WHILE EXISTS (SELECT * FROM @Jobs)
BEGIN
 SET @SomeId = (Select top(1) SomeId from @Some)
-- Do your operations here
DELETE FROM @SomeWHERE SomeId= @SomeId
END

 --------------------------------------------------------------------------------------------------------------

 

Tuesday, June 25, 2013

Interview Questions Asked 6/24/2013

Interview 1 ::
1) Give a nine digit phone number, find the corresponding English text. Give a list of strings to choose from.

for example 134-564-3345   AGJMPJGGLM . The string created should be a valid dictionary work. Assume that you have a
function which takes a string and returns if that word exist in dictionary or not.

0 -
1 - A,B,C
2 - D,E,F
3- G,H,I
4- J,K,L
5 - M,N,O
6 - P,Q,R
7 - S,T,U
8 - V,W,X
9 - Y,Z

2) Check if a particular string is a palindrome. Don't assume a word, A sentence with spaces can be a palindrome.

Word::
level

Phrase::
Bombard a drab mob.

3) Write code to verify if the player has won the Tic-Tac-Toe game.

4) You have a 2 cubes.  6 faces.  Arrange the number from 0 to 9 on the 2 cubes in such a way, that you can form 0-31 numbers.

for eg :: Cube 1 -- 0,1,2,3,4,5
              Cube 2 -- 3,4,5,6,6,7

5) You are given 2 strings . Write a function to tell if the 2 string maintain the order or not.

APPLE  and LEAPP.

6) Write code to convert a string into a number.
     For eg  "-1242422"   ---  1242422
                 "12abc23"     --- 1223
                 "21" --- 21



 

Wednesday, March 6, 2013

Sql Server Deadlock

If your application has lot of traffic and it involves databases then you might run into Deadlock scenarios. A deadlock happens when 2 threads are holding a lock for some resource and waiting on each other to release the lock so that they can continue.

In Sql Server deadlock is handled by the SQL Server Lock monitor thread and when a deadlock occurs it decides which process to terminate based on the priority of the process.

One of the most important thing you need to do, while setting up the SQL Server is turning on the TraceFlag 1222 in the startup parameters. What this does is whenever a Deadlock occurs it will add the deadlock information in the errorlog file, which you can use to analyse why deadlock occurred.


The error log is pretty detailed and you can figure out a lot of information from that. Its like a postmortem analysis, when trying to figure of a issue in production. There is a crime scene, culprit, symptoms and victims.

As you can see from the ErrorLog above, it gives you which process is holding which resource and what type of lock it has. It gives you which Sql Statements caused the deadlocks and the sqlHandle, process Id. It is pretty self descriptive but very informative.

The picture below shows diagrammatically, same info whats there in the error logs. It has helped me a lot to create a picture whenever a deadlocks occurs so that I can figure what exactly is happening.


These are some ways you can try to handle deadlocks situations.

1) Keep the transactions small.
2) Do nibble deletes/updates/inserts i.e fews records at a time and repeating the operation.
3)Using a Retry logic and see if it succeeds the second time/third time etc.
4) Adding WAIT FOR for sometime. so that the transaction which holds the local can complete.

I love SQL Server and love thinking in terms of Sets. Still trying to learn !

Hope this helps someone

Thanks,
Yash