Search This Blog

Monday, April 14, 2014

Drag-and-Drop Operation in Windows Forms

Drag-and-Drop Operation in Windows Forms

To perform drag-and-drop operations within Windows-based applications you must handle a series of events, most notably the DragEnterDragLeave, and DragDrop events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations.


To Start The Drag Operation

All drag-and-drop operations begin with dragging. The functionality to enable data to be collected when dragging begins is implemented in the DoDragDrop method.
In the following example, the MouseDown event is used to start the drag operation because it is the most intuitive (most drag-and-drop actions begin with the mouse button being depressed). However, remember that any event could be used to initiate a drag-and-drop procedure.
  • In the MouseDown event for the control where the drag will begin, use the DoDragDrop method to set the data to be dragged and the allowed effect dragging will have. For more information, see Data and AllowedEffect.
  • The following example shows how to initiate a drag operation. The control where the drag begins is a Button control, the data being dragged is the string representing the Text property of the Button control, and the allowed effects are either copying or moving.

private void button1_MouseDown(object sender, 
System.Windows.Forms.MouseEventArgs e)
{
   button1.DoDragDrop(button1.Text, DragDropEffects.Copy | 
      DragDropEffects.Move);
}

To perform a drop

Once you have begun dragging data from a location on a Windows Form or control, you will naturally want to drop it somewhere. The cursor will change when it crosses an area of a form or control that is correctly configured for dropping data. Any area within a Windows Form or control can be made to accept dropped data by setting the AllowDrop property and handling the DragEnter and DragDrop events.
  1. Set the AllowDrop property to true.
  2. In the DragEnter event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, Text). The code then sets the effect that will happen when the drop occurs to a value in the DragDropEffects enumeration. 
private void textBox1_DragEnter(object sender, 
System.Windows.Forms.DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.Text)) 
      e.Effect = DragDropEffects.Copy;
   else
      e.Effect = DragDropEffects.None;
}
In the DragDrop event for the control where the drop will occur, use the GetData method to retrieve the data being dragged.
In the example below, a TextBox control is the control being dragged to (where the drop will occur). The code sets the Text property of the TextBox control equal to the data being dragged.
private void textBox1_DragDrop(object sender, 
System.Windows.Forms.DragEventArgs e)
{
   textBox1.Text = e.Data.GetData(DataFormats.Text).ToString();
}

Saturday, April 12, 2014

The Concept Of Generics In .Net With C# And VB.Net

The Detailed Description Of Generics In .Net

Generic Type : A generic type is a type that uses generic type parameters. For example, the type LinkedList, defined as:

C#
public class LinkedList
{...}
VB.Net
Public Class LinkedList(Of K, T)
    ...
End Class

Generic Type Parameter : A generic type parameter is the place holder a generic type uses. For example, the generic type LinkedList, defined as:

C#
public class LinkedList
{...}
VB.Net
Public Class LinkedList(Of K, T)
    ...
End Class

Some more description about generics:
Constructed Type : A constructed type is any generic type that has at least one type argument.

Open Constructed Type : A open constructed type is any generic type that which contains at least one type parameter used as a type argument

Closed Constructed Type : A closed constructed type is a generic type that which contains no type parameters as type arguments.

Initialize a Generic Type Parameter

When declaring a generic type, you need to specify the types that will replace the type parameters in the declaration. These are known as type arguments to the generic type. Type arguments are simply types. 
You need to specify which types to use for K, the list's key, and T, the data items stored in the list. You specify the types in two places: when declaring the list's variable and when instantiating it:
C#
LinkedList list = new LinkedList();
list.AddHead(123,"ABC");
VB.Net
Dim list As New LinkedList(Of Integer, String)
list.AddHead(123, "ABC")

Constraints in Generics:

Constraints allow additional contextual information to be added to the type parameters of generic types. The constraints limit the range of types that are allowed to be used as type arguments, but at the same time, they add information about those type parameters. Constraints ensure that the type arguments specified by the client code are compatible with the generic type parameters the generic type itself uses. Meaning, constraints prevent the client from specifying types as type arguments that do not offer the methods, properties, or members of the generic type parameters that the generic type relies upon.
After applying a constraint you get IntelliSense reflecting the constraints when using the generic type parameter, such as suggesting methods or members from the base type.
Derivation constraint indicates to the compiler that the generic type parameters derives from a base type such an interface or a particular base class. 
You can provide constraints for every generic type parameter that your class declares. You can have a base class constraint, meaning, stipulating that the generic type parameter derives from a particular base class:
However, you can only use one base class at most in a constraint because neither C#, Visual Basic or managed C++ support multiple inheritance of implementation. Obviously, the base class you constrain to cannot be a sealed class, and the compiler enforces that. In addition, you cannot constrain System.Delegate or System.Array as a base class.
You can constrain both a base class and one or more interfaces, but the base class must appear first in the derivation constraint list.You can combine the default constructor constraint with derivation constraints, provided the default constructor constraint appears last in the constraint list.

Auto-Generate Wrapper Classes for Stored Procedures Using the AutoSproc Tool

Auto-Generate Wrapper Classes for Stored Procedures Using the AutoSproc Tool


The essence of the idea behind AutoSproc is for the developer to define methods on an interface that correspond to the stored procedures that exist in a database. These interface methods are abstract at the time of program compilation, but receive an implementation at runtime from a code generation assembly the client program references, named AutoSproc.dll. At the heart of this assembly there is a publicly callable static (shared) method called SprocFactory.CreateInstance(). A key parameter that must be passed when making a call to this method is type information for an interface. The primary function of this method is to dynamically fabricate a class that implements the designated interface and to return an instance of that class to the caller. As an example, consider the following stored procedure definition:



CREATE PROCEDURE upAddTwoNumbers
@a int,
@b int,
@result int output
AS
select @result = @a+@b

Given this definition, the interface would be defined in Visual Basic .NET as follows:
Public Interface IMath
    Inherits ISprocBase
    Function upAddTwoNumbers(ByVal a As Integer, _
      ByVal b As Integer, _
      ByRef result As Integer) As Integer
End Interface

ISprocBase adds three properties to your deriving interface:
Public Interface ISprocBase
   Property Connection() as IDbConnection
   Property AutoClose () as Boolean
   Property Transaction () as IDbTransaction
End Interface
The Connection property is the means by which one passes the database connection to the code generated class at runtime.
ISprocBase.AutoClose Property
The AutoClose property on the interface can be used to toggle this feature on and off dynamically at runtime during the lifetime of the application.

ISprocBase.Transaction Property

It is often the case that a local transaction is used to protect multiple operations carried out against a database. To facilitate this, a transaction property is defined on the base interface. Its usage is fairly straightforward: Use the database connection to begin the transaction (IDbConnection.BeginTransaction()), feed the transaction to the transaction property on the code generated class, make one or more transacted stored procedure calls then either commit / abort or rollback the transaction (IDbTransaction.Commit()Abort() / Rollback()).
It is important to note that if AutoClose is set to true, then the transaction will exhibit potentially undesirable auto commit behavior because closing the database connection implicitly attempts to commit the transaction. It is recommended that if the Transaction property is being used then AutoClose is set to false.

SprocFactory.CreateInstance() Method Overloads

There are four overloaded SprocFactory.CreateInstance() methods offered, only one of which is strictly necessary (the second one). The other three are offered as a convenience to the developer for seeding Connection and AutoClose properties at creation time. It should be noted that overloads not providing an AutoClose parameter (the first and third) will configure it to true by default.

Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal prov as DBProvider) _
as Object

2.
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal prov as DBProvider, _
                  autoClose as Boolean) as Object 
3
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal conn as IDbConnection) _
as Object
4.
Public Shared Function CreateInstance (ByVal itf as Type, _
ByVal conn as IDbConnection, _
                  ByVal autoClose as Boolean) _
                  as Object
The DBProvider enumeration is the means by which the user configures the code generation layer to emit an implementation. For this release, only SQL Server and OleDb managed providers are available. If the user elects to use the third or fourth CreateInstance() method then the database provider type is inferred by the code generation layer from the IDbConnection parameter, thus making a DBProvider enumeration parameter unnecessary.

Sunday, March 30, 2014

Drawing in .Net With GDI+

Drawing in .Net With GDI+

GDI+ is an application programming interface (API) that forms the subsystem of the Microsoft Windows XP operating system. GDI+ is responsible for displaying information on screens and printers. As its name suggests, GDI+ is the successor to GDI, the Graphics Device Interface included with earlier versions of Windows.

The GDI+ API is exposed through a set of classes deployed as managed code. This set of classes is called the managed class interface to GDI+. The following namespaces make up the managed class interface:

  • System.Drawing:
The Graphics class provides methods for drawing to the display device. Classes such as Rectangle and Point encapsulate GDI+ primitives. The Pen class is used to draw lines and curves, while classes derived from the abstract class Brush are used to fill the interiors of shapes.

Classes

  • Bitmap:Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap is an object used to work with images defined by pixel data.
  • Brush:Defines objects used to fill the interiors of graphical shapes such as rectangles, ellipses, pies, polygons, and paths.
  • Brushes:Brushes for all the standard colors. This class cannot be inherited.
  • BufferedGraphics:Provides a graphics buffer for double buffering.
  • BufferedGraphicsContext: Provides methods for creating graphics buffers that can be used for double buffering.
  • ColorConverter: Converts colors from one data type to another. Access this class through the TypeDescriptor.
  • ColorTranslator : Translates colors to and from GDI+ Color structures. This class cannot be inherited.
  • Font : Defines a particular format for text, including font face, size, and style attributes. This class cannot be inherited.
  • FontConverter : Converts Font objects from one data type to another.
  • FontConverter.FontNameConverter : Infrastructure. FontConverter.FontNameConverter is a type converter that is used to convert a font name to and from various other representations.
  • FontConverter.FontUnitConverter : Infrastructure. Converts font units to and from other unit types.
  • FontFamily : Defines a group of type faces having a similar basic design and certain variations in styles. This class cannot be inherited.
  • Graphics : Encapsulates a GDI+ drawing surface. This class cannot be inherited.
  • Icon : Represents a Windows icon, which is a small bitmap image used to represent an object. Icons can be thought of as transparent bitmaps, although their size is determined by the system.
  • IconConverter : Converts an Icon object from one data type to another. Access this class through the TypeDescriptor object.
  • Image : An abstract base class that provides functionality for the Bitmap and Metafile descended classes.
  • ImageAnimator : Animates an image that has time-based frames.
  • ImageConverter: ImageConverter is a class that can be used to convert Image objects from one data type to another. Access this class through the TypeDescriptor object.
  • ImageFormatConverter : ImageFormatConverter is a class that can be used to convert ImageFormat objects from one data type to another. Access this class through the TypeDescriptor object.
  • Pen: Defines an object used to draw lines and curves. This class cannot be inherited.
  • Pens : Pens for all the standard colors. This class cannot be inherited.
  • PointConverter : Converts a Point object from one data type to another. Access this class through the TypeDescriptor object.
  • PointConverter :Converts a Point object from one data type to another. Access this class through the TypeDescriptor object.
  • RectangleConverter: Converts rectangles from one data type to another. Access this class through the TypeDescriptor.
  • Region :Describes the interior of a graphics shape composed of rectangles and paths. This class cannot be inherited.
  • SizeConverter : The SizeConverter class is used to convert from one data type to another. Access this class through theTypeDescriptor object.
  • SizeFConverter : Converts SizeF objects from one type to another.
  • SolidBrush : Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths. This class cannot be inherited.
  • StringFormat : Encapsulates text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features. This class cannot be inherited.
  • SystemBrushes : Each property of the SystemBrushes class is a SolidBrush that is the color of a Windows display element.
  • SystemColors : Each property of the SystemColors class is a Color structure that is the color of a Windows display element.
  • SystemFonts : Specifies the fonts used to display text in Windows display elements.
  • SystemIcons : Each property of the SystemIcons class is an Icon object for Windows system-wide icons. This class cannot be inherited.
  • SystemPens : Each property of the SystemPens class is a Pen that is the color of a Windows display element and that has a width of 1 pixel.
  • TextureBrush :Each property of the TextureBrush class is a Brush object that uses an image to fill the interior of a shape. This class cannot be inherited.
  • ToolboxBitmapAttribute : Allows you to specify an icon to represent a control in a container, such as the Microsoft Visual Studio Form Designer.

Formating in DataGridView

To Set Alternating Row Styles for the Windows Forms DataGridView Control

With the DataGridView control, you can specify complete style information for alternating rows. This enables you use style characteristics like foreground color and font, in addition to background color, to differentiate alternating rows.

this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor =
    Color.Beige;
To specify the font used by DataGridView cells
  • Set the Font property of a DataGridViewCellStyle

this.dataGridView1.DefaultCellStyle.Font = new Font("Verdana", 15);

To specify the foreground and background colors of DataGridView cells

Set the ForeColor and BackColor properties of a DataGridViewCellStyle.
this.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;

To specify the foreground and background colors of selected DataGridView cells

  • Set the SelectionForeColor and SelectionBackColor properties of a DataGridViewCellStyle.
this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black;

Use the Row Template to Customize Rows in the Windows Forms DataGridView Control
The DataGridView control uses the row template as a basis for all rows that it adds to the control either through data binding or when you call theDataGridViewRowCollection.Add method without specifying an existing row to use.
The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set anyDataGridViewRow properties, including DefaultCellStyle.
There are some situations where you must use the row template to achieve a particular effect. For example, row height information cannot be stored in a DataGridViewCellStyle, so you must use a row template to change the default height used by all rows. The row template is also useful when you create your own classes derived from DataGridViewRow and you want your custom type used when new rows are added to the control.
  • Set properties on the object retrieved from the DataGridView.RowTemplate property.

DataGridViewRow row = this.dataGridView1.RowTemplate;
row.DefaultCellStyle.BackColor = Color.Bisque;
row.Height = 35;
row.MinimumHeight = 20;


Change the Border and Gridline Styles in the Windows Forms DataGridView Control

To Change the Border and Gridline Styles in the Windows Forms DataGridView Control

With the DataGridView control, you can customize the appearance of the control's border and gridlines to improve the user experience. You can modify the gridline color and the control border style in addition to the border styles for the cells within the control. You can also apply different cell border styles for ordinary cells, row header cells, and column header cells.

To change the gridline color programmatically

  • Set the GridColor property.
this.dataGridView1.GridColor = Color.Blue;

To change the border style of the entire DataGridView control programmatically

  • Set the BorderStyle property to one of the BorderStyle enumeration values.

To change the border styles for DataGridView cells programmatically

  • Set the CellBorderStyleRowHeadersBorderStyle, and ColumnHeadersBorderStyle properties.
this.dataGridView1.CellBorderStyle =
    DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle =
    DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle =
    DataGridViewHeaderBorderStyle.Single;

Configure an Application to Support .NET Framework 4 or 4.5

Application Configuration to Support .Net Framework 4 or 4.5

All apps that host the common language runtime (CLR) need to start, or activate, the CLR in order to run managed code. Typically, a .NET Framework app runs on the version of the CLR that it was built on, but you can change this behavior for desktop apps by using an application configuration file (sometimes referred to as an app.config file). However, you cannot change the default activation behavior for Windows Store apps or Windows Phone apps by using an application configuration file. 

To configure your app to run on the .NET Framework 4 or 4.5
  1. Add or locate the configuration file for the .NET Framework project. The configuration file for an app is in the same directory and has the same name as the app, but has a .config extension. For example, for an app named MyExecutable.exe, the application configuration file is named MyExecutable.exe.config.
    To add a configuration file, on the Visual Studio menu bar, choose ProjectAdd New Item. Choose General from the left pane, and then choose Configuration File. Name the configuration file appName.exe.config. These menu choices are not available for Windows Store app or Windows phone app projects, because you cannot change the activation policy on those platforms.
  2. Add the  element as follows to the application configuration file:
      
        
      
    
  • where  specifies the CLR version that aligns with the .NET Framework version that your app supports. Use the following strings:
    • .NET Framework 1.0: "v1.0.3705"
    • .NET Framework 1.1: "v1.1.4322"
    • .NET Framework 2.0, 3.0, and 3.5: "v2.0.50727"
    • .NET Framework 4 and 4.5 (including point releases such as 4.5.1): "v4.0"
    You can add multiple  elements, listed in order of preference, to specify support for multiple versions of the .NET Framework.




  • Saturday, March 29, 2014

    Introduction to Yield Statement in VB.Net

    The Yield Statement in VB.Net

    The Yield statement returns one element of a collection at a time. The Yield statement is included in an iterator function or Get accessor, which perform custom iterations over a collection.
    You consume an iterator function by using a For Each...Next Statement (Visual Basic) or a LINQ query. Each iteration of the For Each loop calls the iterator function. When aYield statement is reached in the iterator function, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
    An implicit conversion must exist from the type of expression in the Yield statement to the return type of the iterator.
    You can use an Exit Function or Return statement to end the iteration.
    "Yield" is not a reserved word and has special meaning only when it is used in an Iterator function or Get accessor.

    Iterator Functions and Get Accessors

    The declaration of an iterator function or Get accessor must meet the following requirements:
    • It must include an Iterator modifier.
    • The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
    • It cannot have any ByRef parameters.
    • An iterator function can be an anonymous function. For more information
    An iterator function cannot occur in an event, instance constructor, static constructor, or static destructor.

    Exception Handling in Yield 


    Yield statement can be inside a Try block of a Try...Catch...Finally Statement (Visual Basic). A Try block that has a Yield statement can have Catch blocks, and can have aFinally block.
    Yield statement cannot be inside a Catch block or a Finally block.
    If the For Each body (outside of the iterator function) throws an exception, a Catch block in the iterator function is not executed, but a Finally block in the iterator function is executed. A Catch block inside an iterator function catches only exceptions that occur inside the iterator function.

    An Example:
    Sub Main()
        For Each number In Power(2, 8)
            Console.Write(number & " ")
        Next 
        ' Output: 2 4 8 16 32 64 128 256
        Console.ReadKey()
    End Sub 
    
    Private Iterator Function Power(
    ByVal base As Integer, ByVal highExponent As Integer) _
    As System.Collections.Generic.IEnumerable(Of Integer)
    
        Dim result = 1
    
        For counter = 1 To highExponent
            result = result * base
            Yield result
        Next 
    End Function