Good Unit Testing

Good Unit Tests

  1. One unit test should be independent (means its execution or variables should not be
    dependent on any other unit test)

2. Code coverage of testing code should be above 80% (which is considered good)
3. Unit Test should as simple as there is no confusion of correctness of unit test code
4. Execution of unit test should be fast and generate accurate results

5. Should cover one code path (or condition) of a function (or method) at a time

6. Unit test name should be unique and show the function of that particle unit test
7. There should be a separate project of writing unit tests.

8. Parent classes should be tested first and then the child classes.

9. We should use mocks, for write unit tests of such functionalities which take longer time or
ambiguous.

10. Test Driven Development (TDD) should be followed while writing unit tests

11. Unit Tests project should be maintainable and well organized (in object oriented
perspective),

FASTEST WAY TO FIND DISTANCE BETWEEN TWO LAT LONG POINTS

DECLARE @MaxDistance SMALLINT = 1;
	DECLARE @Latitude DECIMAL(18,15) = -6.17686;
	DECLARE @Longitude DECIMAL(18,15) = 106.64901;
	DECLARE @Jarak geography;
	DECLARE @Source geography = geography::Point(@Latitude, @Longitude, 4326);
	


	DECLARE @lng_min float
	DECLARE @lng_max float
	DECLARE @lat_min float
	DECLARE @lat_max float
	DECLARE @iKm int 
	declare @iMiles int 
	
	set @iKm = 111 
	select @iMiles = 69
	
--https://stackoverflow.com/questions/1006654/fastest-way-to-find-distance-between-two-lat-long-points
set @lng_min = @longitude - @MaxDistance/abs(cos(radians(@latitude))*@iKm);
set @lng_max = @longitude + @MaxDistance/abs(cos(radians(@latitude))*@iKm);
set @lat_min = @latitude - (CAST(@MaxDistance as float)/CAST(@iKm as float));
set @lat_max = @latitude + (CAST(@MaxDistance as float)/CAST(@iKm as float));

select @lat_max lat_max, @lat_min lat_min, @lng_max lng_max,  @lng_min lng_min, (CAST(@MaxDistance as float)/CAST(@iKm as float)) MaxDistance
	SELECT O.OutletID, O.NamaOutlet, O.AlamatOutlet, O.ChannelCode, O.NamaChannel
	FROM
		(SELECT KodeOutlet OutletID, 
			Outlet NamaOutlet,
			Alamat AlamatOutlet,
			IdJenisChannel ChannelCode,
			NamaJenisChannel NamaChannel,
			@Source.STDistance(geography::Point(Latitude, Longitude, 4326)) / 1000 as Jarak
		FROM m_OutletSpreading with (nolock)
		WHERE Longitude is not null
			ANd Latitude is not null			
AND (longitude BETWEEN @lng_min AND @lng_max)
AND (latitude BETWEEN @lat_min and @lat_max)
			) O
	WHERE Jarak <= @MaxDistance
	ORDER BY Jarak ASC

jQuery DataTable Server Side Pagination

Original post about this case is at here

 public class WebServiceDataTable : System.Web.Services.WebService  
    {  
            [WebMethod]  
            public void GetDataForDataTable()  
            {  
                HttpContext context = HttpContext.Current;  
                context.Response.ContentType = "text/plain";  
                //List of Column shown in the Table (user for finding the name of column on Sorting)  
                List<string> columns = new List<string>();  
                columns.Add("FullName");  
                columns.Add("PhoneNumber");  
                columns.Add("FaxNumber");  
                columns.Add("EmailAddress");  
                //This is used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables  
                Int32 ajaxDraw = Convert.ToInt32(context.Request.Form["draw"]);  
                //OffsetValue  
                Int32 OffsetValue = Convert.ToInt32(context.Request.Form["start"]);  
                //No of Records shown per page  
                Int32 PagingSize = Convert.ToInt32(context.Request.Form["length"]);  
                //Getting value from the seatch TextBox  
                string searchby = context.Request.Form["search[value]"];  
                //Index of the Column on which Sorting needs to perform  
                string sortColumn = context.Request.Form["order[0][column]"];  
                //Finding the column name from the list based upon the column Index  
                sortColumn = columns[Convert.ToInt32(sortColumn)];  
                //Sorting Direction  
                string sortDirection = context.Request.Form["order[0][dir]"];  
                //Get the Data from the Database  
                DBLayer objDBLayer = new DBLayer();  
                DataTable dt = objDBLayer.GetData(sortColumn,sortDirection, OffsetValue, PagingSize, searchby);  
                Int32 recordTotal = 0;  
                List<People> peoples = new List<People>();  
                //Binding the Data from datatable to the List  
                if (dt != null)  
                {  
                    for (int i = 0; i < dt.Rows.Count; i++)  
                    {  
                        People people = new People();  
                        people.ID = Convert.IsDBNull(dt.Rows[i]["ID"]) ? default(int) : Convert.ToInt32(dt.Rows[i]["ID"]);  
                        people.FullName = Convert.IsDBNull(dt.Rows[i]["FullName"]) ? default(string) : Convert.ToString(dt.Rows[i]["FullName"]);  
                        people.PhoneNumber = Convert.IsDBNull(dt.Rows[i]["PhoneNumber"]) ? default(string) : Convert.ToString(dt.Rows[i]["PhoneNumber"]);  
                        people.FaxNumber = Convert.IsDBNull(dt.Rows[i]["FaxNumber"]) ? default(string) : Convert.ToString(dt.Rows[i]["FaxNumber"]);  
                        people.EmailAddress = Convert.IsDBNull(dt.Rows[i]["EmailAddress"]) ? default(string) : Convert.ToString(dt.Rows[i]["EmailAddress"]);  
                        peoples.Add(people);  
                    }  
                    recordTotal = dt.Rows.Count > 0 ? Convert.ToInt32(dt.Rows[0]["FilterTotalCount"]) : 0;  
                }  
                Int32 recordFiltered = recordTotal;  
                DataTableResponse objDataTableResponse = new DataTableResponse()  
                {  
                    draw = ajaxDraw,  
                    recordsFiltered = recordTotal,  
                    recordsTotal = recordTotal,  
                    data = peoples  
                };  
                //writing the response           context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(objDataTableResponse));  
            }  
    }  

I think this is the important information about jQuery DataTable, how can jQuery DataTable send info the cuurent condition of component UI. And the information sent, used to filter and paginate data from SQL database, usually.

//This is used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables  
                Int32 ajaxDraw = Convert.ToInt32(context.Request.Form["draw"]);  
                //OffsetValue  
                Int32 OffsetValue = Convert.ToInt32(context.Request.Form["start"]);  
                //No of Records shown per page  
                Int32 PagingSize = Convert.ToInt32(context.Request.Form["length"]);  
                //Getting value from the seatch TextBox  
                string searchby = context.Request.Form["search[value]"];  
                //Index of the Column on which Sorting needs to perform  
                string sortColumn = context.Request.Form["order[0][column]"];  
                //Finding the column name from the list based upon the column Index  
                sortColumn = columns[Convert.ToInt32(sortColumn)];  
                //Sorting Direction  
                string sortDirection = context.Request.Form["order[0][dir]"];  

C# Cleaning up unmanaged resources

We should use IDisposable interface. Read : this, and this stackoverflow post is related with this topic.

For unmanaged resource, should use Finalizer

class First
{
    ~First()
    {
        System.Diagnostics.Trace.WriteLine("First's finalizer is called.");
    }
}

class Second : First
{
    ~Second()
    {
        System.Diagnostics.Trace.WriteLine("Second's finalizer is called.");
    }
}

class Third : Second
{
    ~Third()
    {
        System.Diagnostics.Trace.WriteLine("Third's finalizer is called.");
    }
}

/* 
Test with code like the following:
    Third t = new Third();
    t = null;

When objects are finalized, the output would be:
Third's finalizer is called.
Second's finalizer is called.
First's finalizer is called.
*/

Find Queries Taking Most CPU (Processor)

If your box is CPU bound then this is the script you need. The first query will order the results based on the queries that have used the most CPU time since the SQL Server instance has been restarted (or the server has been rebooted). The second query orders the results based upon the average CPU time that each query takes.



-- Find queries that take the most CPU overall
SELECT TOP 30 ObjectName = OBJECT_SCHEMA_NAME(qt.objectid, dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)
	,TextData = qt.TEXT
	,DiskReads = qs.total_physical_reads -- The worst reads, disk reads
	,MemoryReads = qs.total_logical_reads --Logical Reads are memory reads
	,Executions = qs.execution_count
	,TotalCPUTime = qs.total_worker_time
	,AverageCPUTime = qs.total_worker_time / qs.execution_count
	,DiskWaitAndCPUTime = qs.total_elapsed_time
	,MemoryWrites = qs.max_logical_writes
	,DateCached = qs.creation_time
	,DatabaseName = DB_Name(qt.dbid)
	,LastExecutionTime = qs.last_execution_time
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
ORDER BY qs.total_worker_time DESC




-- Find queries that have the highest average CPU usage
SELECT TOP 30 ObjectName = OBJECT_SCHEMA_NAME(qt.objectid, dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)
	,TextData = qt.TEXT
	,DiskReads = qs.total_physical_reads -- The worst reads, disk reads
	,MemoryReads = qs.total_logical_reads --Logical Reads are memory reads
	,Executions = qs.execution_count
	,TotalCPUTime = qs.total_worker_time
	,AverageCPUTime = qs.total_worker_time / qs.execution_count
	,DiskWaitAndCPUTime = qs.total_elapsed_time
	,MemoryWrites = qs.max_logical_writes
	,DateCached = qs.creation_time
	,DatabaseName = DB_Name(qt.dbid)
	,LastExecutionTime = qs.last_execution_time
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
ORDER BY qs.total_worker_time / qs.execution_count DESC


Source