Friday 25 November 2016

Good writing requires an organized, concise mind, a quality that is essential for great developers to have. To move to the front of the application queue, you may write an original blog post to showcase your writing skills and clarity of thought. Your Toptal interviewers will read your post and will incorporate it into your screening process, so make sure it is clear and professional.
Please write a post in English on your personal blog explaining why you are committed to joining Toptal. In the post, make sure you indicate your specific interest in joining the Toptal Web development community.
Please note that posts on social media are not acceptable.
To help you get started, here are a few examples of great admission posts we've received:

Monday 16 January 2012

.Net Multiple update to SQL on single call means....Pass Datatable to Store Procedure...instead of Loop...

DataAccess.vb
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Diagnostics

Public Class DataAccess
  Implements IDisposable

  'Take ConnedctionString Using dbSetting.dll File
  'Create Instant of SQL & Use it as a Connection Object
  Public strConnection As String = System.Configuration.ConfigurationSettings.AppSettings("thriftsql10AIM")
  Private da As SqlDataAdapter
  Private command As SqlCommand
  Private sqlTrans As SqlTransaction
  Private objCn As SqlConnection

  Public Enum daCommandType

    SelectCommand = 1
    InsertCommand = 2
    UpdateCommand = 3
    DeleteCommand = 4

  End Enum

  Public ReadOnly Property ReturnConnection(Optional ByVal intConType As Integer = 0)

    Get
      Dim oCn As SqlConnection
      If intConType = 0 Then
        If oCn Is Nothing Then
          oCn = New SqlConnection(strConnection)
        End If
      Else
        If oCn Is Nothing Then
          oCn = New SqlConnection(strConnection)
        End If
      End If

      oCn.Open()

      Return oCn

    End Get

  End Property
  Public Function CloseConnection(Optional ByVal intConType As Integer = 0)
    Dim oCn As SqlConnection
    If intConType = 0 Then
      If oCn Is Nothing Then
        oCn = New SqlConnection(strConnection)
      End If
    Else
      If oCn Is Nothing Then
        oCn = New SqlConnection(strConnection)
      End If
    End If

    oCn.Open()

    Return oCn

  End Function

  'Used when connection is for ThriftWeb DB & for SqlTransaction --- Creates New Object
  Public Sub New(Optional ByVal intConType As Integer = 0)
    If intConType = 0 Then
      objCn = New SqlConnection(strConnection)
    Else
      objCn = New SqlConnection(strConnection)
    End If
    objCn.Open()
  End Sub

  'Used when no Parameters are passed while Executing Store Procedure
  Public Sub New(ByVal sprocName As String, ByVal commandType As CommandType, Optional ByVal intConType As Integer = 0)

    'Use Connection Object created with dbSetting.dll
    If intConType = 0 Then
      If objCn Is Nothing Then
        objCn = New SqlConnection(strConnection)
      End If
    Else
      If objCn Is Nothing Then
        objCn = New SqlConnection(strConnection)
      End If
    End If
    command = New SqlCommand(sprocName, objCn)
    command.CommandType = commandType
    'command.CommandTimeout = 0 'command.Connection.ConnectionTimeout

    command.Connection.Open()

  End Sub

  'Used when Parameters are passed while Executing Store Procedure
  Public Sub New(ByVal sprocName As String, ByVal commandType As CommandType, ByVal parameters As SqlParameter(), Optional ByVal intConType As Integer = 0)

    'Use Connection Object created with dbSetting.dll
    If intConType = 0 Then
      If objCn Is Nothing Then
        objCn = New SqlConnection(strConnection)
      End If
    Else
      If objCn Is Nothing Then
        objCn = New SqlConnection(strConnection)
      End If
    End If
    command = New SqlCommand(sprocName, objCn)
    command.CommandType = commandType

    Dim parameter As SqlParameter
    For Each parameter In parameters
      command.Parameters.Add(parameter)
    Next
    'command.CommandTimeout = 0 'command.Connection.ConnectionTimeout

    command.Connection.Open()
  End Sub

  'Used to begin Sql Transaction
  Public Function BeginTrans() As SqlTransaction
    Try
      sqlTrans = objCn.BeginTransaction
    Catch ex As Exception
      Throw ex
    End Try
    Return sqlTrans
  End Function

  'Used to Rooback Sql Transaction
  Public Sub RollBackTrans()
    sqlTrans.Rollback()
  End Sub

  'Used to Commit Sql Transaction
  Public Sub CommitTrans()
    sqlTrans.Commit()
  End Sub

  'Used to call SP for Sql Transaction when No Parameters are passed to SP
  Public Sub SetCommand(ByVal sprocName As String, ByVal commandType As CommandType, Optional ByRef sqlTrans As SqlTransaction = Nothing)
    'ASSIGN COMMAND PROPERTIES, ASSIGN TRANSACTION, ASSIGN STORED PROCEDURE NAME
    command = New SqlCommand(sprocName, objCn)
    command.CommandType = commandType
    If Not IsNothing(sqlTrans) Then
      command.Transaction = sqlTrans
    End If
  End Sub

  'Used to call SP for Sql Transaction when Parameters are passed to SP
  Public Sub SetCommand(ByVal sprocName As String, ByVal commandType As CommandType, ByRef Parameters As SqlParameter(), Optional ByRef sqlTrans As SqlTransaction = Nothing)
    'SET COMMAND PROPERTIES, ASSIGN PARAMETERS, ASSIGN TRANSACTION, ASSIGN STORED PROCEDURE NAME
    command = New SqlCommand(sprocName, objCn)
    command.CommandType = commandType
    Dim parameter As SqlParameter
    For Each parameter In Parameters
      command.Parameters.Add(parameter)
    Next
    If Not IsNothing(sqlTrans) Then
      command.Transaction = sqlTrans
    End If
  End Sub

  Public Function runNonQuery_Int(ByRef cn As SqlConnection) As Int32
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If
    command.Connection = cn
    command.CommandTimeout = 300
    Return command.ExecuteNonQuery()

  End Function

  Public Function runNonQuery_Int() As Int32
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If
    Try
      Return command.ExecuteNonQuery()
    Catch ex As Exception
      Throw ex
    End Try
  End Function

  Public Function runScalar_Obj() As Object
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If
    Return (command.ExecuteScalar())
  End Function

  Public Function runReader_Rd() As SqlDataReader
    Dim rdr As SqlDataReader
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If
    rdr = command.ExecuteReader()
    Return rdr
  End Function

  Public Function runAdapter_Dt(ByRef cn As SqlConnection) As DataTable
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If

    command.Connection = cn

    Dim dataAdapter As SqlDataAdapter
    Dim dataTable As DataTable
    dataAdapter = New SqlDataAdapter
    dataTable = New DataTable
    dataAdapter.SelectCommand = command
    command.CommandTimeout = 300
    dataAdapter.Fill(dataTable)
    dataAdapter.Dispose()

    Return dataTable

  End Function

  Public Function runAdapter_Dt() As DataTable
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If

    Dim dataAdapter As SqlDataAdapter
    Dim dataTable As DataTable
    Try


      dataAdapter = New SqlDataAdapter
      dataTable = New DataTable
      command.CommandTimeout = 300
      dataAdapter.SelectCommand = command

      dataAdapter.Fill(dataTable)
      dataAdapter.Dispose()
    Catch ex As Exception
      Throw ex
    End Try
    Return dataTable
  End Function

  Public Function runAdapter_Ds() As DataSet
    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If
    Dim dataAdapter As SqlDataAdapter
    Dim dataSet As DataSet
    dataAdapter = New SqlDataAdapter
    dataSet = New DataSet
    dataAdapter.SelectCommand = command
    command.CommandTimeout = 300
    dataAdapter.Fill(dataSet)
    dataAdapter.Dispose()
    Return dataSet
  End Function

  Public Function runAdapater_Update(ByVal objDt As DataTable, Optional ByVal type As daCommandType = daCommandType.InsertCommand) As Int32

    If IsDBNull(command) Then
      Throw New ObjectDisposedException("Object is disposed")
    End If

    Dim da As SqlDataAdapter
    da = New SqlDataAdapter

    Select Case type

      Case daCommandType.InsertCommand
        da.InsertCommand = command
      Case daCommandType.UpdateCommand
        da.UpdateCommand = command
      Case daCommandType.DeleteCommand
        da.DeleteCommand = command
      Case daCommandType.SelectCommand
        da.SelectCommand = command
      Case Else
        da.InsertCommand = command
    End Select

    Return da.Update(objDt)

  End Function

  Public Sub Dispose() Implements System.IDisposable.Dispose
    If Not IsDBNull(command) Then
      Dim tmpsqlcon As SqlConnection
      tmpsqlcon = command.Connection
      Debug.Assert(Not IsDBNull(tmpsqlcon))

      command.Dispose()
      command = Nothing

      tmpsqlcon.Dispose()
      tmpsqlcon = Nothing

      objCn.Close()
      objCn = Nothing

    End If

  End Sub

End Class


* This source code was highlighted with Source Code Highlighter.
Pass Datatable to Store procedure:

  Public Shared Function InsertAmazonSettlementData(ByVal objDt As DataTable) As Boolean

    Dim objDa As DataAccess = Nothing
    Dim param(17) As SqlParameter
    'Dim intRetValue As Integer
    'Dim blnResult As Boolean = True
    Dim blnResult As Boolean = False
    param(0) = New SqlParameter("@idMarketplace", SqlDbType.Int)
    param(0).SourceColumn = "idMarketplace"
    param(1) = New SqlParameter("@prevSettlementDate", SqlDbType.SmallDateTime)
    param(1).SourceColumn = "prevSettlementDate"
    param(2) = New SqlParameter("@settlementDate", SqlDbType.SmallDateTime)
    param(2).SourceColumn = "settlementDate"

    param(3) = New SqlParameter("@transactionsPeriod", SqlDbType.VarChar, 255)
    param(3).SourceColumn = "transactionsPeriod"
    param(4) = New SqlParameter("@Orders_ProductCharges", SqlDbType.Money)
    param(4).SourceColumn = "Orders_ProductCharges"
    param(5) = New SqlParameter("@Orders_PromoRebates", SqlDbType.Money)
    param(5).SourceColumn = "Orders_PromoRebates"
    param(6) = New SqlParameter("@Orders_AmazonFees", SqlDbType.Money)
    param(6).SourceColumn = "Orders_AmazonFees"
    param(7) = New SqlParameter("@Orders_OtherCharges", SqlDbType.Money)
    param(7).SourceColumn = "Orders_OtherCharges"
    param(8) = New SqlParameter("@Orders_TotalBalance", SqlDbType.Money)
    param(8).SourceColumn = "Orders_TotalBalance"
    param(9) = New SqlParameter("@Refunds_ProductCharges", SqlDbType.Money)
    param(9).SourceColumn = "Refunds_ProductCharges"
    param(10) = New SqlParameter("@Refunds_PromoRebates", SqlDbType.Money)
    param(10).SourceColumn = "Refunds_PromoRebates"
    param(11) = New SqlParameter("@Refunds_AmazonFees", SqlDbType.Money)
    param(11).SourceColumn = "Refunds_AmazonFees"
    param(12) = New SqlParameter("@Refunds_OtherCharges", SqlDbType.Money)
    param(12).SourceColumn = "Refunds_OtherCharges"
    param(13) = New SqlParameter("@Refunds_TotalBalance", SqlDbType.Money)
    param(13).SourceColumn = "Refunds_TotalBalance"
    param(14) = New SqlParameter("@Other_TransactionCharges", SqlDbType.Money)
    param(14).SourceColumn = "Other_TransactionCharges"

    param(15) = New SqlParameter("@closingBalance", SqlDbType.Money)
    param(15).SourceColumn = "closingBalance"
    param(16) = New SqlParameter("@strText", SqlDbType.VarChar, 6000)
    param(16).SourceColumn = "strText"
    param(17) = New SqlParameter("@status", SqlDbType.VarChar, 50)
    param(17).SourceColumn = "status"
    'param(5) = New SqlParameter("@intRetValue", SqlDbType.Int)
    'param(5).Direction = ParameterDirection.Output

    Try
      objDa = New DataAccess("Amazon_Settlement_Insert", CommandType.StoredProcedure, param)
      objDa.runAdapater_Update(objDt, DataAccess.daCommandType.InsertCommand)
      'intRetValue = param(5).Value
      blnResult = True
    Catch ex As Exception
      blnResult = False
      'intRetValue = -1
    Finally

      If Not IsNothing(objDa) Then
        objDa.Dispose()
      End If
      objDa = Nothing

      If Not IsNothing(objDt) Then
        objDt.Dispose()
        objDt = Nothing
      End If

    End Try
    'If intRetValue = -1 Then
    '  blnResult = True
    'ElseIf intRetValue = 1 Then
    '  blnResult = False
    'End If

    Return blnResult
  End Function


* This source code was highlighted with Source Code Highlighter.

Saturday 3 December 2011

Create Dynamic Gridview

Create class under APP_Code: DynamicallyTemplatedGridViewHandler.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Data.SqlClient;

public class DynamicallyTemplatedGridViewHandler : ITemplate
{
  #region data memebers

  ListItemType ItemType;
  public string FieldName;
  public string FieldHeader;
  string InfoType;

  #endregion

  #region constructor

  /// <summary>
  ///
  /// </summary>
  /// <param name="item_type">Item/EditItem</param>
  /// <param name="field_name"></param>
  /// <param name="info_type"></param>
  public DynamicallyTemplatedGridViewHandler(ListItemType item_type, string field_name, string field_header, string info_type)
  {
    ItemType = item_type;
    FieldName = field_name;
    InfoType = info_type;
    FieldHeader = field_header;
  }

  #endregion

  #region Methods

  public void InstantiateIn(System.Web.UI.Control Container)
  {
    switch (ItemType)
    {
      case ListItemType.Header:
        Literal header_ltrl = new Literal();
        header_ltrl.Text = "<b>" + FieldHeader + "</b>";
        Container.Controls.Add(header_ltrl);
        break;
      case ListItemType.Item:
        switch (InfoType)
        {
          case "Text":
            TextBox txt = new TextBox();
            txt.ID = FieldName;
            txt.Text = String.Empty;
            txt.Attributes["onkeydown"] = "return checkNumber(event)";
            txt.Attributes["onkeyup"] = "return checkNumber(event)";
            txt.Attributes["autocomplete"] = "off";
           
            txt.DataBinding += new EventHandler(OnDataBinding);
            Container.Controls.Add(txt);
            break;
          default:
            Label field_lbl = new Label();
            field_lbl.ID = FieldName;
            field_lbl.Text = String.Empty;
            field_lbl.DataBinding += new EventHandler(OnDataBinding);
            Container.Controls.Add(field_lbl);
            break;
        }
        break;
    }

  }

  #endregion

  #region Event Handlers

  private void OnDataBinding(object sender, EventArgs e)
  {
    object bound_value_obj = null;
    Control ctrl = (Control)sender;
    IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
    bound_value_obj = DataBinder.Eval(data_item_container.DataItem, FieldName);

    switch (ItemType)
    {
      case ListItemType.Item:
        if (sender is Label)
        {
          Label field_ltrl = (Label)sender;
          field_ltrl.Text = bound_value_obj.ToString();
        }
        else if (sender is TextBox)
        {
          TextBox field_ltrl = (TextBox)sender;
          field_ltrl.Text = bound_value_obj.ToString();
        }
        break;
    }
  }

  #endregion


}
DEFAULT.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
  <script type="text/javascript">
    function checkNumber(e) {
      if (e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 13 || e.keyCode == 46 || e.keyCode == 35 || e.keyCode == 36 || e.keyCode == 37 || e.keyCode == 39)
        return true;
      if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
        return true;
      }
      else
        return false;
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
  <hr />
  <div>
    <asp:GridView ID="gvTable" runat="server" AutoGenerateColumns="False" CellPadding="4"
      CellSpacing="4">
    </asp:GridView>
  </div>
  </form>
</body>
</html>
DEFAULT.ASPX.CS
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
  #region Data members

  public DataTable dtTable = new DataTable();
 
  #endregion

  #region Events Handlers

  protected void Page_Load(object sender, EventArgs e)
  {
    PopulateDataTable();
    CreateTemplatedGridView();
  }

  public void btnSave_Click(object se, EventArgs e)
  {

  }

  #endregion

  #region Methods
  void PopulateDataTable()
  {
    if (!IsPostBack)
    {

      gvTable.Columns.Clear();

      string ServerName = "PCT37";
      string UserName = "sa";
      string Password = "tatva";
      string DatabaseName = "BakerLand";
      string TableName = "spOrders";

      SqlConnection Connection = new System.Data.SqlClient.SqlConnection("Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";User ID=" + UserName + ";Password=" + Password + "; Connect Timeout=120;");
      SqlDataAdapter adapter = new SqlDataAdapter(TableName, Connection);
      adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
      adapter.SelectCommand.Parameters.Add("odate", SqlDbType.SmallDateTime).Value = DateTime.Now;
      try
      {
        adapter.Fill(dtTable);
      }
      finally
      {
        Connection.Close();
      }

      Session["dtTable"] = dtTable;
    }
    else
    {
      dtTable = (DataTable)Session["dtTable"];
    }
  }
  void CreateTemplatedGridView()
  {
    for (int i = 0; i < dtTable.Columns.Count; i++)
    {
      TemplateField itemField = new TemplateField();
      // create HeaderTemplate
      itemField.HeaderTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Header,
        dtTable.Columns[i].ColumnName,
        GetFieldHeader(dtTable.Columns[i].ColumnName),
        dtTable.Columns[i].DataType.Name);

      if (i < 5)
      {
        // create ItemTemplate
        itemField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Item,
          dtTable.Columns[i].ColumnName,
          GetFieldHeader(dtTable.Columns[i].ColumnName),
          "");
      }
      else
      {
        // create ItemTemplate
        string itemTitle;
        string itemCode;
        itemTitle = dtTable.Columns[i].ColumnName.Split("_".ToCharArray())[0];
        itemCode = dtTable.Columns[i].ColumnName.Split("_".ToCharArray())[1];
        itemField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Item,
          dtTable.Columns[i].ColumnName,
          GetFieldHeader(dtTable.Columns[i].ColumnName),
          "Text");
      }

      // then add to tItemTmpFieldhe GridView
      gvTable.Columns.Add(itemField);
    }

    // bind and display the data    
    gvTable.DataSource = dtTable;
    gvTable.DataBind();
  }

  /// <summary>
  /// Return Item 1 from Item 1_100001
  /// </summary>
  /// <param name="strFieldName"></param>
  /// <returns></returns>
  string GetFieldHeader(string strFieldName)
  {
    int ind = strFieldName.LastIndexOf('_');
    if (ind >= 0)
      return strFieldName.Remove(ind);
    else
      return strFieldName;
  }

  /// <summary>
  /// Return Item 100001 from Item 1_100001
  /// </summary>
  /// <param name="strFieldName"></param>
  /// <returns></returns>
  string GetFieldCode(string strFieldName)
  {
    int ind = strFieldName.LastIndexOf('_');
    if (ind >= 0)
      return strFieldName.Remove(0, ind + 1);
    else
      return strFieldName;
  }

  #endregion
}

Monday 24 October 2011

How to merge Cosecutive duplicate status rows with different values in columns - Sql Server

My Current Table:

Output should be



declare @table table (
       
ProductID int, TransactionID int, Details varchar(50), Status varchar(100), 
       
StatusDate datetime, RequestDate datetime )

insert
into @table 
       
Select 1, 11101, 'Enroll', 'Received'                           , '10/2/2010', '10/01/2010' union all
       
Select 1, 11102, 'Enroll', 'Failed: Invalid Address', '10/4/2010', '10/03/2010' union all
       
Select 1, 11105, 'Update', 'Failed: Invalid Address', '10/5/2010', '10/04/2010' union all
       
Select 1, 11108, 'Update', 'Failed: Invalid Address', '10/6/2010', '10/05/2010' union all
       
Select 1, 11110, 'Update', 'Shipped' , '10/11/2010', '10/10/2010' union all
       
Select 1, 11111, 'Enroll', 'Received'                           , '9/11/2010',  '9/10/2011' union all
       
Select 1, 11113, 'Update', 'Failed: Invalid Address', '9/13/2011',  '9/12/2011' union all
       
Select 1, 11117, 'Update', 'Failed: Invalid Address', '9/14/2011',  '9/13/2011' union all
       
Select 1, 11120, 'Update', 'Shipped'                            , '9/21/2011',  '9/20/2011'
        
;With CTE As (
       
Select *, (Row_Number() over(order by ProductID, TransactionID, StatusDate desc))as RowNum
       
from @table ),
CTE2
As (
       
Select CTE.*, (case When CTE.Status = isnull((select t.Status from CTE t where t.RowNum = (CTE.RowNum + 1)), '')then 1
       
else 0 end
       
)as RowNum2
       
from CTE )Select CTE2.ProductID, CTE2.TransactionID, CTE2.Details, CTE2.Status, CTE2.StatusDate, CTE2.RequestDate
from CTE2 where RowNum2 = 0    

Insert Data in Auto Incremented column Table

--Stop Identity of table and then insert data whichever we need and again start identitiy....
SET IDENTITY_INSERT tablename ON

insert into tablename(id,name,descr)
select id,name,descr
from tablename

SET IDENTITY_INSERT tablename OFF

Monday 17 October 2011

Delete duplicate records from Table

If any time, we want to delete duplicate records from table than we can use following query:


tableName - Our SQL table name
idtablename - Autoincremented Primary Key
columnname - By which we can identify the duplicate value in Table.



DELETE tablename WHERE idtablename in(    
    SELECT idtablename FROM tablename,(
    SELECT columnname,MIN(idtablename) AS minID
    FROM  tablename
    GROUP BY columnname
    HAVING COUNT(*) >1)  c
    WHERE c.columnname = tablename.columnname  
                   AND idtablename > minID)