Sunday, October 21, 2012

Oh my God - For God's sake don't miss it!

Oh my God is a recent Hindi movie I watched and have been meaning to write about it for a couple of weeks now.
OMG Oh my God poster

This is clearly the most path breaking and thought provoking movie I've seen in recent times. India is a place where most people believe in visiting temples, donating money (and/or hair!) and performing rituals to please the Gods. The movie not only questions these practices but also leaves you questioning your own faith.

The movie is not anti-religion or atheistic. On the contrary, it presents a strong opinion about the existence of God. It is probably Paresh Rawal's finest performance since Hera Pheri (2000).

The premise is unique - A shopkeeper sues "God" when an insurance company denies his claim for his broken shop during an earthquake because earthquake is classified as an "Act of God" and hence not covered in the policy. The court then summons religious powerhouses from across the country as the case is accepted and argued in court.

Mithun Chakraborty is outstanding as the evil/sissy God man. Mahesh Manjrekar is brilliant as the shyster. Akshay Kumar as "Krishna" is likable for a change. It's definitely a must see for all age groups. Go get entertained and enlightened!

Monday, July 23, 2012

The new #1 in Test cricket

Dale Steyn signals his 5 for
The South African cricket team defeated the English by an innings and 12 runs at the Oval today. And in doing so, they've certainly taken a massive stride towards that # 1 spot on the ICC test rankings. This is the first time that South Africa have won at the oval and also the first time that they've won the first test of an away series in England.

What is going to the hurt England the most is not just the defeat but the margin and manner of defeat. This is the most comprehensive victory ever in test match cricket history spanning more than 100 years.
Kevin Pieterson is cleaned up
The defeat reveals the toothlessness of the English attack on a flat and placid track. It is difficult to believe this is the same surface on which SA manged to take 20 wickets and England 2 for the cost of 637 runs. If you count the 143 run 10th wicket partnership from the last WI test match, the English bowlers have now conceded 780 runs for 3 wickets.

This can also be treated as an indication of what the English should expect when they tour India later this year. Watch out England, the number one ranking is slipping away.

Monday, June 11, 2012

Cerner Corporation Interview experience

I recently interviewed with Cerner corporation in their Innovation center in Kansas City, MO.

The interview process began with a member from the HR department contacting me through linkedin saying that she was impressed with my profile and would like to me to apply for their Software Engineer position on their website. After I submitted the online application, she contacted me for an onsite interview.
Cerner Innovation center in Kansas City, MO

I was given accommodation for a night in KC and driving mileage reimbursement in the form of a $100 pre-paid card.
The interview process consisted of 3 back to back, 40 minutes, one-on-one interviews. Some of the questions I can remember are:

Initial questions:

 Why do you want to leave you current job?
 Best thing about your current job?
 Least thing you liked about your current job?

Technical questions:

• If a user reports a bug in the application, what steps would you take?
• How would you go about designing a program for binary search?
• How would you go about coding a game of Chess or Checkers?
• What's the difference in encapsulation and inheritance?
• What is database normalization?
• Make a binary tree where the nodes are the letters in "Cerner".
• String reversal program was given and I was told to explain the output.
• Question about unit testing. How to create unit test cases.
• How will you manage the memory while programming.
• Complexity of linked list and tree insertion
• Explain the differences between searching through a linked list vs. a binary tree
• Linked List implementation

Behavorial questions:

• Describe a situation where you have had difficulty with your team members.
• Describe a scenario where you tried to troubleshoot and you succeeded.
• Describe a scenario where you tried to troubleshoot and you failed.
• Were the managers unhappy about your work anytime?
Downtown KC as seen from the Liberty Memorial

Their .NET manager called me a couple of weeks later and explained what my role would be if I were to join the company. I was given an offer the next week.

Wednesday, May 30, 2012

Qualcomm Interview experience - .NET Tools Developer

I recently interviewed with the Qualcomm QCT Software team for their .NET tools developer position in San Diego, CA.

The process started with a member of their team directly calling me and setting up a telephonic interview. The interview was about 45 minutes. The questions were mainly pertaining to ASP.NET and SQL Server. A few which I can remember are:
What are the advantages of MVC v/s Web-Forms?
Asked me to write a simple join in LINQ to SQL.
Why do we use stored procedures?
What are Jquery selectors? In what order are they looked for?
What is DB indexing?
How do you get the value of the last inserted primary key? (This one is tricky, there're 3 ways of doing this and you may get 3 different values based on the DB state.)

I asked him a bit about the team and the role of the person they're looking to hire. He was kind enough to explain the position and the project in detail.
He told me that they're basically looking for "smart" people. "We don't expect you to know everything. We are looking for someone who can come on-board and quickly learn." He then gave himself as an example and said when he'd joined, he knew only Java. And that's what he was interviewed on.
At the end of the interview he told me the HR will be contacting me for an on-site interview in San Diego, CA. The HR contacted me a week later and I scheduled the interview in another week. I was given round trip air tickets, a rental car and accommodation for two days.

I scheduled my interview on a Friday as I wanted to keep Friday evening and Saturday morning for a bit of sight seeing. Also, that way I would miss only two days at work.
One of the 40 Qualcomm buildings at their San Diego HQ

The on-site interview consisted of 6 rounds (1 HR + 5 Technical).
HR Round
The staffing specialist asked me a few basic questions about what my interests were. Why was I looking for a new job, what technologies would I be interested in and so on. She did not ask what my salary expectation was, in spite of asking my current salary. That was a bit surprising.

After the HR round, I was taken by a shuttle to their building where all the interviews were scheduled.
1st Round - .NET Architect/ Sr. Developer
He basically talked about my current project, my technology preferences and the .NET architectures I've worked with. He then asked me to code (No preference of language.) a program to find the first non-repeating character. I first gave him an O(n^2) solution. He asked if I could improve the complexity and somehow I managed to verbally tell about him an O(n) solution which was somewhat similar to the one over here (I'd not seen this until after the interviews). He was reasonably satisfied with this solution. He then escorted me to the next interviewer's office.

2nd Round - Sr. Developer (Lunch Interview)
The interviewer asked what my preferences for lunch were. I said I don't eat pork or beef, apart from that, anything is fine. To my surprise (pleasant!), he took me to an Indian restaurant near by, although he was of Korean origin. The rest of the interview was pretty informal and he talked about his role in the company, what was important for him in the job and some of the technologies he was working on. The conversation then came to Web/WCF services in .NET. I said I'd never worked with WCF before but have coded Web services. He then asked me "Why should an  ASP.NET web service never return a DataSet or DataTable?" I didn't know the answer, as I thought a web service will always return the output in XML format, so how should the output DataStructure matter? But apparently, Python won't accept it if the web service is returning a DataSet or a DataTable. I will need to dig further sometime to know why this is so.The interview ended when we came back to his cabin in the office and he asked to write the program to print the Binary tree using pre-order traversal.

3rd Round -  .NET Architect/ Sr. Developer
I felt this guy was the smartest of the lot. He was pretty direct about everything he said and seemed to explain his project pretty well, when I asked about it. He talked a little while about my previous work-ex and moved on to a coding problem. He asked me to code the "Buzzfizz problem" (I did not know what this was at that point, but he was okay with explaining it.) and then some modification of the Fibonacci program code. He then asked about the advantages and downsides of C#. The interview ended with some questions about OOAD (Class diagrams mainly).

4th Round - .NET Lead
He took about 10 minutes to get to the interview but was polite enough to apologize for the delay. He started off with some basic .NET OO questions about interfaces, abstract classes and so on. He then moved on to some coding questions:
1. Write a program to find the number missing if you have been given 1-n numbers and you know just one in between them is missing.
2. Given two arrays with one number missing in one of them and not in the other, find the number. What property of integer datatype did you make use of to solve the problem?
3. Why do we need interfaces? If I knew all the functions I'm supposed to implement, why would I need  interfaces?
4. What are the advantages/disadvantages of database normalization?

5th Round -  Sr. Developer
I got the impression this interviewer was in a bad mood from the beginning. He asked me to code an n-ary tree in C#. He kept on interrupting me as I proceeded. I was pretty tired by this round and I didn't get the solution he desired. He moved on to the next question: Program to find the second greatest element in an array. I was able to tell him this verbally but did not manage to code due to my nervousness. I explained him that I was pretty tired after all the interviews and had had a pretty long flight. He was pretty cool after the interview though and said I should not worry too much. After that he escorted me to the outside of the building where the cab was waiting to take me to the building where I started.

Overall, I think the experience was really a positive one. San Diego has the most beautiful landscapes. I'd been to a beach after a really long time.
Yet another beach
Some random house by the beach

Sunday, May 13, 2012

Vicky Donor - A simple and funny take on a controversial topic

Vicky donor is a recent Hindi (Many dialogues and songs are in Punjabi, though) movie to hit the cinemas. The film centers around Vicky Arora (Ayushmaan Khurana) who is a sperm donor. The film then follows a romantic  tale of how he falls for Aashima Roy (Yami Gautam) and how his past as a sperm donor complicates the relationship.
Although the topic of sperm donation is controversial in India, the film focuses on the humorous aspect of it. Annu Kapoor plays Dr. Chadda, MBBS who runs an infertility clinic. The best part about the film is that the characters don't actually try to be funny. The humor burgeons from the subject matter.
Vicky Donor Poster
Overall, the film is refreshingly funny and it's good to see that films with small actors can be a huge success with a combination of good writing, script and acting.

Tuesday, May 8, 2012

Sorting and filtering a DataTable in VB.NET

There's no way to automatically sort a DataTable after it's populated.

A way around this is to sort the DefaultView of the DataTable (or any other DataView associated with the DataTable).

You can achieve this using the Sort property of the DataView. This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC).

myDataTable.DefaultView.Sort = "myColumnOfChoice DESC";

Works like a charm.

Filtering the contents of the DataTable:

In this function we check if a value is selected in any of the Dropdown lists  and add the value to the condition. In the last an extra condition “1=1” is added so that there will not be any problem is syntax even when no filter condition is selected.

Not the first entry in all DropDown lists is "All". So if that is selected we don't put any condition.

'Result is of type DataTable ans is populated and bound to a grid on Page_load

 Dim strCondition As String = ""

        If (Not ddlSrcState.SelectedIndex = 0) Then
            strCondition += "srcState='" + ddlSrcState.SelectedItem.Text + "' AND "
        End If
        If (Not ddlEquipType.SelectedIndex = 0) Then
            strCondition += " trl_type1='" + ddlEquipType.SelectedItem.Text + "' AND "
        End If
        If (Not ddlSrcCity.SelectedIndex = 0) Then
            strCondition += " srcCity = '" + ddlSrcCity.SelectedItem.Text + "' AND "
        End If
        If (Not ddlDestCity.SelectedIndex = 0) Then
            strCondition += " destCity = '" + ddlDestCity.SelectedItem.Text + "' AND "
        End If

        strCondition += "1=1"

        Result.DefaultView.RowFilter = strCondition
        Result.DefaultView.Sort = "srcState ASC"
        loadsGridView.DataSource = Result

Tuesday, April 3, 2012

Merging datasets with different schema using ASP.NET

The code for merging two dataset is as follows, it uses the merge method on the dataset (this can also be applied to datatable).

Sub BindGrid()
     Dim myConnection as New SqlConnection (strConn)

     Dim DS1 As DataSet
     Dim DS2 As DataSet
     Dim MyCommand As SqlDataAdapter

     MyCommand = new SqlDataAdapter("exec s_get_table1", MyConnection)
     DS1 = new DataSet()
     MyCommand.Fill(DS1, "MyTable")

     MyCommand = new SqlDataAdapter("exec s_get_table2", MyConnection)
     DS2 = new DataSet()
     MyCommand.Fill(DS2, "MyTable")

'Now this code works because the table name for both datasets are the same.
'Also the data type and column name for both tables are the same.

     DS1.merge(DS2 )

End Sub
What if the schema of two tables are not the same?

You get an error, which is : <target>.destination and <source>.destination have conflicting properties: DataType property mismatch.

What is the workaround for this?

You need to temporarily remove the constraints from the dataset and then merge using an overloaded version of the dataset.merge method. Below is the code:

        'we can merge the mismatched columns
        DS2 .EnforceConstraints = False
        DS2.Merge(DS1 , True, MissingSchemaAction.Ignore)
        DS2 .EnforceConstraints = True

Here is an explaination of the overloaded merge method. We chose to ignore the missing schema action so the datatypes of the souce and destination column can be slightly different.

Tuesday, March 27, 2012

Exporting an ASP.NET gridview to PDF and CSV formats

You will need to download and add a reference to the iTextSharp dll in your ASP.NET application.
Here query1Gridview is the Gridview that I want to export to PDF. The assumption is that the gridview is already provided the datasource before you're ready to export.

Response.ContentType = "application/pdf"

        Response.AddHeader("content-disposition", _
        Dim m As New MemoryStream
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        query1GridView.AllowPaging = False
        Dim dtNow As DateTime
        dtNow = Now()
        Dim todaysDate = dtNow.ToLongDateString
        Dim sr As New StringReader(sw.ToString())

        Dim header As String
        header = "YOUR HEADER" + Environment.NewLine
        Dim c As Chunk = New Chunk(header & vbLf, FontFactory.GetFont("Verdana", 15))
        Dim p As New Paragraph()
        p.Alignment = Element.ALIGN_CENTER

        Dim c1 As Chunk = New Chunk("ADD YOUR QUERY TEXT" + Environment.NewLine & vbLf, FontFactory.GetFont("Verdana", 15))
        Dim p1 As New Paragraph()
        p1.Alignment = Element.ALIGN_CENTER

        Dim c2 As Chunk = New Chunk(todaysDate + Environment.NewLine & vbLf, FontFactory.GetFont("Times New Roman", 12))
        Dim p2 As New Paragraph()
        p2.Alignment = Element.ALIGN_RIGHT

        Dim logo As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Server.MapPath("~\Images\YOURLOGO.jpg"))
        logo.Alignment = Element.ALIGN_LEFT
        logo.Alignment = iTextSharp.text.Image.TEXTWRAP

        Dim pdfDoc As New Document(PageSize.A3, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        Catch ex As Exception
            MessageBox("Unable to create pdf")
        End Try

For exporting to CSV use the below code:


        Response.Buffer = True

        Response.AddHeader("content-disposition", "attachment;filename=YOURFILENAME.csv")
        Response.Charset = ""
        Response.ContentType = "application/text"
        query1GridView.AllowPaging = False

        Dim sb As New StringBuilder()

        For k As Integer = 0 To query1GridView.Columns.Count - 1

            sb.Append(query1GridView.Columns(k).HeaderText + ","c)

        sb.Append(vbCr & vbLf)
        For i As Integer = 0 To query1GridView.Rows.Count - 1

            For k As Integer = 0 To query1GridView.Columns.Count - 1

                'add separator

                sb.Append(query1GridView.Rows(i).Cells(k).Text + ","c)

            sb.Append(vbCr & vbLf)


Monday, March 26, 2012

Autocomplete using VB.NET and AJAX

For using the Autocomplete extender using AJAX and VB.NET you need to create a webservice (.asmx) first. Below is the code for the webservice I'm using to get the autocomplete strings. The webservice uses a SQL statement to get the results. The statement has the "like" clause which matches the first letter and gets all the strings that are supersets of the string entered.

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class AutoComplete
    Inherits System.Web.Services.WebService

<WebMethod()> _
   Public Function GetProducts(ByVal prefixText As String, _
                                 ByVal count As Integer) As String()

        Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLServer2008DBConnectionString").ToString())
        Dim myCommand As New SqlCommand()
        myCommand.Connection = cn
        myCommand.CommandText = "Select ac_id from dbo.tblAccountCarrier where ac_id like '" & prefixText & "%'"
        Dim Results As New ArrayList
            Using Command As New SqlCommand(myCommand.CommandText, cn)
                Using dr As SqlDataReader = myCommand.ExecuteReader()

                    Dim Counter As Integer
                    While dr.Read
                        If (Counter = count) Then Exit While
                        Counter += 1
                    End While
                End Using
                Dim ResultsArray(Results.Count - 1) As String
                ResultsArray = Results.ToArray(GetType(System.String))
                Return ResultsArray
            End Using
        Catch ex As Exception
            Throw ex
        End Try
    End Function

The second part is using the autocomplete AJAX extender in the .aspx page. You need to register the AJAXtoolkit at the top of the page using this tag:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

In the Autocomplete tag you need to specify the  ServicePath which is a path to the above webs service and ServiceMethod which is the name of the web method created in the class.

In the .aspx page

<asp:TextBox ID="acct_idTextBox" runat="server"></asp:TextBox>
                    <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServicePath="~/AutoComplete.asmx"
                       ServiceMethod ="GetProducts" MinimumPrefixLength="1" TargetControlID="acct_idTextBox">

Thursday, March 22, 2012

Importing data from Excel spreadsheet into SQL Server database using VB.NET

I was just asked to do this at my work and here's the code that did the trick for me.
This uses the new SqlBulkCopy class in ASP.NET 2.0 which lets you easily copy bulk amounts of data from one source to another.

The function that does the SQL bulk import is as follows
Protected Sub SqlBulkCopyImport(ByVal dtExcel As DataTable)
Using conn As New SqlConnection(YOURCONNECTIONSTRING)
' Open the connection. 

Using bulkCopy As New SqlBulkCopy(conn)
' Specify the destination table name. 

bulkCopy.DestinationTableName = "dbo.tblImportRG"
' System.Data.IDataReader()

' For Each dc As DataColumn In dtExcel.Columns
' Because the number of the test Excel columns is not  
' equal to the number of table columns, we need to map  
' columns. 
'Here we manually add the mappings from Excel file (First paratmeter) to SQL table (Second parameter)

bulkCopy.ColumnMappings.Add("id", "NWCarrierID")
bulkCopy.ColumnMappings.Add("acct_master_id", "acct_master_id")
'....And so on

' Next

' Write from the source to the destination. 
End Using
End Using
End sub
This function can be called from another function as follows:

Protected Function RetrieveData(ByVal strConn As String) As DataTable
Dim dtExcel As New DataTable()

Using conn As New OleDbConnection(strConn)
' Initialize an OleDbDataAdapter object.
Dim da As New OleDbDataAdapter("select * from [Sheet1$]", conn)

' Fill the DataTable with data from the Excel spreadsheet.

End Using
Return dtExcel
End Function

Protected Sub btnImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnImport.Click
If importFileUpload.HasFile Then
' Get the name of the Excel spreadsheet to upload.
Dim strFileName As String = Server.HtmlEncode(importFileUpload.FileName)

' Get the extension of the Excel spreadsheet.
_strExtension = Path.GetExtension(strFileName)

' Validate the file extension.
If _strExtension <> ".xls" AndAlso _strExtension <> ".xlsx" Then
'Tell the user to upload an excel file.
End If

' Generate the file name to save.
_strUploadFileName = "~/Library/UploadFiles/" & DateTime.Now.ToString("yyyyMMddHHmmss") & _strExtension

' Save the Excel spreadsheet on server.

' Generate the connection string for Excel file.
Dim strExcelConn As String = ""

' There is no column name In a Excel spreadsheet.
' So we specify "HDR=YES" in the connection string to use
' the values in the first row as column names.
If _strExtension = ".xls" Then
' Excel 97-2003
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(_strUploadFileName) & ";Extended Properties='Excel 8.0;HDR=YES;'"
strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath(_strUploadFileName) & ";Extended Properties='Excel 12.0 Xml;HDR=YES;'"
End If

Dim dtExcel As DataTable = RetrieveData(strExcelConn)

' Get the row counts before importing.


' Get the row counts after importing.

' Display the number of imported rows.
lblMessages.Text = Convert.ToString(GetRowCounts()) & " rows were imported into tblImportRG table"
btnSaveTariff.Visible = True

End If

End If

End Sub
Here GetRowCounts() is a simple function that returns the number of rows in the table.

Wednesday, March 21, 2012

Internet service in Des Moines

In today's world Internet has become a basic necessity. A recent survey in the US showed that teenagers would rather prefer Internet over food!

After having moved into my new apartment, I was looking for Internet service providers in the Des Moines area. And as it turns out there're just two of them who provide high speed broadband internet services - Qwest (Centurylink) and Mediacom. After comparing the two I decided to go with Centurylink as I was told they have a better customer service.

So far it has been a good experience with them - no interruption in internet and customer service that is willing to help out with all kinds of issues whether technical or billing. Currently they're also offering a promotional discount where you can get any speed (1.5 Mbps - 40 Mbps) for a flat $25. This discount is valid only for the first six months though, after which regular rates apply. Also, if you're a Verizon wireless customer like me, you'll be getting an additional $10 discount on the bill. A great value deal!

Monday, March 19, 2012

Kahaani - 4.5 out of 5

Kahaani is the latest Hindi move that I saw after "The dirty picture". Coincidentally, both movies being female- centric with Vidya Balan playing the lead protagonist. It is definitely not your regular Bollywood masala film but more on the lines of a Hollywood psychological thriller.

The film begins with the pretext of a pregnant Vidya Bagchi (Vidya Balan) coming to Kolkata from London in search of her missing husband. The film then follows many twists during it's 114 minutes and turns on it's head in the last ten minutes of the climax.

The things to watch out of are: Vidya Balan's tremendous acting, the portrayal of Kolkata and weather you're able to unlock the mystery before the climax.

Life in Des Moines, IA

I recently moved to Des Moines, IA for a job after having stayed in New Jersey for more than a year. While it's only been a little more than a month since I've moved, for the past few days I'm really missing the Indian restaurants of NJ (The Dosa Grill on Route 27 in particular! My God, their Sambhar is the best I've ever had, and that includes those that I've tasted in Mumbai, Kerala, Karnataka and Tamil Nadu).

While moving out of a certain place after having resided there for a fair amount of time does have it's own inertia associated with it, it does come with the possibility of exploring new places. Having said that, Des Moines, although the capital of the US state of Iowa, is only about 80 Sq miles including suburbs. To put that bluntly, if you were to stand in the middle of the city and walk about 10 miles in any direction you'd end up in the middle of nowhere! The city however, is surrounded by four other major US cities - Chicago to the East, Kansas City to the South, Omaha to the West and Minneapolis to the North. I'm definitely planning to visit a couple of these in the near future.

In the process of settling into the new town, I've rented my own studio apartment (Which costs about half of what you would pay if you were in New Jersey). I've also met a few Indian origin people in the city which is always good and am cooking my own Indian food.

PS - If you're ever in Des Moines, IA be sure to visit the Iowa State Capitol, the Des Moines Downtown and the Botanical center here.