Wednesday, February 15, 2012

Monday, September 15, 2008

Basic trouble-shooting list :)

1. check the event log
2. google it
3. reboot
4. run iisreset
5. empty the recycle bin
6. hit ctrl+break
7. kill the aspnet worker process
8. clear temporary internet files
9. touch the config file
10. degauss the monitor
11. remove everything from the startup folder
12. "get latest" and rebuild
13. login as admin
14. run ipconfig /renew
15. check if capslock is on.
16. run a virus scan
17. download the latest CTP
18. disable and then re-enable the network interface
19. restart services (some/most/all)
20. change your password
21. unplug your router, and leave it unplugged for 10 seconds before plugging it back in
22. clear your cookies
23. add current site to your trusted zone
24. disable javascript
25. try to ping the server
26. press 'clean solution' from the context menu in the solution explorer
27. repair the installation
28. run large magnets over all hard drives
29. check the network cable
30. defrag the hard drive
31. try it in a different browser
32. run a spyware scan
33. minimize all windows and check for a modal dialog
34. ensure configuration is correct
35. see what has changed recently
36. run process monitor
37. run chkdsk /v
38. revert all checkins from anyone named 'Gazza'
39. run the windows update service
40. remove and then recreate all Bluetooth partnerships
41. do a hardware reset on your mobile device
42. decompile + monkey punch + duck slap + donkey whack
43. what would jesus do?
44. look for suitable workarounds
45. re-calibrate your Geiger counter
46. check for packet storms
47. best to rule out toxicological contamination early on
48. describe the problem in terms even a child can understand
49. apply duct tape
50. increase the timeout duration
51. increase the maximum threadpool size
52. write to your local minister or government representative
53. try using the Microsoft Online Crash Analysis to submit your crash dump bucket-id
54. disable the customer experience improvement program
55. eat liver of sacred monkey
56. import the decryption certificate to the local client certificate store
57. ensure sql server is setup for mixed mode authentication
58. bypass proxy server for local addresses
59. check the hosts file and the routing tables
60. use filemon to locate any other log files being accessed
61. check the bios
62. update the device drivers for all peripherals
63. attach a debugger, get a memory dump, look at it in a hex reader and post it to a forum
64. cleanse all user inputs
65. put a try catch around it
66. replace the batteries in your wireless mouse and keyboard
67. recompile all dll's
68. uninstall the old version, re- install the new version, apply hot fixes patches and upgrades
69. remove the case from your computer, and aim a fan at it
70. check that you haven't been blacklisted
71. run diagnostic checks on surge protection units
72. add an index
73. remove an index
74. recalculate indexes
75. ensure ftp uses passive mode
76. recalculate statistics
77. reboot in safe mode
78. check kerberos delegation
79. review query plan
80. if 'automatically detect settings' is checked/unchecked, then uncheck/check it
81. kill rogue processes in task manager
82. run memtest.exe
83. boot from your emergency repair disks
84. follow standard knoppix data recovery procedures
85. tweak-UI
86. uninstall adobe pdf reader
87. insert "Debug.WriteLine("up to line 53");" where appropriate
88. set tracelevel to verbose
89. flush buffers
90. % truss -t \!all -t open a.out
91. use cdb or windbg. add in SOS for clr issues.
92. field test any lightning protection devices
93. use a temperature gauge on all hardware components, and compare against safe operating limits from manufacturer
94. run it inside a VM
95. check the DPI.
96. search the knowledge base
97. enable javascript debugging
98. turn off friendly http error messages in IE
99. set the current culture to en-US
100. attach a multi-meter
101. roll back to your most recent backup
102. check for GC pressure
103. empty the MSI cache
104. temporarily allow popups
105. look in your spam folder
106. recompile. wait. recompile.
107. turn off windows firewall
108. run caspol and give everything full trust
109. put yourself in the shoes of the program itself. if you were the program, what would you do?
110. ask hanselman
111. try wireshark. failing that, try fiddler. what does tracert show?
112. check the blueprints and read over the uml.
113. implement the retry pattern.
114. rtfm
115. delete the bios
116. attach anti-static wrist strap on every appendage
117. it inside a faraday cage
118. insert "alert('here');" where appropriate
119. overwrite every byte in memory the standard five times as pre-scribed by nsa guidelines
120. reinstall the operating system from the original media provided by the supplier
121. add a lock statement
122. blame Irwin the intern
123. blame the guy who left last week
124. blame the ESL guy
125. blame DNS
126. add a sleep statement
127. apply a fudge factor.
128. run a spell checker over your code
129. light some candles. sacrifice chicken.
130. set all DWORD's to 0 in the registry. Then delete the registry
131. drop all databases.
132. unregister and re-register all dlls
133. reboot 3 times
134. drink own urine
135. run prime95 overnight
136. recompile the kernel
137. do the packets hop subdomains, and if so does NAS require a NAS forwarding service -- how about VLAN?
138. track down the original programmers who wrote the system, apply percussive trauma therapy.
139. uninstall java
140. underclock it
141. ignore it
142. post a request for comment on theDailyWTF
143. ask for correlating evidence that the problem even exists
144. sharpen your wooden stakes before proceeding any further
145. melt silver crucifixes onto tips of all bullets
146. fill your water bottle with holy water
147. call tech support
148. check when daylight savings begins
149. simmer ground rhino horn on a bed of whale pancreas
150. plan and enact your fire evacuation plan
151. bathe in holy water
152. increase dosage on all medications. check for interactions.
153. bury heart of an ox at midnight under crossroads on fullmoon
154. clean up your desk
155. check that pump's suction pipe is elevated above bottom of pond. (Float the inlet 18 to 24 inches below the water surface)
156. wear shoes with six inch cork soles
157. wear raincoat, goggles, breathing apparatus
158. climb into an anti static bag
159. always use a condom
160. check pressure reading on gauges number 1 and 2
161. run it through an oscilloscope
162. check your immunization schedule is up to date
163. check for seismic/tectonic activity, solar flares, tsunami, meteor showers.
164. go and get a coffee. come back and look at it with a fresh set of eyes.

Tuesday, September 2, 2008

Close Vs Dispose - Eternal discussion

If we compare to connection object, Dispose will also clear the connection, whereas Close will not. This means that if you close a connection and then open it, it will work OK, but if you dispose it and then open it, it will throw InvalidOperationException since the connection string is not initialized

I would always argue that you should call Dispose() on any object that implements IDisposable (as Microsoft Recomend) when you are through with the object. Even if it does nothing. The jit compiiler will optimize it out of the final code anyway(Because of finalizer thread who do the task). If the object contains a Close() but no Dispose() then call Close().

IL of the Dispose method of Connection Object

.method family hidebysig virtual instance void Dispose(bool disposing) cil managed
{
.maxstack 2
L_0000: ldarg.1
L_0001: brfalse.s L_0017
L_0003: ldarg.0
L_0004: ldnull
L_0005: stfld class System.Data.Common.DbConnectionOptions System.Data.SqlClient.SqlConnection::_userConnectionOptions
L_000a: ldarg.0
L_000b: ldnull
L_000c: stfld class System.Data.ProviderBase.DbConnectionPoolGroup System.Data.SqlClient.SqlConnection::_poolGroup
L_0011: ldarg.0
L_0012: callvirt instance void System.Data.Common.DbConnection::Close()
L_0017: ldarg.0
L_0018: ldarg.1
L_0019: call instance void System.Data.SqlClient.SqlConnection::DisposeMe(bool)
L_001e: ldarg.0
L_001f: ldarg.1
L_0020: call instance void [System]System.ComponentModel.Component::Dispose(bool)
L_0025: ret
}

Dispose of Connection Object (C#):

protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null; (make connection string = null)
this._poolGroup = null; (Remove connection from connection pool)
this.Close(); (Close connection)
}
this.DisposeMe(disposing); (Dispose Connection)
base.Dispose(disposing); (Dispose parent object)
}


_userConnectionOptions is effectively the processed connection string as theprovider uses it internally

A Recurrent question: Should I initialize las member (fields) and no member variables?

NO Never

Explicitly initializing class member variables and method variables actually reduces performance in .NET.
This article explores the different types of variable initialization schemes available in .NET and the performance impact of each initialization scheme. Measurements indicate that expressly initializing variables slows object initialization by 10% and slows method calls by about 20%.

In .NET, the Common Language Runtime (CLR) expressly initializes all variables as soon as they are created. Value types are initialized to 0 and reference types are initialized to null. When you expressly initialize your variables, the compiler creates code to set the value of the variables and includes that code as part of your object initialization (for classes) or method call (for methods).
The compiler is not smart enough (Microsoft, take a hint…) to discover this duplicate initialization. Granted, if you initialize a variable to a non-default value (e.g., int A = 3;) the compiler is perfectly justified in creating the extra code. When you instantiate an object (using the new keyword) or make a method call, the following sequence happens:

1. Your variables are allocated (based on instructions from the compiler).
2. The variables are initialized by the CLR.
3. The code for the object constructor or method is executed.

The problem here is: if you explicitly initialized your variables, the constructor or method code will initialize your variables again. Is this really a problem? In many cases, the double initialization is not a problem:
If the variables are static (class variables), the initialization is done once during the entire life of the process. If the class is instantiated only a few times or the method is rarely called, the extra initialization time can be safely ignored.

- But what about those objects instantiated many times in rapid succession?
- What about those methods called thousands of times?
- What is the performance impact?

Using Visual Studio .NET 2003 in "Release" mode (with the optimizer using default settings) and running on my Win2K 1.6GHz Pentium-M machine:

Creating an object and not initializing variables ~503mSec (100%)
Creating an object and initializing on definition ~557mSec (111%)
Creating an object and initializing in the constructor ~582mSec (116%)
Calling a method and not initializing local variables ~253mSec (100%)
Calling a method and initializing variables ~316mSec (125%)

Conclusions:

- If an object is heavily used (created many times a second) – don’t initialize the variables. Not initializing shaves a nice 10% off the initialization. Obviously, if you do time-consuming and lengthy initialization in the constructor – the variable initialization time will become insignificant and lost in the noise.
- For short and quick methods which are heavily used – avoid initializing local variables to default values – just trust the CLR to do it for you.

Surprisingly, initializing variables in the constructor is a little slower than initializing on definition but this may be explained by the fact that class B has an empty constructor so the constructor calling code might be eliminated by the optimizer, saving a little time.

source: http://www.codeproject.com/KB/dotnet/DontInitializeVariables.aspx

Tuesday, July 1, 2008

Dispose Pattern

C# Sample

public sealed class MyClass: IDisposable{
// Variable to track if Dispose has been called
private bool disposed = false;
// Implement the IDisposable.Dispose() method
public void Dispose(){
// Check if Dispose has already been called
if (!disposed) {
// Call the overridden Dispose method that contains common cleanup code
// Pass true to indicate that it is called from Dispose
Dispose(true);
// Prevent subsequent finalization of this object. This is not needed
// because managed and unmanaged resources have been explicitly released GC.SuppressFinalize(this);
}
}

// Implement a finalizer by using destructor style syntax
~MyClass() {
// Call the overridden Dispose method that contains common cleanup code
// Pass false to indicate the it is not called from Dispose
Dispose(false);
} // Implement the override Dispose method that will contain common
// cleanup functionality protected virtual void Dispose(bool disposing){ if(disposing){
// Dispose time code . . . }
// Finalize time code . . . }
…}


Passing true to the protected Dispose method ensures that dispose specific code is called. Passing false skips the Dispose specific code. The Dispose(bool) method can be called directly by your class or indirectly by the client.
If you reference any static variables or methods in your finalize-time Dispose code, make sure you check the Environment.HasShutdownStarted property. If your object is thread safe, be sure to take whatever locks are necessary for cleanup.
Use the HasShutdownStarted property in an object's Dispose method to determine whether the CLR is shutting down or the application domain is unloading. If that is the case, you cannot reliably access any object that has a finalization method and is referenced by a static field

protected virtual void Dispose(bool disposing){ if(disposing){ // dispose-time code . . . } // finalize-time code CloseHandle(); if(!Environment.HasShutDownStarted) { //Debug.Write or Trace.Write – static methods Debug.WriteLine("Finalizer Called"); } disposed = true;}

Visual Basic .NET sample

'Visual Basic .NET Code snippet

Public Class MyDispose
Implements IDisposable

Public Overloads Sub Dispose()
Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me) ' No need call finalizer
End Sub

Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)

If disposing Then
'Free managed resources

End If

' Free unmanaged resources

End Sub

Protected Overrides Sub Finalize()
Dispose(False)
End SubEnd Class


Common disposable resources include the following:

  • Database-related classes: SqlConnection, SqlDataReader, and SqlTransaction.
  • File-based classes: FileStream and BinaryWriter.
  • Stream-based classes: StreamReader, TextReader, TextWriter, BinaryReader, and TextWriter.
  • Network-based classes: Socket, UdpClient, and TcpClient.
  • EnterpriseServices: classes that derive from System.EnterpriseServices.ServicedComponent

Wednesday, January 30, 2008

Code Review

I usually need to have information like this at hand. This is the compilation of techniques to improve General Performance in manage code. This information belong to Microsoft Patterns and Practices and can be found in the MSDN Library. It’s good to know that every Pattern and Practices have its correspondent Checklist which is super useful to verify quickly what we have not checked yet.

http://msdn.microsoft.com/practices/topics/perfscale/default.aspx?pull=/library/en-us/dnpag/html/scalenet.asp

Design Considerations:

Design for efficient resource management.
Reduce boundary crossings.
Prefer single large assemblies rather than multiple smaller assemblies.
Factor code by logical layers.
Treat threads as a shared resource.
Design for efficient exception management.

Class Design Considerations:

Do not make classes thread safe by default.
Consider using the sealed keyword.
Consider the tradeoffs of using virtual members.
Consider using overloaded methods.
Consider overriding the Equals method for value types.
Know the cost of accessing a property.
Consider private versus public member variables.
Limit the use of volatile fields.

Garbage Collection Guidelines

Identify and analyze your application's allocation profile.
Avoid calling GC.Collect.
Consider weak references with cached data.
Prevent the promotion of short-lived objects.
Set unneeded member variables to Null before making long-running calls.
Minimize hidden allocations.
Avoid or minimize complex object graphs.
Avoid preallocating and chunking memory.
Finalize and Dispose Call Close or Dispose on objects that support it.
Use the using statement in Microsoft® C# and Try/Finally blocks in Microsoft Visual Basic®.NET to ensure Dispose is called.
Do not implement Finalize unless required.
Implement Finalize only if you hold unmanaged resources across client calls.
Move the finalization burden to the leaves of object graphs.
If you implement Finalize, implement IDisposable.
If you implement Finalize and Dispose, use the Dispose pattern.
Suppress finalization in your Dispose method.
Allow Dispose to be called multiple times.
Call Dispose on base classes and on IDisposable members.
Keep finalizer code simple to prevent blocking.
Provide thread-safe cleanup code only if your type is thread-safe.
Pinning
If you need to pin buffers, allocate them at startup.

Threading

Minimize thread creation.
Use the thread pool when you need threads.
Use a Timer to schedule periodic tasks.
Consider parallel versus synchronous tasks.
Do not use Thread.Abort to terminate other threads.
Do not use Thread.Suspend and Thread.
Resume to pause threads.
Asynchronous Calls
Consider client-side asynchronous calls for UI responsiveness.
Use asynchronous methods on the server for I/O bound operations.
Avoid asynchronous calls that do not add parallelism.

Locking and Synchronization

Determine if you need synchronization.
Determine the approach.
Determine the scope of your approach.
Acquire locks late and release them early.
Avoid locking and synchronization unless required.
Use granular locks to reduce contention.
Avoid excessive fine-grained locks.
Avoid making thread safety the default for your type.
Use the fine grained lock (C#) statement instead of Synchronized.
Avoid locking "this".
Coordinate multiple readers and single writers by using ReaderWriterLock instead of lock.
Do not lock the type of the objects to provide synchronized access.

Boxing and Unboxing

Avoid frequent boxing and unboxing overhead.
Measure boxing overhead. Use DirectCast in your Visual Basic .NET code.

Exception Management

Do not use exceptions to control application flow.
Use validation code to avoid unnecessary exceptions.
Use the finally block to ensure resources are released.
Replace Visual Basic .NET On Error Goto code with exception handling.
Do not catch exceptions that you cannot handle.
Be aware that rethrowing is expensive.
Preserve as much diagnostic information as possible in your exception handlers.
Use performance monitor to monitor common language runtime (CLR) exceptions.

Iterating and Looping

Avoid repetitive field or property access.
Optimize or avoid expensive operations within loops.
Copy frequently called code into the loop.
Consider replacing recursion with looping.
Use for instead of foreach in performance-critical code paths.

String Operations

Avoid inefficient string concatenation.
Use + when the number of appends is known.
Use StringBuilder when the number of appends is unknown.
Treat StringBuilder as an accumulator.
Use the overloaded Compare method for case-insensitive string comparisons.

Arrays

Prefer arrays to collections unless you need functionality.
Use strongly typed arrays.
Use jagged arrays instead of multidimensional arrays.

Collections

Analyze your requirements before choosing the collection type.
Initialize collections to the right size when you can.
Consider enumerating overhead.
Prefer to implement IEnumerable with optimistic concurrency. Consider boxing overhead. Consider for instead of foreach.
Implement strongly typed collections to prevent casting overhead.

Reflection and Late Binding

Prefer early binding and explicit types rather than reflection.
Avoid late binding. Avoid using System.
Object in performance critical code paths.
Enable Option Explicit and Option Strict in Visual Basic.NET.

Code Access Security

Consider SuppressUnmanagedCodeSecurity for performance-critical, trusted scenarios.
Prefer declarative demands rather than imperative demands.
Consider using link demands rather than full demands for performance - critical, trusted scenarios.

Working Set Considerations

Load only the assemblies you need.
Consider assemblies that are being loaded as side effects.
Reduce the number of application domains, and/or make assemblies shared assemblies.
Reduce the number of threads.

Native Image Generator (Ngen.exe)

Scenarios where startup time is paramount should consider Ngen.exe for their startup path. Scenarios that will benefit from the ability to share assemblies should adopt Ngen.exe.
Scenarios with limited or no sharing should not use Ngen.exe.
Do not use Ngen.exe for ASP.NET version 1.0 and 1.1. Consider Ngen.exe for ASP.NET version 2.0. Measure performance with and without Ngen.exe.
Regenerate your image when you ship new versions.
Choose an appropriate base address. Install assemblies in the GAC if you want to use NGEN to get the best performance.
A setup application for an update of a library assembly should run the 'Ngen.exe update' command.