Search This Blog

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

    Introduction to SyncLock Statement in VB.Net

    The SyncLock statement in VB.Net

    SyncLock in VB.Net


    The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock prevents each thread from entering the block until no other thread is executing it.
    The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously. If the statements that manipulate the data must go to completion without interruption, put them inside a SyncLock block.
    A statement block protected by an exclusive lock is sometimes called a critical section.
    • Branching. You cannot branch into a SyncLock block from outside the block.
    • Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a SyncLock statement.
      You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock object remain unchanged.
    • You can't use the Await operator in a SyncLock block.
    How SyncLock Statement works in vb.net

    • Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLockstatement.
    • Protected Data. If lockobject is a Shared variable, the exclusive lock prevents a thread in any instance of the class from executing the SyncLock block while any other thread is executing it. This protects data that is shared among all the instances.
      If lockobject is an instance variable (not Shared), the lock prevents a thread running in the current instance from executing the SyncLock block at the same time as another thread in the same instance. This protects data maintained by the individual instance.
    • Acquisition and Release. A SyncLock block behaves like a Try...Finally construction in which the Try block acquires an exclusive lock on lockobject and the Finallyblock releases it. Because of this, the SyncLock block guarantees release of the lock, no matter how you exit the block. This is true even in the case of an unhandled exception.
    • Framework Calls. The SyncLock block acquires and releases the exclusive lock by calling the Enter and Exit methods of the Monitor class in the System.Threadingnamespace.
    Example

    The following example shows a class that maintains a simple list of messages. It holds the messages in an array and the last used element of that array in a variable. The addMessage procedure increments the last element and stores the new message. Those two operations are protected by the SyncLock and End SyncLockstatements, because once the last element has been incremented, the new message must be stored before any other thread can increment the last element again.
    If the simpleMessageCollection class shared one list of messages among all its instances, the variables messageCollection and messageseEnd would be declared as Shared. In this case, the variable msgLock should also be Shared, so that there would be a single lock object used by every instance.
    Class simpleMessageCollection
        Public messagesCollection() As String = New String(100) {}
        Public messagesEnd As Integer = -1
        Private msgLock As New Object 
        Public Sub addMessage(ByVal newMsg As String)
            SyncLock msgLock
                messagesEnd += 1
                If messagesEnd < messagesCollection.Length Then
                    messagesCollection(messagesEnd) = newMsg
                End If 
            End SyncLock 
        End Sub 
    End Class

    The using Keyword/Statement in C# and VB.Net

    All About using Keyword/Statement in C# and VB.Net

    In C#,  using Keyword  can be used in two different ways and are hence referred to differently.
     As a Directive 
    In  this usage, the "using" keyword can be used to include a namespace  in your program.(Mostly used)
    As a Statement
    Using can also be used in a block of code to dispose a IDisposable objects.(less used).
    Example
    A simple and straightforward  approach to connect to a database server and read data would be-
      SqlConnection sqlconnection = new SqlConnection(connectionString);
      SqlDataReader reader = null;
      SqlCommand cmd = new SqlCommand(commandString.  
    sqlconnection);
      
    sqlconnection 
    .Open();
      reader = cmd.ExecuteReader();
           while (reader.Read())
             {
               //Do
             }
      reader.Close();
      
    sqlconnection 
    .Close();
    However, the above given code may generate error.
    If any exception occurs inside while block it throws exception the connection.close() process will not executed due to the exception.To avoid this situation, we can take the help of the try....catch... finally block   by closing the connection inside the finally block or inside the catch block.
    "Using" keyword takes the parameter of type IDisposable.Whenever you are using any IDisposable type object you should use the "using" keyword  to handle automatically when it should close or dispose. Internally using keyword calls the Dispose() method to dispose the IDisposable object.
    So the correct code would be :
    using(SqlConnection sqlconnection= new SqlConnection(connectionString) )
                {
                  SqlCommand cmd = new SqlCommand(commandString, sqlconnection);
              sqlconnection.Open();
                 using (SqlDataReader reader = cmd.ExecuteReader())
                 {
                    while (reader.Read())
                    {
                      //DO
                    }
                 }
               }
     In this code  if any exception occurs then dispose() will be called and connection will closed automatically.

    Using Statement in VB.Net

    Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
    Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.
    Using block has three parts: acquisition, usage, and disposal.
    • Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using statement.
    • Usage means accessing the resources and performing actions with them. The statements between Using and End Using represent the usage of the resources.
    • Disposal means calling the Dispose method on the object in resourcename. This allows the object to cleanly terminate its resources. The End Using statement disposes of the resources under the Using block's control.
    How using statement works in VB.Net

    Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException.
    The scope of every resource variable acquired by the Using statement is limited to the Using block.
    If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one within another.
    If resourcename is Nothing, no call to Dispose is made, and no exception is thrown.
    Example
    The following example creates a file that is named log.txt and writes two lines of text to the file. The example also reads that same file and displays the lines of text.
    Because the TextWriter and TextReader classes implement the IDisposable interface, the code can use Using statements to ensure that the file is correctly closed after the write and read operations.
    Private Sub WriteToFile()
        Using writer As System.IO.TextWriter = System.IO.File.CreateText("myfile.txt")
            writer.WriteLine("This is line one.")
            writer.WriteLine("This is line two.")
        End Using 
    End Sub 
    
    Private Sub ReadFromFile()
        Using reader As System.IO.TextReader = System.IO.File.OpenText("log.txt")
            Dim line As String
    
            line = reader.ReadLine()
            Do Until line Is Nothing
                Console.WriteLine(line)
                line = reader.ReadLine()
            Loop 
        End Using 
    End Sub