Search Results:

Wednesday, November 25, 2009

Color Tabs of a Tabcontrol using VB.NET

In order to color the tabs of the tabcontrol in vb.net

just drop a tab control on a form with DrawMode = OwnerDrawFixed and put a couple of tab pages in it

1.
Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem
2.
3.
'Firstly we'll define some parameters.
4.
Dim CurrentTab As TabPage = TabControl1.TabPages(e.Index)
5.
Dim ItemRect As Rectangle = TabControl1.GetTabRect(e.Index)
6.
Dim FillBrush As New SolidBrush(Color.Red)
7.
Dim TextBrush As New SolidBrush(Color.White)
8.
Dim sf As New StringFormat
9.
sf.Alignment = StringAlignment.Center
10.
sf.LineAlignment = StringAlignment.Center
11.
12.
'If we are currently painting the Selected TabItem we'll
13.
'change the brush colors and inflate the rectangle.
14.
If CBool(e.State And DrawItemState.Selected) Then
15.
FillBrush.Color = Color.White
16.
TextBrush.Color = Color.Red
17.
ItemRect.Inflate(2, 2)
18.
End If
19.
20.
'Set up rotation for left and right aligned tabs
21.
If TabControl1.Alignment = TabAlignment.Left Or TabControl1.Alignment = TabAlignment.Right Then
22.
Dim RotateAngle As Single = 90
23.
If TabControl1.Alignment = TabAlignment.Left Then RotateAngle = 270
24.
Dim cp As New PointF(ItemRect.Left + (ItemRect.Width \ 2), ItemRect.Top + (ItemRect.Height \ 2))
25.
e.Graphics.TranslateTransform(cp.X, cp.Y)
26.
e.Graphics.RotateTransform(RotateAngle)
27.
ItemRect = New Rectangle(-(ItemRect.Height \ 2), -(ItemRect.Width \ 2), ItemRect.Height, ItemRect.Width)
28.
End If
29.
30.
'Next we'll paint the TabItem with our Fill Brush
31.
e.Graphics.FillRectangle(FillBrush, ItemRect)
32.
33.
'Now draw the text.
34.
e.Graphics.DrawString(CurrentTab.Text, e.Font, TextBrush, RectangleF.op_Implicit(ItemRect), sf)
35.
36.
'Reset any Graphics rotation
37.
e.Graphics.ResetTransform()
38.
39.
'Finally, we should Dispose of our brushes.
40.
FillBrush.Dispose()
41.
TextBrush.Dispose()
42.
End Sub

Monday, November 16, 2009

Copy rows from one grid view to another grid view.

I haven't tried this code on my own but my friend used this code to bring this functionality, I just wanted to share so that someone might get benifitted from this code

The code is in VB.NET

If (e.Control And e.KeyCode = Keys.V) Then
Dim s As String = Clipboard.GetText()
Dim lines As String()
lines = System.Text.RegularExpressions.Regex.Split(s, Environment.NewLine)
'Dim row As Integer = dgv.CurrentCell.RowIndex
'Dim col As Integer = dgv.CurrentCell.ColumnIndex
Dim row, col As Integer
For intRow As Integer = 0 To dgv.RowCount - 1
For intCol As Integer = 0 To dgv.ColumnCount - 1
If dgv.Rows(intRow).Cells(intCol).Selected = True Then
row = intRow
col = intCol
Exit For
End If
Next
If Not (row = 0 And col = 0) Then
Exit For
End If
Next
For intNextLine As Integer = 0 To (lines.Length - 1)
If (row < dgv.RowCount And lines(intNextLine).Length > 0) Then
Dim cells As String() = System.Text.RegularExpressions.Regex.Split(lines(intNextLine), "\t")
For i As Integer = 0 To cells.Length - 1
If (col + i < dgv.ColumnCount) Then
dgv.Rows(row).Cells(col + i).Value = cells(i)
End If
Next
row = row + 1
End If
Next
End If

Wednesday, November 4, 2009

Code Sample to Combine two PDF files

How To: Combine PDFs Using InsertPages



Issue
How do I combine multiple PDFs into one PDF using Visual Basic?
Solution
This record contains VisualBasic code to demonstrate AcroExch.PDDoc InsertPages.

As far as InsertPages is concerned, the tricky part is to remember that the page number you will be inserting after is -1; in other words, you want to insert these pages before page 0, which is the first page of the document.

Private Sub Command1_Click()
Dim b As Boolean

Dim AcroPDDoc As CAcroPDDoc
Dim PDDoc As CAcroPDDoc

Set AcroPDDoc = CreateObject("AcroExch.PDDoc")
Set PDDoc = CreateObject("AcroExch.PDDoc")

b = PDDoc.Open("c:\testinsertpages.pdf")
b = AcroPDDoc.Open("c:\Tips.pdf")
b = AcroPDDoc.InsertPages(0, PDDoc, 0, 1, False)
b = AcroPDDoc.Save(1, "c:\Tips.pdf")

End Sub

Monday, November 2, 2009

Combine 2 PDF's Using vb.net

How To: Combine PDFs Using InsertPages



Issue
How do I combine multiple PDFs into one PDF using Visual Basic?
Solution
This record contains VisualBasic code to demonstrate AcroExch.PDDoc InsertPages.

As far as InsertPages is concerned, the tricky part is to remember that the page number you will be inserting after is -1; in other words, you want to insert these pages before page 0, which is the first page of the document.

Private Sub Command1_Click()
Dim b As Boolean

Dim AcroPDDoc As CAcroPDDoc
Dim PDDoc As CAcroPDDoc

Set AcroPDDoc = CreateObject("AcroExch.PDDoc")
Set PDDoc = CreateObject("AcroExch.PDDoc")

b = PDDoc.Open("c:\testinsertpages.pdf")
b = AcroPDDoc.Open("c:\Tips.pdf")
b = AcroPDDoc.InsertPages(0, PDDoc, 0, 1, False)
b = AcroPDDoc.Save(1, "c:\Tips.pdf")

End Sub

PDF Programming

A website for PDF programming help

Link is

http://www.nk-inc.com/blog/?page=2

Friday, October 16, 2009

Easily Create Loading GIF's for free

Here is a website to create a Loading GIF and save it to your desktop very easily. Give it a try ?? Click Here

A few samples below are



Another one

Wednesday, October 14, 2009

Disable Autorun of CD's,Pendrives etc

Here is the registry edit that can be done to disable the auto run feature in windows.
  1. Go to RUN type "Regedit".
  2. Go to Hkey_current_user/Software/Microsoft/windows/currentversion/policies/Explorer
  3. Add DWORD "NoDriveTypeAutoRun
  4. Edit the Value to Hexadecimal "FF"
You are set now the auto run is disabled.

Tuesday, October 6, 2009

Query to find no of multiple columns

SELECT id, COUNT(id) AS NumOccurrences
FROM Driver_History
GROUP BY id
HAVING (COUNT(id) = 2)


This above query gives all the rows that have same id's.

Monday, September 28, 2009

Connection Strings Made easy .

Visit this website for various connection strings such as to connect to Access,Excel etc...

Click Here


Once you get the connection string it is similar to any other database access. use ole db connection objects.

Friday, September 25, 2009

Get Open Dialog to browse system files

The OpenFileDialog class is defined in Windows.Forms class. You need to add to reference to System.Windows.Form.dll library and call using System.Windows.Forms before using the class.

The OpenFileDialog class can be used to open a file similar to CFileDialog 's Open method in VC++. This class is derived from FileDialog. OpenFile method of this class opens a file which can be read by a steam.

In this sample code, I have use OpenFileDialog class to browse a file.

Private fdlg As OpenFileDialog = New OpenFileDialog()
Private fdlg.Title = "C# Corner Open File Dialog"
Private fdlg.InitialDirectory = "c:\"
Private fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
Private fdlg.FilterIndex = 2
Private fdlg.RestoreDirectory = True
If fdlg.ShowDialog() = DialogResult.OK Then
textBox1.Text = fdlg.FileName
End If

Title member let you set the title of the open dialog. Filter member let you set a filter for types of files to open.

Sunday, September 13, 2009

Delete Duplicate Rows in SQL Server.

Deleting duplicate rows in SQL Server

--1.Deleting rows from a table having primary key

CREATE TABLE TEST1
( ID INT NOT NULL PRIMARY KEY
,VALUE CHAR(2)
)

INSERT INTO dbo.TEST1 SELECT '1','A' UNION ALL SELECT '2','A' UNION ALL SELECT '3','A' UNION ALL SELECT '4','B' UNION ALL SELECT '5','B' UNION ALL SELECT '6','B'

The original table with duplicates

DELETE FROM dbo.TEST1 WHERE ID NOT IN (SELECT MIN(ID) FROM dbo.TEST1 GROUP BY VALUE)

Now the resulting table with no duplicate rows

2. Deleting rows from a table without a primary key

I have a table dbo.MYDATABASE with following data---


now deleting the duplicate rows using ROW_NUMBER()


WITH TEMP_TABLE AS ( SELECT ROW_NUMBER() OVER( PARTITION BY CUSTID ORDER BY CustID ) AS ROWNUMBER,* FROM dbo.MYDATABASE )

DELETE FROM TEMP_TABLE WHERE ROWNUMBER > 1


The result looks like

Thursday, September 10, 2009

Visual Studio Debug skips the break point

The main issue i found out is the problem with the browser. (IE8)
IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes.
http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie

Older versions of the Visual Studio Debugger get confused by this and cannot figure out how to attach to the correct process. You can work around this by disabling the process growth feature of LCIE. Here's how:

1) Open RegEdit
2) Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3) Add a dword under this key called TabProcGrowth
4) Set TabProcGrowth to 0

Since you are running on Windows Server 2003, this is all you should need to do. If you run into the same problem on Vista or newer, you will also need to turn off protected mode.

Friday, September 4, 2009

Catch SMTP Exception and re-send Email.

SmtpException Class


Represents the exception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation.
Namespace: System.Net.MailAssembly: System (in System.dll)

Code Sample


public static void RetryIfBusy(string server)
{
MailAddress from = new MailAddress("ben@contoso.com");
MailAddress to = new MailAddress("jane@contoso.com");
MailMessage message = new MailMessage(from, to);
// message.Subject = "Using the SmtpClient class.";
message.Subject = "Using the SmtpClient class.";
message.Body = @"Using this feature, you can send an e-mail message from an application very easily.";
// Add a carbon copy recipient.
MailAddress copy = new MailAddress("Notifications@contoso.com");
message.CC.Add(copy);
SmtpClient client = new SmtpClient(server);
// Include credentials if the server requires them.
client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an e-mail message to {0} using the SMTP host {1}.",
to.Address, client.Host);
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
client.Send(message);
}
else
{
Console.WriteLine("Failed to deliver message to {0}",
ex.InnerExceptions[i].FailedRecipient);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
ex.ToString() );
}
}

Friday, August 28, 2009

Create datatable dynamically or during runtime

Here is the code to create a datatable and add rows to it . This is the case when you want to add certain rows to the datatable which are manipulated in the code instead of bringing directly from the database.

Please find the code below to achieve this:


Public Class Form1 Inherits System.Windows.Forms.Form

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Dim Table1 As DataTable
Table1 = New DataTable("Customers")
'creating a table named Customers
Dim Row1, Row2, Row3 As DataRow
'declaring three rows for the table
Try
Dim Name As DataColumn = New DataColumn("Name")
'declaring a column named Name
Name.DataType = System.Type.GetType("System.String")
'setting the datatype for the column
Table1.Columns.Add(Name)
'adding the column to table
Dim Product As DataColumn = New DataColumn("Product")
Product.DataType = System.Type.GetType("System.String")
Table1.Columns.Add(Product)
Dim Location As DataColumn = New DataColumn("Location")
Location.DataType = System.Type.GetType("System.String")
Table1.Columns.Add(Location)

Row1 = Table1.NewRow()
'declaring a new row
Row1.Item("Name") = "Reddy"
'filling the row with values. Item property is used to set the field value.
Row1.Item("Product") = "Notebook"
'filling the row with values. adding a product
Row1.Item("Location") = "Sydney"
'filling the row with values. adding a location
Table1.Rows.Add(Row1)
'adding the completed row to the table
Row2 = Table1.NewRow()
Row2.Item("Name") = "Bella"
Row2.Item("Product") = "Desktop"
Row2.Item("Location") = "Adelaide"
Table1.Rows.Add(Row2)
Row3 = Table1.NewRow()
Row3.Item("Name") = "Adam"
Row3.Item("Product") = "PDA"
Row3.Item("Location") = "Brisbane"
Table1.Rows.Add(Row3)
Catch
End Try

Dim ds As New DataSet()
ds = New DataSet()
'creating a dataset
ds.Tables.Add(Table1)
'adding the table to dataset
DataGrid1.SetDataBinding(ds, "Customers")
'binding the table to datagrid
End Sub

End Class

Tuesday, August 25, 2009

Add Serial Number to Datagridview

This article explains how to add a Serial Number (Row Index) Column in DataGridView control without adding this column in Physical Database or in DataSet's DataTable.




Level: Beginner

Knowledge Required:
• DataGridView
• Data Binding

Description:
We use DataGridView control alot of times in Data Manipulation application. Sometimes we require to have a Serial Number (S.No.) Column in DataGridView Control in such a way that no matter how Sorting/Filtering is done, Serial Number should remain constant i.e. in a Sequence.

One way to accomplish this is to create a Column in DataSet's DataTable in which we can store the Serial Numbers, but this will make our job too complex if sorting/filtering is also done. Because we have to re-check the Serial Number column again and again each time the Sorting/Filtering is performed.

So the better way is to use the DataGridView control's Virtual Mode. Here are the steps that we will do,

1) Bind the DataGridView control to some BindingSource and setup its Columns
2) Add another column (Unbound Column) and make it the first column
3) Set its name = ColumnSNo
4) Set its ReadOnly = True
4) Set the DataGridView control's VirtualMode property to True
5) In CellValueNeeded event use the following code:


Private Sub DataGridView1_CellValueNeeded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValueNeeded
If e.RowIndex >= 0 AndAlso e.ColumnIndex = Me.ColumnSNo.Index Then
e.Value = e.RowIndex + 1
End If
End Sub


Note that if we don't set the VirtualMode Property to True then CellValueNeeded event wouldn't fire


Summary:
To display the Serial Numbers we have added an unbound column and set the Virtual Mode Property of DataGridView control to True. Then in CellValueNeeded Event we just return the Row Index whose value is required

Friday, August 21, 2009

Crystal Report Login Code


Dim cr As New crptCurrentEmployees
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table

'Get database connection info

With crConnectionInfo
.ServerName = My.Settings.ConnectionString.Split(";")(0).Split("=")(1)
.DatabaseName = My.Settings.ConnectionString.Split(";")(1).Split("=")(1)
.UserID = My.Settings.ConnectionString.Split(";")(3).Split("=")(1)
.Password = My.Settings.ConnectionString.Split(";")(4).Split("=")(1)
End With

'Set database connection for all tables in report

CrTables = cr.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
' Loop through each section and find report objects

Dim crReportobjects As ReportObjects, crSubReportobject As SubreportObject, subReportDocument As ReportDocument
Dim crDatabase As Database
Dim crSections As Sections = cr.ReportDefinition.Sections
For Each crSection As Section In crSections
crReportobjects = crSection.ReportObjects
For Each crReportobject As ReportObject In crReportobjects
If crReportobject.Kind = ReportObjectKind.SubreportObject Then

' If a subreport is found cast as subreportobject
crSubReportobject = CType(crReportobject, SubreportObject)
' Open the sub report
subReportDocument = crSubReportobject.OpenSubreport(crSubReportobject.SubreportName)
crDatabase = subReportDocument.Database
CrTables = crDatabase.Tables
' Loop through each table in the sub report and set the connection info
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
End If
Next
Next

If Me.cboLocations.SelectedIndex < 0 Then
cr.RecordSelectionFormula = "{Employees.CustomerID} = {?clientid}"
Else
cr.RecordSelectionFormula = "{Employees.CustomerID} = {?clientid} AND {Employees.LocationID} = {?locationid}"
cr.SetParameterValue("locationid", cboLocations.SelectedValue)
End If
cr.SetParameterValue("clientid", cboCompanyName.SelectedValue)

With crptViewer
.ReportSource = cr
.Zoom(100)
.Visible = True
.Refresh()
End With

Tuesday, July 28, 2009

Details about Finalizer Thread

Not all memory leaks in .NET applications specifically relate to objects that are rooted or being referenced by rooted objects. There are other things that might produce the same behavior (memory increase) and we are going to talk about one of them.

What is the Finalizer Thread?
The finalizer thread is a specialized thread that the Common Language Runtime (CLR) creates in every process that is running .NET code. It is responsible to run the Finalize method (for the sake of simplicity, at this point, think of the finalize method as some kind of a destructor) for objects that implement it.

Who needs finalization?
Objects that needs finalization are usually objects that access unmanaged resources such as files, unmanaged memory and so on. Finalization is used to make sure these resources are closed or discarded to avoid actual memory leaks.

How does finalization works?
(NOTE: please email me if I’ve got something wrong or in accurate at this stage ;-) )

Objects that implement the finalize method, upon their creation, are being placed in a finalization queue. When no one references these objects (determined when the GC runs) they are moved to a special queue called FReachable queue (which means Finalization Reachable queue) which the finalizer thread iterates on and calls the finalize method of each of the objects there.
After the finalize method of an object is called it is read to be collected by the GC.

So how can the finalizer thread get blocked?
Finalizer thread block occurs when the finalizer thread calls to a finalize method of a certain object.
The implementation of that finalize method is dependat on a resource (its a general term for the sake of the general definition) that is blocked.
If that resource will not be freed and available for our finalize method, the finalizer thread will be blocked and none of the objects that are in the FReachable queue will get GCed.

For example:

  1. The implementation of the Finalize method contains code that requires a certain lock of a synchronization object (Critical Section, Mutex, Semaphore, etc) and that synchronization object is already blocked and is not getting freed (see previous post on Identifying Deadlocks in Managed Code for help on resolving this issue).
  2. The object that is being finalized is an Single Threaded Apratment (STA) COM object. Since STA COM objects have thread affinity, in order to call the destructor of that COM object we have to switch to the STA thread that created that object. If, for some reason, that thread is blocked, the finalizer thread will also get blocked due to that.

Symptoms of a blocked Finalizer thread

  • Memory is increasing
  • Possbile deadlock in the system (depends on a lot of factors, but it can happen)

How can we tell our Finalizer thread is blocked?

The technique for finding if the finalizer thread is blocked is quite easy and involves a few easy steps.

First of all, we need to take a series of dumps at fixed intervals (i.e. 5min apart). When we have the dumps we need to run the following set of commands from the SOS extension on all dumps and compare results (to find out how to load the SOS extension and set the symbols path look at this previous post):

  1. !FinalizeQueue – This dumps the finalization queue (not the FReachable queue). If you’ll see that the total number of object is increasing from dump to dump, we can start to suspect that our finalizer thread is blocked.
    NOTE: I say “suspect” because its still not certain at this point that the finalizer thread is blocked. This situation can also mean that the finalization of some of the objects takes a long time and the rate of objects being allocated vs. the rate of objects being finalized is in favor of the allocated objects, meaning, we are allocating objects that needs finalization faster than we are collecting them.
  2. !threads – This command will show us all .NET threads in the current process. The finalizer thread is marked at the end of the line by the text (finalizer) (surprisingly enough ;-) ). At the beginging of the line that has the (finalizer) text at the end of it you will see the thread’s index. We will need it to run the next command.
  3. ~[Finalizer Thread Index]k (i.e. ~24k)- This will dump the native call stack of the finalizer thread. If you will see in all dumps that the last function in the call stack (the top most) is something like ZwWaitForSingleObject or ZwWaitForMultipleObjects it means something is blocking our thread, usually a sync object.
    NOTE: If the call stack contains a call to a function named GetToSTA it means that the call to ZwWaitForSingleObject is there because we are tring to switch to the STA thread that created the STA objects and we are waiting to switch to it. This means that the STA thread is blocked for some reason.
  4. ~[Finalizer Thread Index]e!clrstack (i.e. ~24e!clrstack) – Dump the .NET call stack just to verify that if we don’t see a call to ZwWaitForSingleObject or ZwWaitForMultipleObjects we might be blocked due to a call to the .NET Monitor class (a native .NET implementation for a Critical Section). If we do see a call to Monitor.Enter it means we have some kind of a managed deadlock.

How to resolve a blocked finalizer thread?

If we are talking about a block that is being created due to a synchronization object (usually a critical section) we need to address it as a deadlock.

Managed Deadlock
To resolve a mangaed deadlock refer to the previous post on Identifying
Deadlock in Managed Code.

Unmanaged Deadlock
I’ll give a crash course to find unmanaged deadlocks, specifically Critical Sections since this is mainly a .NET debugging blog.

There is a Microsoft extension called sieextpub.dll (you can download it from here that is mainly focused at resolving COM issues. It has some useful commands for synchronization objects as well that we will use.

  • run the !critlist command. It will list all locked critical sections and the thread that is owning them (This is similar to running !locks but runs a lot faster).
  • Run ~[Thread ID]k (i.e. ~[22]k) to get the call stack of the owning thread.
  • If the problem is not with a critical section, but with another synchornization object such as a Mutex or a Semaphore, you can run !waitlist to see all the handles that every thread is blocking on. These handles should appear as parameters to functions such as WaitForSingleObject and WaitForMultipleObjects. We can use some native WinDbg commands to find these handles from the calls stack of the finalizer thread. For example:WaitForSingleObject:
    The handle itself will be shown in the call stack (using the kb or kv command, not just k) here:
    09b2f608 77ab4494 00000594 ffffffff 00000100 KERNEL32!WaitForSingleObject+0xf

    Compare this number to the number shown in the output of !waitlist and you will see who is the thread that is blocking the handle.

    WaitForMultipleObjects:
    Here the handle doesn’t appear directly in the kb command output since the function receives an array of handles. To find it we will need to find to parameters:
    00f4ff34 791d25d5 00000003 00f4ff58 00000000 KERNEL32!WaitForMultipleObjects+0×17

    The first bold one is the count of element in the passed array. The second one is the pointer to the array. To dump the array on the screen we will need to run the following command:
    dc 00f4ff58 – This will output the memory at that address and the output will look something like this:00f4ff58 00000700 00000708 000006d4 81b35acc ………….Z..
    00f4ff68 03a50008 b6788cb0 00000000 00000003 ……x………
    00f4ff78 00000000 ffffffff 00000000 00f4ff4c …………L…
    00f4ff88 8042f639 00f4ffdc 7920fd39 791d25e0 9.B…..9. y.%.y
    00f4ff98 ffffffff 00f4ffb4 791d254c 00000000 ……..L%.y….
    00f4ffa8 00dfcdf4 00000000 791d4d50 00f4ffec ……..PM.y….
    00f4ffb8 7c57b388 03a50008 00dfcdf4 00000000 ..W…………
    00f4ffc8 03a50008 7ff9f000 00dfc8ac 00f4ffc0 …………….

    We need to relate to the bolded number since we earlier saw that we have 3 handles to watch for. We should look to see if they appear in the output of the !waitlist to see who is blocking on them.

STA COM issues

STA COM issues are usualy caused due to the thread in which the STA object was created is blocked. To quickly find to which thread the finalizer thread is trying to switch to in order to call the destructor of the STA COM object we will use the sieextpub.dll that we mentioned above and call the !comcalls command which will simply show us the two important figures, the index of the thread that is trying to switch and the index of thread that we are trying to switch to.

Best resolution way – Avoidance

The best way of resolving blocked finalizer thread is avoiding it.
The first rule of thumb is AVOID FINALIZATION. If you don’t have to use it DON’T.

The only case implementing the finalize method is important is in a case where your class holds some private members that are native resources or that call native resources (SqlConnection for example, various Streams like FileStream and so on) in which case it is best to use the IDisposable pattern. You can find a lot of information on the internet about that but I’ll just point out a few interesting links such as this (from Eric Gunnerson’s blog. He is the Visual C# PM), and this excellent post (from Peter Provost’s blog).

In regards to STA COM object, the minute you don’t need them call Marshal.ReleaseComObject. This function wil guarentee that the COM object will get released the minute you call this function and NOT when the next GC will occur.

This was a long post, but I think it worthwhile. It a very important not to block the finalizer thread. I know that having only one without some watchdogging mechanisms is not a good design and Microsoft are aware of that.

Some additional resources for extra reading:

http://blogs.msdn.com/maoni/archive/2004/11/4.aspx – An excellent post by Maoni.

http://msdn.microsoft.com/msdnmag/issues/1100/GCI/ – An excellent article on Garbage Collection in .NET. Specifically read the “Forcing an Object to Clean Up” section which talks about the finalization of objects and a few other things.

http://www.devsource.com/article2/0,1759,1785503,00.asp – An excellent article on DevSource about .NET memory management and Finalization

Friday, July 24, 2009

Windows Forms Interview Questions

  1. Write a simple Windows Forms MessageBox statement.

System.Windows.Forms.MessageBox.Show
("Hello, Windows Forms");

  1. Can you write a class without specifying namespace? Which namespace does it belong to by default??
    Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn’t want global namespace.
  2. You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem? One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.
  3. How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
  4. So how do you retrieve the customized properties of a .NET application from XML .config file? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
  5. Can you automate this process? In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.
  6. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.
  7. What’s the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code; the program runs within security sandbox, properly written app will not require additional security privileges.
  8. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.
  9. What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
  10. What’s the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.
  11. How would you create a non-rectangular window, let’s say an ellipse? Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
  12. How do you create a separator in the Menu Designer? A hyphen ‘-’ would do it. Also, an ampersand ‘&\’ would underline the next letter.
  13. How’s anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

.NET Remoting Questions.

  1. What’s a Windows process? It’s an application that’s running and had been allocated memory.
  2. What’s typical about a Windows process in regards to memory allocation? Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
  3. Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology? A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
  4. What distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
  5. What are possible implementations of distributed applications in .NET? .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
  6. When would you use .NET Remoting and when Web services? Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
  7. What’s a proxy of the server object in .NET Remoting? It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
  8. What are remotable objects in .NET Remoting? Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
  9. What are channels in .NET Remoting? Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
  10. What security measures exist for .NET Remoting in System.Runtime.Remoting? None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
  11. What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
  12. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
  13. What’s SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
  14. What’s Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
  15. How do you define the lease of the object? By implementing ILease interface when writing the class code.
  16. Can you configure a .NET Remoting object via XML file? Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
  17. How can you automatically generate interface for the remotable object in .NET with Microsoft tools? Use the Soapsuds tool.

C# Interview Questions

  1. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and its datatype depends on whatever variable we’re changing.
  2. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it’s double colon in C++.
  3. Does C# support multiple inheritance? No, use interfaces instead.
  4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
  5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  6. Describe the accessibility modifier protected internal. It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
  7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
  8. What’s the top .NET class that everything is derived from? System.Object.
  9. How’s method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
  10. What does the keyword virtual mean in the method definition? The method can be over-ridden.
  11. Can you declare the override method static while the original method is non-static? No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
  12. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
  13. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.
  14. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.
  15. What’s an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.
  16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
  17. What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
  18. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
  19. Can you inherit multiple interfaces? Yes, why not.
  20. And if they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
  21. What’s the difference between an interface and abstract class? In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
  22. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters.
  23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
  24. What’s the difference between System.String and System.StringBuilder classes? System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  25. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
  26. Can you store multiple data types in System.Array? No.
  27. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  28. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  29. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
  30. What’s class SortedList underneath? A sorted HashTable.
  31. Will finally block get executed if the exception had not occurred? Yes.
  32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  33. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  34. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  35. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  36. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
  37. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  38. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  39. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  40. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
  41. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
  42. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
  43. What’s the difference between and XML documentation tag? Single line code example and multiple-line code example.
  44. Is XML case-sensitive? Yes, so and are different elements.
  45. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
  46. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
  47. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  48. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  50. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
  51. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  52. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
  53. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
  54. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  55. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  56. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
  57. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  58. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  59. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  60. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  61. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
  62. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
  63. What’s the data provider name to connect to Access database? Microsoft.Access.
  64. What does Dispose method do with the connection object? Deletes it from the memory.
  65. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.