Blog Archive

What is Application Domain?

The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.
Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages.
MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.
AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.
using System;
using System.Runtime.Remoting;

public class CAppDomainInfo : MarshalByRefObject
{
public string GetAppDomainInfo()
{
return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
}
}
public class App
{
public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );
ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );
CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());
string info = adInfo.GetAppDomainInfo();
Console.WriteLine( "AppDomain info: " + info );
return 0;
}
}

40. Which namespace is the base class for .net Class library?

system.object

What is Code Access Security (CAS)?

CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

What is Event - Delegate? Clear syntax for writing a event delegate

The event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code. The delegate can have one or more associated methods that will be called when your code indicates that the event has occurred. An event in one program can be made available to other programs that target the .NET Framework Common Language Runtime.
// keyword_delegate.cs
// delegate declaration
delegate void MyDelegate(int i);
class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}
public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}
public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate with number: {0}.", i);
}
}

What is portable executable (PE)?

The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. The specification for the PE/COFF file formats is available at
http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx

What is strong name?

A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly

What is JIT (just in time)? how it works?

Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler.
Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls.
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed.
As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

Can I write IL programs directly?

Yes.
assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!"
call void System.Console::WriteLine(class System. Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.

What is MSIL, IL?

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Is .NET a runtime service or a development platform?

It's both and actually a lot more. Microsoft .NET includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The .NET frameworks SDK consists of two parts: the .NET common language runtime and the .NET class library. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform.

What are the new features of Framework 1.1 ?

1. Native Support for Developing Mobile Web Applications

2. Enable Execution of Windows Forms Assemblies Originating from the Internet
Assemblies originating from the Internet zone—for example, Microsoft Windows® Forms controls embedded in an Internet-based Web page or Windows Forms assemblies hosted on an Internet Web server and loaded either through the Web browser or programmatically using the System.Reflection.Assembly.LoadFrom() method—now receive sufficient permission to execute in a semi-trusted manner. Default security policy has been changed so that assemblies assigned by the common language runtime (CLR) to the Internet zone code group now receive the constrained permissions associated with the Internet permission set. In the .NET Framework 1.0 Service Pack 1 and Service Pack 2, such applications received the permissions associated with the Nothing permission set and could not execute.

3. Enable Code Access Security for ASP.NET Applications
Systems administrators can now use code access security to further lock down the permissions granted to ASP.NET Web applications and Web services. Although the operating system account under which an application runs imposes security restrictions on the application, the code access security system of the CLR can enforce additional restrictions on selected application resources based on policies specified by systems administrators. You can use this feature in a shared server environment (such as an Internet service provider (ISP) hosting multiple Web applications on one server) to isolate separate applications from one another, as well as with stand-alone servers where you want applications to run with the minimum necessary privileges.

4. Native Support for Communicating with ODBC and Oracle Databases

5. Unified Programming Model for Smart Client Application Development
The Microsoft .NET Compact Framework brings the CLR, Windows Forms controls, and other .NET Framework features to small devices. The .NET Compact Framework supports a large subset of the .NET Framework class library optimized for small devices.

6. Support for IPv6
The .NET Framework 1.1 supports the emerging update to the Internet Protocol, commonly referred to as IP version 6, or simply IPv6. This protocol is designed to significantly increase the address space used to identify communication endpoints in the Internet to accommodate its ongoing growth.
http://msdn.microsoft.com/netframework/technologyinfo/Overview/whatsnew.aspx

What is CLR, CTS, CLS?

The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture", http://msdn.microsoft.com/net/ecma/

What is .NET Framework?

The .NET Framework has two main components: the common language runtime and the .NET Framework class library.
You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that ensure security and robustness.
The class library, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.

how to use the Char2Format Structure in VB .NET for Highlighting Text

Example

Private Sub SetCharFormatColour(ByVal RichTextBox As RichTextBox)
'Set-up Char2Format2 Structure
Dim CF2 As WinAPI.RichEditControl.CharFormat2
With CF2
.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(CF2)
.dwMask = WinAPI.RichEditControl.CFM_COLOR
.crTextColor = RGB(255, 0, 0)
End With
Dim Win32Error As Integer
Win32Error = WinAPI.RichEditControl.SendMessageA(RichTextBox.Handle.ToInt32, WinAPI.RichEditControl.EM_SETCHARFORMAT, WinAPI.RichEditControl.SCF_SELECTION, CF2)
'If the operation fails, the return value is zero. So lets get the error description and display it.
If Win32Error = 0 Then
MsgBox(WinAPI.General.GetLastErrorMessageDescription)
End If
End Sub

The latter routine requires the following unit in order to provide the interface to the Windows API:

Option Strict On
Imports System.Runtime.InteropServices

Namespace WinAPI
Public Class General
Public Const WM_USER As Int32 = &H400
Public Const WM_SETREDRAW As Int32 = &HB

'Declare Function SendMessageByString Lib "user32" Alias "SendMessageA" _
' (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long

' Declare Function SendMessageByLong Lib "user32" Alias "SendMessageA" _
' (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Declare Auto Function SendMessage Lib "user32" _
(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr

Private Declare Auto Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Integer, ByRef lpSource As Object, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByVal lpBuffer As String, ByVal nSize As Integer, ByRef Arguments As Integer) As Integer

Public Shared Function GetLastErrorMessageDescription() As String
Const FORMAT_MESSAGE_FROM_SYSTEM As Short = &H1000S
Const LANG_NEUTRAL As Short = &H0S
Dim Win32Error As Integer
Win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
Dim Buffer As String = Space(999)
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, Win32Error, LANG_NEUTRAL, Buffer, 999, 0)
Return Trim(Buffer)
End Function
End Class

Public Class RichEditControl
Public Declare Function SendMessageA Lib "user32.dll" _
(ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As CharFormat2) As Integer

Public Structure CharFormat2
Public cbSize As Int32
Public dwMask As Int32
Public dwEffects As Int32
Public yHeight As Int32
Public yOffset As Int32
Public crTextColor As Int32
Public bCharSet As Byte
Public bPitchAndFamily As Byte
Public szFaceName As String
Public wWeight As Int16
Public sSpacing As Int16
Public crBackColor As Int32
Public lcid As Int32
Public dwReserved As Int32
Public sStyle As Int16
Public wKerning As Int16
Public bUnderlineType As Byte
Public bAnimation As Byte
Public bRevAuthor As Byte
Public bReserved1 As Byte
End Structure

Public Declare Function SendMessageAv Lib "user32.dll" Alias "SendMessageA" _
(ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As CharRange) As Integer

Public Structure CharRange
Public cpMin As Int32
Public cpMax As Int32
End Structure

'RichEdit messages
Public Const EM_GETLIMITTEXT As Int32 = General.WM_USER + 37
Public Const EM_POSFROMCHAR As Int32 = General.WM_USER + 38
Public Const EM_CHARFROMPOS As Int32 = General.WM_USER + 39
Public Const EM_SCROLLCARET As Int32 = General.WM_USER + 49
Public Const EM_CANPASTE As Int32 = General.WM_USER + 50
Public Const EM_DISPLAYBAND As Int32 = General.WM_USER + 51
Public Const EM_EXGETSEL As Int32 = General.WM_USER + 52
Public Const EM_EXLIMITTEXT As Int32 = General.WM_USER + 53
Public Const EM_EXLINEFROMCHAR As Int32 = General.WM_USER + 54
Public Const EM_EXSETSEL As Int32 = General.WM_USER + 55
Public Const EM_FINDTEXT As Int32 = General.WM_USER + 56
Public Const EM_FORMATRANGE As Int32 = General.WM_USER + 57
Public Const EM_GETCHARFORMAT As Int32 = General.WM_USER + 58
Public Const EM_GETEVENTMASK As Int32 = General.WM_USER + 59
Public Const EM_GETOLEINTERFACE As Int32 = General.WM_USER + 60
Public Const EM_GETPARAFORMAT As Int32 = General.WM_USER + 61
Public Const EM_GETSELTEXT As Int32 = General.WM_USER + 62
Public Const EM_HIDESELECTION As Int32 = General.WM_USER + 63
Public Const EM_PASTESPECIAL As Int32 = General.WM_USER + 64
Public Const EM_REQUESTRESIZE As Int32 = General.WM_USER + 65
Public Const EM_SELECTIONTYPE As Int32 = General.WM_USER + 66
Public Const EM_SETBKGNDCOLOR As Int32 = General.WM_USER + 67
Public Const EM_SETCHARFORMAT As Int32 = General.WM_USER + 68
Public Const EM_SETEVENTMASK As Int32 = General.WM_USER + 69
Public Const EM_SETOLECALLBACK As Int32 = General.WM_USER + 70
Public Const EM_SETPARAFORMAT As Int32 = General.WM_USER + 71
Public Const EM_SETTARGETDEVICE As Int32 = General.WM_USER + 72
Public Const EM_STREAMIN As Int32 = General.WM_USER + 73
Public Const EM_STREAMOUT As Int32 = General.WM_USER + 74
Public Const EM_GETTEXTRANGE As Int32 = General.WM_USER + 75
Public Const EM_FINDWORDBREAK As Int32 = General.WM_USER + 76
Public Const EM_SETOPTIONS As Int32 = General.WM_USER + 77
Public Const EM_GETOPTIONS As Int32 = General.WM_USER + 78
Public Const EM_FINDTEXTEX As Int32 = General.WM_USER + 79
Public Const EM_GETWORDBREAKPROCEX As Int32 = General.WM_USER + 80
Public Const EM_SETWORDBREAKPROCEX As Int32 = General.WM_USER + 81
'Richedit v2.0 messages
Public Const EM_SETUNDOLIMIT As Int32 = General.WM_USER + 82
Public Const EM_REDO As Int32 = General.WM_USER + 84
Public Const EM_CANREDO As Int32 = General.WM_USER + 85
Public Const EM_GETUNDONAME As Int32 = General.WM_USER + 86
Public Const EM_GETREDONAME As Int32 = General.WM_USER + 87
Public Const EM_STOPGROUPTYPING As Int32 = General.WM_USER + 88
Public Const EM_SETTEXTMODE As Int32 = General.WM_USER + 89
Public Const EM_GETTEXTMODE As Int32 = General.WM_USER + 90

Public Const CFM_BOLD As Int32 = &H1
Public Const CFM_ITALIC As Int32 = &H2
Public Const CFM_UNDERLINE As Int32 = &H4
Public Const CFM_STRIKEOUT As Int32 = &H8
Public Const CFM_PROTECTED As Int32 = &H10
Public Const CFM_LINK As Int32 = &H20
Public Const CFM_SIZE As Int32 = &H80000000
Public Const CFM_COLOR As Int32 = &H40000000
Public Const CFM_FACE As Int32 = &H20000000
Public Const CFM_OFFSET As Int32 = &H10000000
Public Const CFM_CHARSET As Int32 = &H8000000

Public Const SCF_SELECTION As Int32 = &H1
Public Const SCF_WORD As Int32 = &H2
Public Const SCF_DEFAULT As Int32 = &H0
Public Const SCF_ALL As Int32 = &H4
Public Const SCF_USEUIRULES As Int32 = &H8

'Event notification masks
Public Const ENM_NONE As Int32 = &H0
Public Const ENM_CHANGE As Int32 = &H1
Public Const ENM_UPDATE As Int32 = &H2
Public Const ENM_SCROLL As Int32 = &H4
Public Const ENM_KEYEVENTS As Int32 = &H10000
Public Const ENM_MOUSEEVENTS As Int32 = &H20000
Public Const ENM_REQUESTRESIZE As Int32 = &H40000
Public Const ENM_SELCHANGE As Int32 = &H80000
Public Const ENM_DROPFILES As Int32 = &H100000
Public Const ENM_PROTECTED As Int32 = &H200000
Public Const ENM_CORRECTTEXT As Int32 = &H400000 ' PenWin specific
Public Const ENM_SCROLLEVENTS As Int32 = &H8
Public Const ENM_DRAGDROPDONE As Int32 = &H10
Public Const ENM_PARAGRAPHEXPANDED As Int32 = &H20
End Class

End Namespace

Source Code for Print An Array of Strings

Public Class PrintArrayOfStrings
Private pArrayOfStrings() As String
Private pPrintFont As Font
Private pCurrentLine As Integer = 0
Private pArrayOfStrings_UpperBound As Integer

Public Sub New(ByVal ArrayOfStrings() As String)
Me.New(ArrayOfStrings, New Font("Arial", 10))
End Sub

Public Sub New(ByVal ArrayOfStrings() As String, ByVal PrintFont As Font)
pArrayOfStrings = ArrayOfStrings
pPrintFont = PrintFont
pArrayOfStrings_UpperBound = pArrayOfStrings.GetUpperBound(0)
Try
Dim PrintDocument As PrintDocument = New PrintDocument() 'Assumes default printer
AddHandler PrintDocument.PrintPage, New System.Drawing.Printing.PrintPageEventHandler(AddressOf PrintPage)
PrintDocument.Print()
Catch ex As Exception
MessageBox.Show("An error occurred printing. " + ex.Message)
End Try
End Sub

Private Sub PrintPage(ByVal sender As Object, ByVal ev As System.Drawing.Printing.PrintPageEventArgs)
Dim LinesPerPage As Single
Dim yPos As Single = 0
Dim Count As Integer = 0
Dim Line As String
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
LinesPerPage = ev.MarginBounds.Height / pPrintFont.GetHeight(ev.Graphics)
' Print each line of the file.
While (Count < LinesPerPage) And (pCurrentLine <= pArrayOfStrings_UpperBound)
Line = pArrayOfStrings(pCurrentLine)
yPos = topMargin + Count * pPrintFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(Line, pPrintFont, Brushes.Black, leftMargin, yPos, New StringFormat())
Count += 1
pCurrentLine += 1
End While
ev.HasMorePages = (pCurrentLine <= pArrayOfStrings_UpperBound)
End Sub

End Class

how to get Version Information From The AssemblyInfo File in vb.net

Function GetVersion() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart
End With
End Function

Function GetComments() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .Comments
End With
End Function

How to programmatically Resizing DataGrid Columns in vb.net/c#

Public Class MyUtils_DataGrid
'Method: DataGridApplyAutomaticWidths
'Parameters
' DataGrid=DataGrid that is to be formatted.
' NumberOfRowsToScan=Number of data records to be scanned in order to compute the columns widths (Recommend 20).
' MaxPixelWidth=Maximum allowable pixel width of a column.
'
'Takes a DataGrid that should be already assigned a populated dataset,
'and formats the DataGrid so that the column widths reflect the widths of the data.
'This is accomplished by dynamically creating a single DataGridTableStyle and multiple DataGridTextBoxColumn(s).
'For each data column, the width of the column is set to the highest data width within the column.
'In order to reduce computation time where large datasets exist,
'a parameter exists to define how many rows are scanned.
'I would suggest that only the first 20 rows are scanned,
Public Shared Function DataGridApplyAutomaticWidths _
(ByVal DataGrid As System.Windows.Forms.DataGrid, ByVal NumberOfRowsToScan As Integer, ByVal MaxPixelWidth As Integer) _
As DataGridTableStyle
'Create graphics object for measuring widths.
Dim Graphics As Graphics = DataGrid.CreateGraphics()
'Define new table style.
Dim TableStyle As DataGridTableStyle = New DataGridTableStyle()
Try
Dim DataTable As DataTable
'DataTable = DataGrid.DataSource.DataSet.Tables(0)
DataTable = DataGrid.DataSource.Tables(0)
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan, DataTable.Rows.Count)
'Clear any existing table styles.
DataGrid.TableStyles.Clear()
'Use mapping name that is defined in the data source.
TableStyle.MappingName = DataTable.TableName
'Now create the column styles within the table style.
Dim Column As DataColumn
Dim ColumnStyle As DataGridTextBoxColumn
Dim Width As Integer
For Each Column In DataTable.Columns
ColumnStyle = New DataGridTextBoxColumn()
With ColumnStyle
.TextBox.Enabled = True
.HeaderText = Column.ColumnName
.MappingName = Column.ColumnName
'Set width to header text width.
Width = Graphics.MeasureString(.HeaderText, DataGrid.Font, MaxPixelWidth).Width
End With
'Change width, if data width is wider than header text width.
'Check the width of the data in the first X rows.
Dim iRow As Integer
Dim DataRow As DataRow
For iRow = 0 To NumberOfRowsToScan - 1
DataRow = DataTable.Rows(iRow)
If Not IsDBNull(DataRow(Column.ColumnName)) Then
Width = System.Math.Max(Width, Graphics.MeasureString(DataRow(Column.ColumnName), DataGrid.Font, MaxPixelWidth).Width)
End If
Next
ColumnStyle.Width = Width + 4
'Add the new column style to the table style.
TableStyle.GridColumnStyles.Add(ColumnStyle)
Next
'Add the new table style to the data grid.
DataGrid.TableStyles.Add(TableStyle)
Finally
Graphics.Dispose()
End Try
Return TableStyle
End Function

'This one allows a DataGridTableStyle to all ready exist on the table.
Public Shared Function DataGridApplyAutomaticWidths _
(ByVal DataGrid As System.Windows.Forms.DataGrid, ByVal TableStyle As DataGridTableStyle, _
ByVal NumberOfRowsToScan As Integer, ByVal MaxPixelWidth As Integer) _
As DataGridTableStyle
'Create graphics object for measuring widths.
Dim Graphics As Graphics = DataGrid.CreateGraphics()
Try
Dim DataTable As DataTable
'DataTable = DataGrid.DataSource.DataSet.Tables(0)
DataTable = DataGrid.DataSource.Tables(0)
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan, DataTable.Rows.Count)
'Now loop through the columns and set the widths.
Dim Column As DataColumn
Dim ColumnStyle As DataGridColumnStyle
Dim Width As Integer
For Each Column In DataTable.Columns
ColumnStyle = TableStyle.GridColumnStyles(Column.ColumnName)
If Not ColumnStyle Is Nothing Then
'Set width to header text width.
Width = Graphics.MeasureString(ColumnStyle.HeaderText, DataGrid.Font, MaxPixelWidth).Width
'Change width, if data width is wider than header text width.
'Check the width of the data in the first X rows.
Dim iRow As Integer
Dim dr As DataRow
For iRow = 0 To NumberOfRowsToScan - 1
dr = DataTable.Rows(iRow)
If Not IsDBNull(dr(Column.ColumnName)) Then
Width = System.Math.Max(Width, Graphics.MeasureString(dr(Column.ColumnName), DataGrid.Font, MaxPixelWidth).Width)
End If
Next
ColumnStyle.Width = Width + 4
End If
Next
Finally
Graphics.Dispose()
End Try
Return TableStyle
End Function

Public Shared Function GetNewDataGridTextBoxColumn(ByVal MappingName As String) As DataGridTextBoxColumn
Dim TextBoxColumn As DataGridTextBoxColumn = New DataGridTextBoxColumn()
With TextBoxColumn
.MappingName = MappingName
.HeaderText = MappingName
.ReadOnly = True
.Width = 200
End With
Return TextBoxColumn
End Function

Public Shared Function GetNewDataGridTextBoxColumn(ByVal MappingName As String, ByVal [ReadOnly] As Boolean) As DataGridTextBoxColumn
Dim TextBoxColumn As DataGridTextBoxColumn
TextBoxColumn = GetNewDataGridTextBoxColumn(MappingName)
TextBoxColumn.ReadOnly = [ReadOnly]
Return TextBoxColumn
End Function

End Class

What is late binding ?

When code interacts with an object dynamically at runtime .because our code literally doesnot care what type of object it is interacting and with the methods thats are supported by object and with the methods thats are supported by object .The type of object is not known by the IDE or compiler ,no Intellisense nor
compile-time syntax checking is possible but we get unprecedented flexibilty in exchange.if we enable strict type checking by using option strict on at the top of our code modules ,then IDE and compiler will enforce early binding behaviour .By default Late binding is done.

What is ASP.Net Web Matrix?

ASP.Net Web Matrix is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, download includes simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.

What is XPATH?

XML Path Language is a W3C specification that defines syntax for addressing parts of XML document. XML document is considered as a logical tree structure, and syntax based on this consideration is used to address elements and attributes at any level in the XML document.

For example, considering the XML document described above in answer to question 2, /abc:Employees/abc:Emp/@EmpID XPath expression can be used to access the EmpID attribute under the Emp element under the Employees document element.

XPath is used in various other specifications such as XSLT.

What is a Satellite Assembly ?

This assembly is used to get language specific resources for an application.These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language.

What is an application domain?

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET.

What is view state and use of it?

The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.

What is the difference between an event and a delegate?

An event is just a wrapper for a multicast delegate. Adding a public event to a class is almost the same as adding a public multicast delegate field. In both cases, subscriber objects can register for notifications, and in both cases the publisher object can send notifications to the subscribers.

However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to restrict to the publisher. Hence events - an event adds public methods to the containing class to add and remove receivers, but does not make the invocation mechanism public.

What is view state and use of it?

The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.

What's a bubbled event?

When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious.

The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.Suppose you want a certain ASP.NET function executed on MouseOver over a certain button.

Why do we get errors when we try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

Why is XmlSerializer so slow?

There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay.

This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application

How can I turn on/off tracing for entire site/application?

Open up your web.config file - then, somewhere in the system.web section, put this :
true" />

Set it to 'false' when you don't want it to show up.

What's the difference between a Panel and a Placeholder?

Functionality-wise, both server controls are generally the same. They both act as containers, separating other server controls, etc., into logical sections.


The PlaceHolder control doesn't have most of those capabilities. It's major function is to act as a container for other tags/server controls.

However, the Panel has a bit more overhead. A panel has most of the display/decoration/style capabilities of the other server controls (border style/width/color, BackColor, Font, CssClass, etc).

Why isn't database with OleDb ExecuteNonQuery updating my database?

When editing/updating a database with OleDb - here are two things to make sure of:

Make sure the defining parameter (ie: Where uid=@uid) in the Where clause is actually getting populated

When using parameterized queries, OLEDB parameters are positional. Make sure the parameters are defined in the same order as they appear in the SQL update string.

How can I add nest Master Pages?

Master page for your business's website.

However, inside that 'shell', you also want a certain design for each department of the business. All you need to do, is create the second 'Department' Master page. Then, inside the Master Directive, include a reference back to the Business Master:

<%@ Master Language="VB" MasterPageFile="~/Business.master" .....

Also, be sure to use different ContentPlaceholder ids, and remember the one caveat - if you're using Nested Masters inside VS.Net 2005, you'll need to only use the html view, since the design view does not support nesting master pages.

what is smart Clients?

Smart clients are client applications that consume Web services and reside on user hardware such as desktop PCs, laptops, Pocket PCs, and Smartphones. They are easily deployed and managed and provide an adaptive, responsive, and rich interactive experience by taking advantage of the computing resources on the device and intelligently connecting to distributed data sources.

Debugging Problems in ASP.NET

When you try to debug an ASP.NET application in Visual Studio.NET. you may receive the following debugging error.

Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.

Following are reasons and solutions for this problems.

Possibility 1:
You are not a part of debugger group.

Solution
Local Users and Groups ->Users- > add yourself as a Debugger User (Also check if you are a VSDeveloper

Possibility 2:
You dont have execute permissions on your virtual folder.

Solution
Step 1: Control Panel -> Administrative Tools- >Internet Service Manager

Step 2: Default Web Site -> Right Click on your Project-> Properties->Execute Permissions -> Scripts and Executables

Possibility 3:
You have kept ASP.NET debugging unchecked.

Solution
In VS.NET IDE,

Right Click Project - >Properties->Configuration Properties ->Debugging-> Debuggers Enable Check the checkbox for ASP.NET Debugging

Difference Between ASP.NET Server Controls,HTML Server Controls and HTML Intrinsic Controls

ASP.NET Server Controls
Advantages:

1. ASP .NET Server Controls can however detect the target browser's capabilities and render themselves accordingly. No issues for compatibility issues of Browsers i.e page that might be used by both HTML 3.2 and HTML 4.0 browsers code to be written by you.
2. Newer set of controls that can be used in the same manner as any HTMl control like Calender controls. (No need of Activex Control for doing this which would then bring up issues of Browser compatibility).
3. Processing would be done at the server side. In built functionality to check for few values(with Validation controls) so no need to choose between scripting language which would be incompatible with few browsers.
4. ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls.
5. ASP .NET Server Controls have higher level of abstraction. An output of an ASP .NET server control can be the result of many HTML tags that combine together to produce that control and its events.


Disadvantages:

1. The control of the code is inbuilt with the web server controls so you have no much of direct control on these controls
2. Migration of ASP to any ASP.NET application is difficult. Its equivalent to rewriting your new application
HTML Server Controls
Advantages:

1. The HTML Server Controls follow the HTML-centric object model. Model similar to HTML
2. Here the controls can be made to interact with Client side scripting. Processing would be done at client as well as server depending on your code.
3. Migration of the ASP project thought not very easy can be done by giving each intrinsic HTML control a runat = server to make it HTML Server side control.
4. The HTML Server Controls have no mechanism of identifying the capabilities of the client browser accessing the current page.
5. A HTML Server Control has similar abstraction with its corresponding HTML tag and offers no abstraction.

Disadvantages:
1. You would need to code for the browser compatibility.
HTML Intrinsic Controls
Advantages:
1. Model similar to HTML
2. Here the controls can be made to interact with Client side scripting

Disadvantages:
1. You would need to code for the browser compatibility

Controls Not Appearing on ASP.NET Page

After you install Microsoft Visual Studio .NET or the Microsoft .NET Framework, When you try to access any aspx page. If the ASPX page is not coming or if controls or not appearing in the Page. Then this could be caused because of wrong asp.net installation.

To configure asp.net properly in IIS Just follow these steps.

Dot net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v1.0.3705\aspnet_regiis.exe (This folder might change depending upon on you framework installation folder)

Then uninstall current ASP.NET Version using following Command,

aspnet_regiis.exe -u

For again installing ASP.NET, Use following command.

aspnet_regiis.exe -i

To know more about aspnet_regiis, check out this link.

What is SOAP?

SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.
To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted):

xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">


10016



As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode).
Here is a sample SOAP response from the weather service:

xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

xmlns:ns1="urn:examples:weatherservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
*65
*
*

*
The response indicates a single integer return value (the current temperature).
The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.

What is a Web service?

Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system

XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications.
Beyond this basic definition, a Web service may also have two additional (and desirable) properties:

First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL).

Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration

How to User Windows API user for Printing Directly to Printer in C#?

Printing in C# - .NET C#
Printing Directly to the Printer
Code is here

using System.Runtime.InteropServices;
using System.IO;



System.Drawing.Printing.PrinterSettings pr = new System.Drawing.Printing.PrinterSettings();
clsPrinter.SendStringToPrinter(pr.PrinterName, "Hello");


// Class for Printer
public class clsPrinter
{

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}

Connect to web site using SSL & Client Certificates

public void Connect()
{

X509Certificate cert =X509Certificate.CreateFromCertFile("c:\\Certificat es\\verisign_cert.cer");
//WebRequest request = GetWebRequest(newUri(https://myserver.com/mypage.aspx));
request.ContentType = "text/xml";
request.Method = "POST";
HttpWebRequest httpRequest = (HttpWebRequest)request;httpRequest.UserAgent = "Exel Test";
httpRequest.Headers = new WebHeaderCollection();
httpRequest.ClientCertificates.Add(cert);
request = (WebRequest)httpRequest;
// This is where it breaks...
Stream reqStream = request.GetRequestStream();
reqStream.Close();
WebResponse resp = GetWebResponse(request);
Stream respStream = resp.GetResponseStream();
TextReader tr = new StreamReader(respStream, new UTF8Encoding(), true,4096);
string certInfo = tr.ReadToEnd();
System.Diagnostics.Debug.WriteLine(certInfo);
}

How to Create new Session in Connected Services Framework(CSF) ?

using System;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.ConnectedServices.Sdk;
using Microsoft.ConnectedServices.Sdk.Client;
using Microsoft.ConnectedServices.Sdk.Messaging;
using Microsoft.ConnectedServices.Sdk.Addressing;
using Microsoft.ConnectedServices.Contracts.Session;
using Microsoft.ConnectedServices.Sdk.Security.Tokens;

///


/// Create new session based on the Message
///

///
/// Return the SessionResponse Object on successful completion
/// otherwise throws SoapException
///

private CreateSessionResponse CreateSession()
{
CreateSessionRequest request = new CreateSessionRequest(GetSessionManifest());
Message sessionCreateMessage = Message.CreateMessage( SessionActions.CreateRequest, new Uri(_sessionManagerAdminUri), request );

// Add Security Header
sessionCreateMessage.Header.Security.Add(SecurityUserToken());
MessageSender sessionCreateSender = new MessageSender();
try
{
// Create the session synchronously!
CreateSessionResponse response = sessionCreateSender.SendSync( sessionCreateMessage );
return response;
}
catch (Exception ex)
{
throw ex;
}
}