CoderGenie Blog

Where knowledge has no dimensions

Debugging unnecessary code?

clock September 26, 2009 19:13 by author Genie

If are debugging through a class/library you've gone through many many times. You know it works, it's solid. So stop wasting time going through it. Place a

[System.Diagnostics.DebuggerStepThrough()] for C#
or
<System.Diagnostics.DebuggerStepThrough()> for VB.NET

This attribute tells Visual Studio to skip the class while debugging through code.



When returning DataReader from a function, specify CommandBehavior.CloseConnection

clock September 26, 2009 19:04 by author Genie

When you create an ADO.NET DataReader object, specify the CommandBehavior.CloseConnection enumeration in your call to ExecuteReader. This ensures that when you close the DataReader, the SQL connection is also closed. This is especially helpful when you return a DataReader from a function, and you do not have control over the calling code. If the caller forgets to close the connection but closes the reader, both are closed when the DataReader is created by using CommandBehavior.CloseConnection.

ChEeRs!!!



Debug by using "Attach to Process"

clock September 26, 2009 19:03 by author Genie

Most ASP.NET developers use the standard F5 (Debug/Start Debugging) to start debugging from Visual Studio. However, there is a much faster way to start debugging if you already have an instance of your web application running. Just attach to it instead:

 * Choose Debug/Attach to Process.
 * Select the "aspnet_wp.exe" process and choose Attach.

 Keyboard Shortcut: * ALT+D, P, "as", Enter.

Debugging this way is faster because you skip the often-lengthy compilation step, and you don't have to navigate from the start page to the actual page that you want to debug

Genie!!!



Use BETWEEN instead of IN

clock September 21, 2009 20:11 by author Genie

The BETWEEN keyword is very useful for filtering out values in a specific range. It is much faster than typing each value in the range into an IN. 

Example: 
While at OUAC I built a small webpage that displayed all possible degrees and their information. Each degree belonged to a grouped category. In the database the category numbers where in a specific range. So I was able to benefit from using a BETWEEN instead having each value inside an IN.


Check the performance with the below mentioned queries....

Before: SELECT col FROM tbl WHERE col IN (508858, 508859, 508860, 508861,508862) 
After: SELECT col FROM tbl WHERE col BETWEEN 508858 and 508862

Genie!!!



Use EXISTS instead of LEFT JOIN

clock August 22, 2009 18:44 by author Genie

The LEFT JOIN merges the outer query with the inner query and keeps the extra rows from the outer table. The same result can be obtained by using an EXISTS sub query. The will eliminate the need to compare two tables as the inner query acts as a filter when the outer query executes. 

Example: While creating a tool that modified the help pages dynamically at OUAC, I needed to find which Universities had help files associated with them. By using an EXISTS sub query instead of LEFT JOIN, I increased the efficiency of this query by avoiding a table comparison.
Before: 
SELECT merfnbr, mestname FROM buma.merchant LEFT JOIN buma.helpfiles ON merfnbr=hemenbr 
After: 
SELECT merfnbr, mestname FROM buma.merchant 
WHERE EXISTS (SELECT * FROM buma.helpfiles where merfnbr = hemenbr)



Speed testing in .NET - System.Diagnostics.Stopwatch

clock August 1, 2009 09:17 by author Genie

System.Diagnostics.Stopwatch is a replacement for what most people probably do to identify the time spent on excecuting a method. The process usually goes something like: create a DateTime.Now value at the start and then subtract the ending DateTime.Now to get the TimeDuration value that elapsed. 

As an alternative, the Stopwatch class was built using low-level API calls, with less overhead than other .NET methods. If the hardware and Windows version of the computer support a high-resolution performance counter, it will use this counter instead of the standard PC clock. 

Here is a simple example: 

 

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

watch.Start();

 

//do my stuff

...

watch.Stop();

MessageBox.Show("Time spent: " + watch.Elapsed.ToString());



Access Master Page Controls from Content Pages without using FindControl

clock July 20, 2009 22:44 by author Genie

Assume in the master page, we have a user control which we need to access and set its visiblity from content page. We create a public property in the master page called controlVisiblity

public bool LoginControlVisible { 
get{ return LoginControl.Visible;}
set{  LoginControl.Visible = value;}
}

To gain access to the master page file from the content page, you just need to add the below directive to the content page
'<'% @ MasterType VirtualPath=”~/siteMaster.master” %'>'
When
ASP.NET realizes the existance of this directive, it generates a strongly typed property “Master”. this property will give you access to the MasterPage file. So directly in the content page code behind you would use the below instead of trying to use the FindControl method.

Master.LoginControlVisible = true;
or
Master.LoginControlVisible = false;
ChEeRs!!!


SecurityPermission Class in .NET

clock July 14, 2009 09:57 by author Genie

Securitypermission Perm = new Securitypermission (SecurityPermissionFlag.UnmanagedCode);

Perm.deny();

Perm.Assert();

This class is used to check whether you have permissions to execute an unmanaged code or not. If you don’t have permissions then you need to provide the application with necessary permissions otherwise this will throw an error.

This procedure is called the declarative security code writing.

[SecurityPermission(SecurityAction.Assert, Flags =

       SecurityPermissionFlag.UnmanagedCode)]

Public void execUnmanagedCode()

{

      // the code goes here./….. this is another method to execute the code.

}



Use Column Names Instead of * in a SELECT Statement

clock July 11, 2009 06:03 by author Genie


Use Column Names Instead of * in a SELECT Statement. If you are selecting only a few columns from a table there is no need to use SELECT *. Though this is easier to write, it will cost more time for the database to complete the query. By selecting only the columns you need, you are reducing the size of the result table and in turn increasing the speed of the query. Example: While creating a tool that modified the help pages dynamically at OUAC, I needed to get eachfile's information from the database. By replacing the * in my query with the columnnames, I increased the speed of the query.

Before: SELECT * FROM buma.helpfiles
After: SELECT heshnbr, hemenbr, hename,
hetitle, hecontent, hefield1, hefield2
FROM buma.helpfiles
 
   
   



CSV into SQL Server

clock July 9, 2009 00:59 by author Genie

Private Function ImportLeadFile(ByVal projectfile As String, ByVal sLeadFile As String, ByVal DATABASE As String) As Boolean

        Dim objConn As nsSqlClient.SqlConnection

        Dim ds As New DataSet

        Dim m_strConnection As String = "server=NINEL-D246655F1;Initial Catalog=TimeControl;user id=timeuser;password=timeuser;"

 

        objConn = New nsSqlClient.SqlConnection

        objConn.ConnectionString = m_strConnection

        objConn.Open()

 

        ' Make sure the .CSV file exists:

        If File.Exists(sLeadFile) Then

            Try

                ' ------ Load the data from the .CSV file: ----------

                Dim strSQL As String

                strSQL = "Select * " & _

                       " INTO " & DATABASE & ".dbo.[List_staging] " & _

                      "FROM  OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)}; DEFAULTDIR=C:\VoicenetSQL\project\tampa\Politic\" & projectfile & "; Extensions=CSV; HDR=No;','SELECT * FROM at1008.csv') "

 

                 Dim objCommand As nsSqlClient.SqlCommand

                objCommand = New nsSqlClient.SqlCommand(strSQL, objConn)

 

                objCommand.CommandText = strSQL

                objCommand.ExecuteNonQuery()

                objConn.Close()

            Catch ex As Exception

                sResultText = sResultText & "<BR>" & ex.Message

            End Try

        End If

End Function

Genie!!!



About Vinu - Genie

I am a technology specialist with experience in wide range of technologies (.net, SQL Server, Cisco, Sun and many more). Also working as a Network Consultant for many companies and running my own company named CoderGenie Technologies. In my leisure time I also work as a corporate trainer on different technologies basically on .net, sql, windows servers, cisco routers and switches. Holding a CCIE in Rouing and Switching and about to attain a CCIE in Service Provider.(check out my networks blog @ http://networks.codergenie.com)

Any person interested in technical discussions at any level are welcome and can contact me at genie@codergenie.com

Sign in