Search This Blog

Showing posts with label C Sharp Programming. Show all posts
Showing posts with label C Sharp Programming. Show all posts

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 DragEnter, DragLeave, 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.

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.

Saturday, March 29, 2014

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.
A 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

A 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

Thursday, March 27, 2014

C# Programming Fundamentals

C# Programming Fundamentals in Point wise Way 

  • A complete program instruction is called a statement. Each statement ends with a semicolon (;).
  • All objects, variables, and constants must have a specific type.
  • Most of the intrinsic types are used for working with numeric values. You will commonly use int for whole numbers and double or float for fractional values.
  • The char type is used for holding a single character.
  • The bool type can hold only the value true or false.
  • A variable is an instance of a type. You initialize a variable by creating it with an assigned value.
  • You can use the var keyword to create a variable without a type, but only if you assign it immediately. The complier will determine the type of the variable from the value assigned.
  • You can cast a value from one type to another as long as the compiler knows how to turn the original type into the cast-to type. If no information can be lost, you may cast from one type to another implicitly. If information may be lost, you must cast explicitly. You accomplish the cast by prefacing the variable with the name of the type you want to cast to, in parentheses.
  • A constant is similar to a variable, but the value cannot be changed while the program is running. Literal constants are simply values used on their own. Symbolic constants, indicated with the const keyword, are values with assigned names, which you use like variables, but the values cannot change.
  • An enumeration is a value type that consists of a set of named constants.
  • A string object holds a series of characters (such as a word or sentence). A string literal is simply text enclosed by double quotes. You can assign a string to a string variable, just as you would make any other assignment.
  • Extra whitespace (spaces, tabs, and newline characters) is ignored by the compiler, unless it appears within a string.

Introduction To The is and as Operator in C#

The is and as Operator in C#

Sometimes, however, you may not know at compile time whether an object supports a particular interface.

The is operator lets us query whether an object implements an interface (or derives from a base class). The form of the is operator is:
if ( expression is type )
The is operator evaluates true if the expression (which must be a reference type, such as an instance of a class) can be safely cast to type without throwing an exception.
The as operator is similar to is, but it goes a step further. The as operator tries to cast the object to the type, and if an exception would be thrown, it instead returns null:
ICompressible myCompressible = myObject as ICompressible
if ( myCompressible != null )
The is operator is slightly less efficient than using as, so the as operator is slightly preferred over the is operator, except when you want to do the test but not actually do the cast (a rare situation).

Tuesday, March 25, 2014

Async Programming In C#

An Introduction to Async Programming In C#

The Async feature in Visual Studio 2012 RC makes it easy to invoke asynchronous methods.If a method marked with or async modifier, we can use the await operator in the method. When control reaches an await expression in the async method, control returns to the caller, and progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method.
Using asynchronous methods instead of synchronous methods can provide benefits.  Asynchrony makes UI applications more responsive because the UI thread that launches that operation can perform other work.  Asynchrony also improves the scalability of server-based application by reducing the need for threads.

What's the difference between asynchronous programming and using multiple threads to do parallel programming?
In synchronous programming, something doesn't happen until the last thing is done. There may not be any human delays for which Async may be useful, but there are much shorter delays. Think milliseconds. These often are I/O operations like waiting to retrieve something from the hard drive. There are a lot of short delays, so the milliseconds add up to mega-milliseconds, so people watch swirling donuts.
Using multiple threads and the Task Parallel Library can improve things. On a single core processor, while one thread is waiting to get something back from the hard drive, Windows may assign another thread to run on the processor. That makes the whole thing run faster. On multiple core processors, things are even better. Windows may assign one thread to run on one core, and another to run on another.

Friday, March 21, 2014

A Sample Client/Server Chat Program in C#


How to make a sample client/server chat program in C# .Net

This is the sample code for client part of chat program.
Client

using System.IO; 
using System.Net; 
using System; 
using System.Threading; 
using N = System.Net; 
using System.Collections; 
using System.Windows.Forms; 
using System.ComponentModel; 
using System.Runtime.InteropServices; 

class TalkUser { 
    
   static Form talk; 
   static N.Sockets.TcpClient TC; 

   [DllImport("kernel32.dll")] 
   private static extern void ExitProcess(int a); 
    
   public static void Main() { 
       talk = new Form(); 
       talk.Text = "TalkUser - The OFFICIAL TalkServ Client"; 
       talk.Closing += new CancelEventHandler(talk_Closing); 
       talk.Controls.Add(new TextBox()); 
       talk.Controls[0].Dock = DockStyle.Fill; 
       talk.Controls.Add(new TextBox()); 
       talk.Controls[1].Dock = DockStyle.Bottom; 
       ((TextBox)talk.Controls[0]).Multiline = true; 
       ((TextBox)talk.Controls[1]).Multiline = true; 
       talk.WindowState = FormWindowState.Maximized; 
       talk.Show(); 
       ((TextBox)talk.Controls[1]).KeyUp += new KeyEventHandler(key_up); 
       TC = new N.Sockets.TcpClient(); 
       TC.Connect("IP OF A SERVER HERE",4296); 
       Thread t = new Thread(new ThreadStart(run)); 
       t.Start(); 
       while(true) { 
           Application.DoEvents(); 
       } 
   } 
    
   private static void talk_Closing(object s, CancelEventArgs e) { 
       e.Cancel = false; 
       Application.Exit(); 
       ExitProcess(0); 
   } 
    
   private static void key_up(object s,KeyEventArgs e) { 
       TextBox TB = (TextBox)s; 
       if(TB.Lines.Length>1) { 
           StreamWriter SW = new StreamWriter(TC.GetStream()); 
           SW.WriteLine(TB.Text); 
           SW.Flush(); 
           TB.Text = ""; 
           TB.Lines = null; 
       } 
   } 
    
   private static void run() { 
       StreamReader SR = new StreamReader(TC.GetStream()); 
       while(true) { 
           Application.DoEvents(); 
           TextBox TB = (TextBox)talk.Controls[0]; 
           TB.AppendText(SR.ReadLine()+"\r\n"); 
           TB.SelectionStart = TB.Text.Length; 
       } 
   } 
}

This is server part of chat program.

using System.IO; 
using System.Net; 
using System; 
using System.Threading; 
using N = System.Net; 
using System.Collections; 

class TalkServ { 
    
   System.Net.Sockets.TcpListener server; 
   public static Hashtable handles; 
   public static Hashtable handleByConnect; 
    
   public static void Main() { 
       TalkServ TS = new TalkServ(); 
   } 

   public TalkServ() { 
       handles = new Hashtable(100); 
       handleByConnect = new Hashtable(100); 
       server = new System.Net.Sockets.TcpListener(4296); 
       while(true) { 
           server.Start(); 
           if(server.Pending()) { 
               N.Sockets.TcpClient connection = server.AcceptTcpClient(); 
               Console.WriteLine("Connection made"); 
               BackForth BF = new BackForth(connection);             
           } 
       } 
   } 
    
   public static void SendToAll(string name,string msg) { 
       StreamWriter SW; 
       ArrayList ToRemove = new ArrayList(0); 
       N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count];
       TalkServ.handles.Values.CopyTo(tc,0); 
       for(int i=0;i
           try { 
           if(msg.Trim()==""||tc[i]==null) 
               continue; 
           SW = new StreamWriter(tc[i].GetStream()); 
           SW.WriteLine(name + ": " + msg); 
           SW.Flush(); 
           SW = null; 
           } catch(Exception e44) { e44 = e44; 
               string g = (string) TalkServ.handleByConnect[tc[i]]; 
               TalkServ.SendSysMsg("** " + g + " ** HAS LEFT US."); 
               TalkServ.handles.Remove(g); 
               TalkServ.handleByConnect.Remove(tc[i]); 
           } 
       } 
   } 

   public static void SendSysMsg(string msg) { 
       StreamWriter SW; 
       ArrayList ToRemove = new ArrayList(0); 
       N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count];
       TalkServ.handles.Values.CopyTo(tc,0); 
       for(int i=0;i
           try { 
           if(msg.Trim()==""||tc[i]==null) 
               continue; 
           SW = new StreamWriter(tc[i].GetStream()); 
           SW.WriteLine(msg); 
           SW.Flush(); 
           SW = null; 
           } catch(Exception e44) { e44 = e44; 
               TalkServ.handles.Remove(TalkServ.handleByConnect[tc[i]]); 
               TalkServ.handleByConnect.Remove(tc[i]); 
           } 
       } 
   } 
}//end of class TalkServ 

class BackForth { 
   N.Sockets.TcpClient client; 
   System.IO.StreamReader SR; 
   System.IO.StreamWriter SW; 
   string handle; 
    
   public BackForth(System.Net.Sockets.TcpClient c) { 
       client = c; 
       Thread t = new Thread(new ThreadStart(init)); 
       t.Start(); 
   } 
    
   private string GetHandle() { 
       SW.WriteLine("What is your handle? "); 
       SW.Flush(); 
       return SR.ReadLine(); 
   } 
    
   private void run() { 
       try { 
       string l = ""; 
       while(true) { 
           l = SR.ReadLine(); 
           TalkServ.SendToAll(handle,l); 
       } 
       } catch(Exception e44) { Console.WriteLine(e44); } 
   } 
    
   private void init() { 
       SR = new System.IO.StreamReader(client.GetStream()); 
       SW = new System.IO.StreamWriter(client.GetStream()); 
       SW.WriteLine("WELCOME TO TalkServ! Be Nice!"); 
       //SW.WriteLine("What is your handle? "); 
       //SW.Flush(); 
       handle = GetHandle(); 
       while(TalkServ.handles.Contains(handle)) { 
           SW.WriteLine("ERR - Handle already exists!"); 
           handle = GetHandle(); 
       } 
       TalkServ.handles.Add(handle,client); 
       TalkServ.handleByConnect.Add(client,handle); 
       TalkServ.SendSysMsg("** " + handle + " ** HAS JOINED US."); 
       SW.WriteLine("Now Talking.....\r\n-------------------------------"); 
       SW.Flush(); 
       Thread t = new Thread(new ThreadStart(run)); 
       t.Start(); 
   } 
}