Let’s Learn Remoting in .NET 3.5

Remoting is very important part of WCF (Windows Communication Foundation)

Here we are going to write code for retrieving remote machine process details.

  1. First we need create a class i.e. .dll where we will write the functionality of the project.
  2. Secondly we will create a Windows project as Server.
  3. And finally we will create a Windows project as Client.

Step 1:

Create project New Class Library Project which will create .dll file.

Add below code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data ;
using Microsoft.Win32;
namespace RemoteClass
 {
public class Remote:MarshalByRefObject {
  public DataTable Remoteprocesses()
        {
            DataTable ProcessTable = new DataTable();
            ProcessTable.Columns.Add("processno");
            ProcessTable.Columns.Add("ProcessId");
            ProcessTable.Columns.Add("ProcessName");
            int i = 1;
            foreach (System.Diagnostics.Process winProc in
            System.Diagnostics.Process.GetProcesses())
            {
                DataRow myNewRow;
                myNewRow = ProcessTable.NewRow();
                myNewRow["processno"] = i;
                myNewRow["ProcessId"] = winProc.Id;
                myNewRow["ProcessName"] = winProc.ProcessName;
                ProcessTable.Rows.Add(myNewRow);
                i++;
            }
            return ProcessTable;
        }
    }
}

Build this project. Once your have build Project successfully the .dll file will be generated at bin/debug folder location.

Step 2:

Now create a windows application project for developing a “SERVER”. Add reference of Remote class (.dll file) in the project. Add a button and label control on the windows form. As shown in the picture

Now add below code in the .CS file . don’t forget to add Remoting related namespaces in the project and Add the names space System.Runtime.Remoting from References

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            TcpChannel tcpChannel = new TcpChannel(8010);
            ChannelServices.RegisterChannel(tcpChannel,false);
            RemotingConfiguration.
            RegisterWellKnownServiceType(typeof(RemoteClass.Remote),
             "abc",WellKnownObjectMode.SingleCall);
            label1.Text = "Server is running";
        }
    }
}

Build this project.

Step 3:

Now create a windows application project for developing a “CLIENT”. Add reference of Remote class (.dll file) in the project.

Add a button, datagridview and label control on the windows form. As shown in the picture

Now add below code in the .CS file . don’t forget to add Remoting related namespaces in the project and Add it namesspace System.Runtime.Remoting from Reference. Just like Server project. Now on View Button Click add below Code.

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
//Adding the names space System.Runtime.Remoting from References 
namespace Client
{
        public partial class Form1 : Form   {
        RemoteClass.Remote RemoteObject = new RemoteClass.Remote();
        public Form1()
        {
            InitializeComponent();
        }
         private void button1_Click(object sender, EventArgs e)
        {
          RemoteObject = (RemoteClass.Remote)Activator.GetObject
         (typeof(RemoteClass.Remote), "tcp://192.168.16.51:8010/abc");
            DataTable a = RemoteObject.Remoteprocesses();
            dataGridView1.DataSource = a;
        }    }
}

Build this project.

Now let’s test the project. By pressing F5 in Server and Client project…

Here if you are having two machines namely X & Y and you want view the process details of X machine then simply you need to install the Server on the X machine and from Y machine Client you can monitor it.

i Hope u all understand a small example of remoting..if you like this example comment me..

n joy Diving in .NET World…

Shortcuts are for .NET developers

Usually I never recommend taking shortcuts in life, as it is priceless. But shortcuts can be useful for you, if you are a asp.net, vb, c# programmer or web developer who love to work with visual Studio 2003/2005. It will help you in finishing your work more quickly and the saved time can be enjoyed with your friends. I found these while searching the same for myself, and now would happily like to share with others. So here is the Comprehensive list of keyboard shortcuts of Visual Studio Application Programming and Internet Explorer 7(IE7).

[pdf] [size: 120KB] VisualStudio.NET_2005_Keyboard_Shortcuts.pdf
[pdf] [size:1.5MB] VisualBasic_2005_keyboard_shortcuts.pdf
[pdf] [size:1.4MB] VCSharp_2005_keyboard_shortcuts.pdf
[pdf] [size:41KB] MostUsed_Shortcuts_VisualStudio2003_2005.pdf
[pdf] [size:760KB] InternetExplorer7_shortcutRefrence.pdf

To get Microsoft list of Complete list of default setting Visual Studio shortcuts keys, go to: http://msdn2.microsoft.com/en-us/library/xte2hh6a(vs.71).aspx
All of the download are available in PDF format, just download them and Speed up the growth of Information technology.

.NET Framework 3.5 (Short Explanation for Interview)

The .NET Framework 3.5 is an integral Windows component that supports building and running the next generation of applications and Web services. The key components of the .NET Framework are the common language runtime (CLR) and the .NET Framework class library, which includes ADO.NET, ASP.NET, Windows Forms, and Windows Presentation Foundation (WPF). The .NET Framework provides a managed execution environment, simplified development and deployment, and integration with a wide variety of programming languages. For a brief introduction to the architecture of the .NET Framework, see .NET Framework Conceptual Overview.

 The following illustration shows the relationship of the common language runtime and the class library to your applications and to the overall system. The illustration also shows how managed code operates within a larger architecture.

 Enhancement from .NET Framework 2.0 to .NET Framework 3.5 are Mention below:

 .NET Framework Class Library

Supplies syntax, code examples, and related information for each class contained in the .NET Framework namespaces.

Quick Technology Finder

Provides a table of links to the main technology areas of the .NET Framework.

What’s New in the .NET Framework

Describes key features that have been added or modified in the latest versions of the .NET Framework.

Overview of the .NET Framework

Describes key .NET Framework concepts such as the common language runtime, the common type system (CTS), cross-language interoperability, managed execution, assemblies, and security.

Core Development Technologies

Explains common programming tasks that apply to a range of .NET Framework applications. Includes topics such as accessing data, file and stream I/O, configuration, encoding, deployment, and debugging.

Advanced Development Technologies

Provides information about sophisticated development tasks and techniques in the .NET Framework.

Security in the .NET Framework

Provides information about the classes and services in the .NET Framework that facilitate secure application development.

ASP.NET Portal

Provides links to documentation about ASP.NET applications, Web Forms, and Web services.

Windows Forms Portal

Provides links to documentation about common programming tasks in Windows Forms applications.

.NET Compact Framework

Introduces the .NET Framework-based, hardware-independent environment for running applications on resource-constrained computing devices.

Windows Presentation Foundation

Provides information about developing applications using Windows Presentation Foundation (WPF).

Windows Communication Foundation for Applications

Provides information on the Windows Communication Foundation (WCF) programming model for building service-oriented applications.

Windows CardSpace

Provides information about CardSpace, which is Microsoft’s implementation of an identity metasystem.

Windows Workflow Foundation

Provides information on the framework, programming model, and tools for Windows Workflow Foundation (WF).

General Reference for the .NET Framework

Provides reference information related to the .NET Framework. Includes sections on languages and compilers, tools, technical references, and a glossary of terms.

Tools (.NET Framework)

Provides information about tools that make it easier for you to create, deploy, and manage applications and components that target the .NET Framework.

Samples (.NET Framework Technologies)

Provides samples that illustrate various aspects of the .NET Framework.

Enjoy depth of .NET…

Create Custom Control in C#.NET

DOWNLOAD EXAMPLE HERE

Contents

Overview

Types of Custom Controls

User controls
Inherited controls
Owner-drawn controls
Extender providers

Communication between User Controls and subscribing Applications

Publising and Subscribing Events
Events and Delegates

Submit Button User Control  

Create the Submit Button User Control
Using the Submit User Control in a Windows Application

Login Validation User Control  

Create the Login Validation User Control
Using the Login Validation User Control in a Windows Application

Format Mask Control  

Create the Format Mask Control
Using the Edit Mask User Control in a Windows Application

Toggle Button User Control

Create the Toggle Button User Control
Using the Toggle Button User Control in a Windows Application

 

 


Overview

 

 

Embedding user controls in a Windows form is just like adding a simple button or text box that are already provided with .NET. These basic controls were written essentially like you code your own controls. Typically the controls you design are to be used in multiple forms or to modularize your code. These reasons help reduce the amount of code you have to type as well as make it easier for you to change your implementation. There should almost never be any reason to duplicate code because it leaves a lot of room for bugs. So, implementing functionality specific to your control in the control’s source code is a good idea. This reduces code duplication as well as modularize your code, which is a good programming guideline.

Custom controls are a key theme in .NET development. They can help your programming style by improving encapsulation, simplifying a programming model, and making user interface more “pluggable” (i.e., making it easier to swap out one control and replace it with a completely different one without rewriting your form code). Of course, custom controls can have other benefits, including the ability to transform a generic window into a state-of-the-art modern interface.

Generally, developers tackle custom control development for one of three reasons:

  • To create controls that abstract away unimportant details and are tailored for a specific type of data. You will see  with custom ListView and TreeView examples.

  • To create controls that provide entirely new functionality, or just combine existing UI elements in a unique way.

  • To create controls with a distinct original look, or ones that mimic popular controls in professional applications (like Microsoft’s Outlook bar) that aren’t available to the masses.

In .NET, creating a custom control is as easy as creating an ordinary class. You simply inherit from the best possible ancestor and add the specific features you need. Best of all, you can create a custom control class as part of an existing project, and then decide later to place it in a separate assembly that can be shared with other programmers.

Types of Custom Controls

Developers often make a distinction between three or four types of controls:

  • User controls are the simplest type of control. They inherit from the System.Windows.Forms.UserControl class, and follow a model of composition. Usually, user controls combine more than one control in a logical unit (like a group of text boxes for entering address information).

  • Inherited controls are generally more powerful and flexible. With an inherited control, you choose the existing .NET control that is closest to what you want to provide. Then, you derive a custom class that overrides or adds properties and methods. The examples you’ve looked at so far in this book, including the custom TreeViews and ListViews, have all been inherited controls.

  • Owner-drawn controls generally use GDI+ drawing routines to generate their interfaces from scratch. Because of this, they tend to inherit from a base class like System.Windows.Forms.Control. Owner-drawn controls require the most work and provide the most customizable user interface.

  • Extender providers, which aren’t necessarily controls at all. These components add features to other controls on a form, and provide a remarkable way to implement extensible user interface.

Communication between User Controls and subscribing Applications

Because the basic .NET controls are contained within our user control, events are not fired for the contained applications. Our user control is treated like any other and must implement it’s own properties (besides those inherited from System.Windows.Forms.Control) and events.

Publising and Subscribing Events

The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of “publisher and subscribers.” In this model, you have publishers who will do some logic and publish an “event.” Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified. The following figure shows this mechanism.

1 

Events and Delegates

At the heart of Events in C# are Delegates. When an object generates an events, it must send the event out. The way that events are dispatched is through the use of delegates. Let’s look how Events are declared in C#.

[attributes] [modifier] event type member-name;

       Modifier is any allowable scope modifier.

       Type must be a delegate.

       Member-name is the Name of the Event with which you will refer to the event in your code.

The important thing to note here is the delegate type that events should use. In the strictest sense, the delegate can be any legal delegate. But there is a convention that you should follow and is one that Window Forms uses. By Convention, the delegate should accept two parameters:

  1. The object that generated the event
  2. The parameters for the specific event

An example of an event / delegate is as follows:

public delegate void SubmitClickedHandler(object sender, EventArgs e);
public event SubmitClickedHandler SubmitClicked;

SubmitClickedHandler is the name of the delegate, sender is self explanatory. EventArgs is defined under the System namespace and is a very plain class. SubmitClicked is the name of the event, which is published to the Subscriber.

Submit Button User Control

Create the Submit Button User Control

The control we will create will contain a text box for your name and a button that will fire an event. To begin, open Visual Studio .NET and begin a new C#  Windows Control Library. You may name it whatever you like, for this sample the project name will be SubmitButton.

2 

using System;

using System.Collections;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Windows.Forms;

namespace Akadia

{

    namespace SubmitButton

    {

        // User Control which contain a text box for your

        // name and a button that will fire an event.

        public class SubmitButtonControl : System.Windows.Forms.UserControl

        {

            private System.Windows.Forms.TextBox txtName;

            private System.Windows.Forms.Label lblName;

            private System.Windows.Forms.Button btnSubmit;

            private System.ComponentModel.Container components = null;

            // Declare delegate for submit button clicked.

            //

            // Most action events (like the Click event) in Windows Forms

            // use the EventHandler delegate and the EventArgs arguments.

            // We will define our own delegate that does not specify parameters.

            // Mostly, we really don’t care what the conditions of the

            // click event for the Submit button were, we just care that

            // the Submit button was clicked.

            public delegate void SubmitClickedHandler();

            // Constructor           public SubmitButtonControl()

            {

                // Create visual controls

                InitializeComponent();

            }

            // Clean up any resources being used.

            protected override void Dispose( bool disposing )

            {

                if( disposing )

                {

                    if( components != null )

                        components.Dispose();

                }

                base.Dispose( disposing );

            }

            …..

            …..

            // Declare the event, which is associated with our

            // delegate SubmitClickedHandler(). Add some attributes

            // for the Visual C# control property.

            [Category("Action")]

            [Description("Fires when the Submit button is clicked.")]

            public event SubmitClickedHandler SubmitClicked;

            // Add a protected method called OnSubmitClicked().

            // You may use this in child classes instead of adding

            // event handlers.

            protected virtual void OnSubmitClicked()

            {

                // If an event has no subscribers registerd, it will

                // evaluate to null. The test checks that the value is not

                // null, ensuring that there are subsribers before

                // calling the event itself.

                if (SubmitClicked != null)

                {

                    SubmitClicked();  // Notify Subscribers 

                }

            }

            // Handler for Submit Button. Do some validation before

            // calling the event.

            private void btnSubmit_Click(object sender, System.EventArgs e)

            {

                if (txtName.Text.Length == 0)

                {

                    MessageBox.Show(“Please enter your name.”);

                }

                else

                {

                    OnSubmitClicked();

                }

            }

            // Read / Write Property for the User Name. This Property

            // will be visible in the containing application.

            [Category("Appearance")]

            [Description("Gets or sets the name in the text box")]

            public string UserName

            {

                get { return txtName.Text; }

                set { txtName.Text = value; }

            }

        }

    }

}

Using the Submit User Control in a Windows Application

Using the control in a Windows form is trivial. It’s just like adding any other control like a button or a DataGrid. First, create a new Windows Application project named: TestApp. Add a reference to the Submit Button User Control DLL named: SubmitButton.dll. Now you are ready to customize the Toolbox: Right-Click the Toolbox, .NET Framework Components, Browse, select the SubmitButton.dll.

3 

The Submit Button User Control is now added to the Toolbox and can be inserted in Windows Form as any other control. Now we want to handle the SubmitClicked event for the user control. This will simply close the form. The control itself will take care of validation and the event won’t be fired unless the text is valid. Click on the lightning-looking button (for events) with the control selected and you’ll see the event, SubmitClicked, listed under the “Action” category. Click on it once and you’ll see the description we added previously. Now double-click it and VS.NET will add an event handler SubmitClicked() which displays the name from the user control and close the form when the event is fired.

4 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace TestApp

{

   // Test Application for the Submit Button User Control

    public class TestApp : System.Windows.Forms.Form

    {

        private Akadia.SubmitButton.SubmitButtonControl submitButtonControl;

        private System.ComponentModel.Container components = null;

        ….

        …..

        [STAThread]

        static void Main()

        {

            Application.Run(new TestApp());

        }

        // Handle the SubmitClicked Event

        private void SubmitClicked()

        {

            MessageBox.Show(String.Format(“Hello, {0}!”,

                submitButtonControl.UserName));

            this.Close();

        }

    }

}

Login Validation User Control

Create the Login Validation User Control

The following sample shows how to implement a Login user control. When the user clicks the Login button, the control will validate the data entered by the user. If the user has left either the User name or the Password text boxes empty, the loginError validation control will display an error icon against the offending control. The Password will then be checked by a “secret algorithm”, if the Password is valid, the user control will raise an event called LoginSuccess; otherwise it will fire a different event called LoginFailed.

In this sample we use the predefined System.EventHandler delegate. This delegate is useful if you want to define an event that has no additional data. The event will be passed an empty System.EventArgs parameter instead. This is the delegate used by many of the Windows Forms.

dotnet_user_control_5 

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace Akadia
{
    namespace LoginControl
    {
        // Implementation of a Login User Control
        public class LoginControl : System.Windows.Forms.UserControl
        {
            private System.Windows.Forms.Label lblUserName;
            private System.Windows.Forms.Label lblPassword;
            private System.Windows.Forms.TextBox txtUserName;
            private System.Windows.Forms.TextBox txtPassword;
            private System.Windows.Forms.Button btnLogin;
            private System.Windows.Forms.ErrorProvider erpLoginError;
            private System.Windows.Forms.StatusBar stbMessage;
            private System.ComponentModel.Container components = null;
 
            // Here we use the predefined System.EventHandler delegate.
            // This delegate is useful if you want to define an event
            // that has no additional data. The event will be passed an
            // empty System.EcentArgs parameter instead. This is the
            // delegate used by many of the Windows Forms.
            public delegate void EventHandler(Object sender, EventArgs e);
            public event EventHandler LoginSuccess;
            public event EventHandler LoginFailed;
 

            // Constructor
            public LoginControl()
            {
                InitializeComponent();
            }
 
            ….
            ….
 
            // This is the very simple Login Check Validation
            // The Password mus be … “secret” …..
            private bool LoginCheck(string pName, string pPassword)
            {
                return pPassword.Equals(“secret”);
            }
 
            // Validate Login, in any case call the LoginSuccess or
            // LoginFailed event, which will notify the Application’s
            // Event Handlers.
            private void loginButtonClicked(object sender, System.EventArgs e)
            {
                // User Name Validation
                if (txtUserName.Text.Length == 0)
                {
                    erpLoginError.SetError(txtUserName,”Please enter a user name”);
                    stbMessage.Text = “Please enter a user name”;
                    return;
                }
                else
                {
                    erpLoginError.SetError(txtUserName,”");
                    stbMessage.Text = “”;
                }
 
                // Password Validation
                if (txtPassword.Text.Length == 0)
                {
                    erpLoginError.SetError(txtPassword,”Please enter a password”);
                    stbMessage.Text = “Please enter a password”;
                    return;
                }
                else
                {
                    erpLoginError.SetError(txtPassword,”");
                    stbMessage.Text = “”;
                }
 
                // Check Password
                if (LoginCheck(txtUserName.Text, txtPassword.Text))
                {
                    // If there any Subscribers for the LoginSuccess
                    // Event, notify them …
                    if (LoginSuccess != null)
                    {
                        LoginSuccess(this, new System.EventArgs());
                    }
                }
                else
                {
                    // If there any Subscribers for the LoginFailed
                    // Event, notify them …
                    if (LoginFailed != null)
                    {
                        LoginFailed(this, new System.EventArgs());
                    }
                }
            }
 
            // Read-Write Property for User Name Label
            public string LabelName
            {
                get
                {
                    return lblUserName.Text;
                }
                set
                {
                    lblUserName.Text = value;
                }
            }
 
            // Read-Write Property for User Name Password
            public string LabelPassword
            {
                get
                {
                    return lblPassword.Text;
                }
                set
                {
                    lblPassword.Text = value;
                }
            }
 
            // Read-Write Property for Login Button Text
            public string LoginButtonText
            {
                get
                {
                    return btnLogin.Text;
                }
                set
                {
                    btnLogin.Text = value;
                }
            }
 
            // Read-Only Property for User Name
            [Browsable(false)]
            public string UserName
            {
                set
                {
                    txtUserName.Text = value;
                }
            }
 
            // Read-Only Property for Password
            [Browsable(false)]
            public string Password
            {
                set
                {
                    txtPassword.Text = value;
                }
            }

        }
    }
}

Using the Login Validation User Control in a Windows Application

Create a new Windows Application project named: TestApp. Add a reference to the Login Validation User Control DLL named: LoginControl.dll. Now you are ready to customize the Toolbox: Right-Click the Toolbox, .NET Framework Components, Browse, select the LoginControl.dll.

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace TestApp
{
    // Test Application for the Login Validation User Control
    public class TestApp : System.Windows.Forms.Form
    {
        private Akadia.LoginControl.LoginControl loginControl;
        private System.ComponentModel.Container components = null;
 
        ….
        ….
 
        [STAThread]
        static void Main()
        {
            Application.Run(new TestApp());
        }
 
        // This Event is fired by the Login Validation User Control
        private void LoginFailed(object sender, System.EventArgs e)
        {
            MessageBox.Show(“Login falied ….”, “Login Validation”,
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

 
        // This Event is fired by the Login Validation User Control
        private void LoginSuccess(object sender, System.EventArgs e)
        {
            MessageBox.Show(“Login success ….”, “Login Validation”,
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

    }
}

Format Mask Control

Create the Format Mask Control

An inherited control example is one for a custom masked text box. A masked text box is one that automatically formats the user’s input into the correct format. For example, it may add dashes or brackets to make sure it looks like a phone number. This task is notoriously difficult. One useful tool is Microsoft’s masked edit text box, which is provided as an ActiveX control with previous versions of Visual Studio.

The example of a masked text box is important because it demonstrates how features (rather than data) might be added to an existing control by subclassing. The example is still quite limited-notably, it restricts deletions and the
use of the arrow keys. Tracking the cursor position, which is required to allow inline masked edits, results in a good deal of tedious code that only obscures the point.

 dotnet_user_control_7

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace Akadia
{
    namespace FormatMask
    {
        // Extended User Control to implement an Edit Mask Text Box
        public class EditMask : System.Windows.Forms.TextBox
        {
            // Fields
            private string _mask;
 
            // Properties
            public string Mask
            {
                get { return _mask; }
                set
                {
                    _mask = value;
                    this.Text = “”;
                }
            }
 
            // To use the masked control, the application programmer chooses
            // a mask and applies it to the Mask property of the control.
            // The number sign (#) represents any number, and the period (.)
            // represents any letter. All other characters in the mask
            // are treated as fixed characters, and are inserted automatically
            // when needed. For example, in the phone number mask (###) ###-####
            // the first bracket is inserted automatically when the user types
            // the first number.
            protected override void OnKeyPress(KeyPressEventArgs e)
            {
                if (Mask != “”)
                {
                    // Suppress the typed character.
                    e.Handled = true;
 
                    string newText = this.Text;
 
                    // Loop through the mask, adding fixed characters as needed.
                    // If the next allowed character matches what the user has
                    // typed in (a number or letter), that is added to the end.
                    bool finished = false;
                    for (int i = this.SelectionStart; i < _mask.Length; i++)
                    {
                        switch (_mask[i].ToString())
                        {
                            case “#” :
                                // Allow the keypress as long as it is a number.
                                if (Char.IsDigit(e.KeyChar))
                                {
                                    newText += e.KeyChar.ToString();
                                    finished = true;
                                    break;
                                }
                                else
                                {
                                    // Invalid entry; exit and don’t change the text.
                                    return;
                                }
                            case “.” :
                                // Allow the keypress as long as it is a letter.
                                if (Char.IsLetter(e.KeyChar))
                                {
                                    newText += e.KeyChar.ToString();
                                    finished = true;
                                    break;
                                }
                                else
                                {
                                    // Invalid entry; exit and don’t change the text.
                                    return;
                                }
                            default :
                                // Insert the mask character.
                                newText += _mask[i];
                                break;
                        }
                        if (finished)
                        { break; }
                    }
 
                    // Update the text.
                    this.Text = newText;
                    this.SelectionStart = this.Text.Length;
                }
                // base.OnKeyPress(e);
            }
 
            // Stop special characters.
            protected override void OnKeyDown(KeyEventArgs e)
            {
                e.Handled = true;
            }
        }
    }
}

Using the Edit Mask User Control in a Windows Application

Create a new Windows Application project named: TestApp. Add a reference to the Edit Mask User Control DLL named: FormatMask.dll. Now you are ready to customize the Toolbox: Right-Click the Toolbox, .NET Framework Components, Browse, select the FormatMask.dll.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace TestApp
{
    // Test Application for the Edit mask User Control
    public class TestApp : System.Windows.Forms.Form
    {
        private Akadia.FormatMask.EditMask editMask;
        private System.Windows.Forms.Label lblText;
        private System.ComponentModel.Container components = null;
 
        public TestApp()
        {
            InitializeComponent();
        }
        ……
        private void InitializeComponent()
        {
            ….
            this.editMask.Location = new System.Drawing.Point(93, 63);
            this.editMask.Mask = “[###]-(##)-#####”;
            this.editMask.Name = “editMask”;
            this.editMask.TabIndex = 0;
            ….
        }
 
        static void Main()
        {
            Application.Run(new TestApp());
        }
    }
}

Toggle Button User Control

Create the Toggle Button User Control

The Toggle Button User Control is an inherited control.  When the user clicks a toggle Button, the Text and BackColor properties should be set according to the Checked state of the button. The natural place to do this is the Click event. However, keep in mind that you only want to extend the default Click event supplied with the CheckBox class rather than replacing is. In the .NET Framework documentation, you will be notice that controls typically have a protected OnXXX method that raises each event (where XXX is the name of the event) – for example the Click event is raised by the OnClick method. The Control call these methods when an event occurs. If you want to extend the Click event, the Trick is therefore to override the OnClick method.

If the Appearance value is set to Appearance.Normal, then the check box has a typical appearance. If the value is set to Button, the check box appears like a toggle button, which may be toggled to an up or down state.

 dotnet_user_control_8

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace Akadia
{
    namespace ToggleButton
    {
        // The ToggleButton class is inherited from the
        // System.Windows.Forms.CheckBox Class
        public class ToggleButton : System.Windows.Forms.CheckBox
        {
            // Fields
            private string _checkedText;
            private string _uncheckedText;
            private Color _checkedColor;
            private Color _uncheckedColor;
 
            // Constructor
            public ToggleButton()
            {
                // If Appearance value is set to Appearance.Normal,
                // the check box has a typical appearance.
                // If the value is set to Button, the check box appears
                // like a toggle button, which may be toggled to
                // an up or down state.
                this.Appearance = Appearance.Button;
 
                // Set Default toggled Text
                this._checkedText = “Checked”;
                this._uncheckedText = “Unchecked”;
 
                // Set Default toggled Color
                this._checkedColor = Color.Gray;
                this._uncheckedColor = this.BackColor;
            }
 
            // Public Properties, can be accessed in Property Panel
            public string CheckedText
            {
                get { return this._checkedText; }
                set { this._checkedText = value; }
            }
 
            public string UncheckedText
            {
                get { return this._uncheckedText; }
                set { this._uncheckedText = value; }
            }
 
            public Color CheckedColor
            {
                get { return this._checkedColor; }
                set { this._checkedColor = value; }
            }
 
            public Color UncheckedColor
            {
                get { return this._uncheckedColor; }
                set { this._uncheckedColor = value; }
            }
 
            // When the user clicks a toggle Button, the Text and
            // BackColor properties should be set according to the Checked
            // state of the button. The natural place to do this is
            // the Click event. However, keep in mind that you only
            // want to extend the default Click event supplied with
            // the CheckBox class rather than replacing is. In the .NET
            // Framework documentation, you will be notice that controls
            // typically have a protected OnXXX method that raises each
            // event (where XXX is the name of the event) – for example
            // the Click event is raised by the OnClick method. The Control
            // call these methods when an event occurs. If you want to
            // extend the Click event, the Trick is therefore to override
            // the OnClick method.
            protected override void OnClick(EventArgs e)
            {
                base.OnClick(e); // Call the CheckBox Baseclass
 
                // Set Text and Color according to the
                // current state
                if (this.Checked)
                {
                    this.Text = this._checkedText;
                    this.BackColor = this._checkedColor;
                }
                else
                {
                    this.Text = this._uncheckedText;
                    this.BackColor = this._uncheckedColor;
                }
            }
        }
    }
}

Using the Toggle Button User Control in a Windows Application

Create a new Windows Application project named: TestApp. Add a reference to the Toggle Button User Control DLL named: ToggleButton.dll. Now you are ready to customize the Toolbox: Right-Click the Toolbox, .NET Framework Components, Browse, select the ToggleButton.dll.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace TestApp
{
    // Test Application for the toggled CheckBox und Button
    public class TestApp : System.Windows.Forms.Form
    {
        private Akadia.ToggleButton.ToggleButton btnToggle1;
        private Akadia.ToggleButton.ToggleButton btnToggle2;
        private Akadia.ToggleButton.ToggleButton btnToggle3;

        private System.Windows.Forms.Label lblText1;
        private System.Windows.Forms.Label lblText2;
        private Akadia.ToggleButton.ToggleButton btnToggle4;
        private System.ComponentModel.Container components = null;
 
        public TestApp()
        {
            InitializeComponent();
 
            // Set Appearance to CheckBox
            btnToggle1.Appearance = Appearance.Normal;
            btnToggle2.Appearance = Appearance.Normal;

        }
        ……
        private void InitializeComponent()
        {
            this.btnToggle1 = new Akadia.ToggleButton.ToggleButton();
            this.btnToggle2 = new Akadia.ToggleButton.ToggleButton();
            this.btnToggle3 = new Akadia.ToggleButton.ToggleButton();

            …..
        }
 
        static void Main()
        {
            Application.Run(new TestApp());
        }
    }
}

SOCKET PROGRAMMING IN C#.NET

We always Treat Socket Programming as Complex programming but if the concept are clear then it will just like doing ADO.NET code.. here i want to introduce a small example where you will understand the the NAMESPACE and the CLASSES need to do the Socket programming….System.NET.Sockets this is the main namespace is needed here…kindly go through the basic concept about the Socket Programming.. 

Inter-Process Communication i.e. the capability of two or more physically connected machines to exchange data, plays a very important role in enterprise software development. TCP/IP is the most common standard adopted for such communication. Under TCP/IP each machine is identified by a unique 4 byte integer referred to as its IP address (usually formatted as 192.168.0.101).

Though IPAddress allows to identify machines in the network, each machine may host multiple applications which use network for data exchange. Under TCP/IP, each network oriented application binds itself to a unique 2 byte integer referred to as its port-number which identifies this application on the machine it is executing. The data transfer takes place in the form of byte bundles called IP Packets or Datagrams. The size of each datagram is 64 KByte and it contains the data to be transferred, the actual size of the data, IP addresses and port-numbers of sender and the prospective receiver. Once a datagram is placed on a network by a machine, it will be received physically by all the other machines but will be accepted only by that machine whose IP address matches with the receiver�s IP address in the packet. Later on, this machine will transfer the packet to an application running on it which is bound to the receiver’s port-number present in the packet.

TCP/IP suite actually offers two different protocols for data exchange. The Transmission Control Protocol (TCP) is a reliable connection oriented protocol while the User Datagram Protocol (UDP) is not very reliable (but fast) connectionless protocol.

This is the simple example I am going to explain here in which the client server communication is takes place through the socket programming. If you need more examples for reference, kindly email me.

First we will create a program for Server Application
Create a console project as “Server”
Add following namespace which are essential for Socket Programming:

using System.Net;
using System.Net.Sockets;

Add below code in the main method:

static void Main(string[ ] args)
{
try
{
IPAddress ipAd = IPAddress.Parse(“192.168.10.51″);
//use local m/c IP address, and use the same in the client
TcpListener myList = new TcpListener(ipAd, 8001);
myList.Start();
Console.WriteLine(“The server is running at port 8001…”);
Console.WriteLine(“The local End point is :” + myList.LocalEndpoint);
Console.WriteLine(“Waiting for a connection…..”);
Socket s = myList.AcceptSocket();
Console.WriteLine(“Connection accepted from ” +
s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine(“Recieved…”);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(“The string was recieved by the server.”));
Console.WriteLine(“\\nSent Acknowledgement”);
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine(“Error….. ” + e.Message);
}
 Console.ReadLine();
}

Chatserver

Create a console project as “Client”, Add following namespace which are essential for Socket Programming:

 using System.Net;

using System.Net.Sockets;

Add below code in the main method:

     static void Main(string[] args) {

            try     {

                TcpClient tcpclnt = new TcpClient();

                Console.WriteLine(“Connecting…..”);

                tcpclnt.Connect(“192.168.10.51”, 8001);

 // use the ipaddress as in the server program

                 Console.WriteLine(“Connected”);

                Console.Write(“Enter the string to be transmitted : “);

                String str = Console.ReadLine();

                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();

                byte[] ba = asen.GetBytes(str);

                Console.WriteLine(“Transmitting…..”);

                stm.Write(ba, 0, ba.Length);

                byte[] bb = new byte[100];

                int k = stm.Read(bb, 0, 100);

                for (int i = 0; i < k; i++)

                Console.Write(Convert.ToChar(bb[i]));

                tcpclnt.Close();

            }

            catch (Exception e)      {

                Console.WriteLine(“Error….. “ + e.StackTrace);

            }

            Console.ReadLine();

        }

chatclient1

Now run the server Program you will see the below screen:

run1

Now run the Client Program you will see the below screen, now enter the test you want to transfer.

 run2

Now see the Server Programm you will receive the text you have transferred from Client Program.

run3

This Program you can Run on the remote machine.

Comment  me in case of BUG…..

 You can Download Above Example from Here

Thank you.

HAPPY PROGRAMMING….

Introduction to Neural Networks for C#

Make An Advanced Notepad In C#

C# Network Development Programming

Reading & Writing Barcodes

NEW RELEASE “.NET FRAMEWORK 4.0″ FEATURES

This post contains information about key features and improvements in the .NET Framework version 4 Beta 1. This topic does not provide comprehensive information about all new features and is subject to change.The new features and improvements are described in the following sections:

Content :

1 Common Language Runtime (CLR)
2 Base Class Libraries
3 Networking
4 Web
5 Client
6 Data
7 Communications
8 Workflow

1. Common Language Runtime (CLR)

The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.

* Security

The .NET Framework 4 Beta 1 provides simplifications, improvements, and expanded capabilities in
the security model. For more information, see Security Changes in the .NET Framework 4.

* Parallel Computing

The .NET Framework 4 Beta 1 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.

* Performance and Diagnostics

In addition to the following features, the .NET Framework 4 Beta 1 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.

* ETW Events

You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:

Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.

* Code Contracts

Code contracts let you specify contractual information that is not represented by a method’s or type’s signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.

The applicable scenarios include the following:

  • Perform static bug finding, which enables some bugs to be found without executing the code.
  • Create guidance for automated testing tools to enhance test coverage.
  • Create a standard notation for code behavior, which provides more information for documentation.
* Lazy Initialization

With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.

* Dynamic Language Runtime

The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.

* In-Process Side-by-Side Execution

In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4 Beta 1 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.

* Interoperability

New interoperability features and improvements include the following:

  • You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
  • You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.
* Profiling

In the .NET Framework 4 Beta 1, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.

* Garbage Collection

The .NET Framework 4 Beta 1 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog. 

* Covariance and Contravariance

Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.

2. Base Class Libraries

The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.

* Collections and Data Structures

Enhancements in this area include the new System.Numerics..::.BigInteger structure, the System.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.

* BigInteger

The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

* SortedSet Generic Class

The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.

The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements the ISet<(Of <(T>)>) interface.

* Tuples

A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4 Beta 1 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.

* Exceptions Handling

The .NET Framework 4 Beta 1 class library contains the new System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions. 

* Corrupted State Exceptions

The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.

Alternatively, you can add the following setting to an application’s configuration file:

legacyCorruptedStateExceptionsPolicy=true

* I/O

The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.

* File System Enumeration Improvements

New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.

There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.

* Memory-Mapped Files

The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.

* Isolated Storage Improvements

Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.

* Compression Improvements

The compression algorithms for the System.IO.Compression..::.DeflateStream and System.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.

* Reflection

The .NET Framework 4 Beta 1 provides the capability to monitor the performance of your application domains.

* Application Domain Resource Monitoring

Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4 Beta 1, you can get processor usage and memory usage estimates per application domain.

Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.

For more information, see the <appDomainResourceMonitoring> Element, and the following properties in the AppDomain class:

* 64-bit View and Other Registry Improvements

Windows registry improvements include the following:

* Threading

General threading improvements include the following:

  • The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
  • You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.

The following sections describe new threading features.

* Unified Model for Cancellation

The .NET Framework 4 Beta 1 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.

* Thread-Safe Collection Classes

The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).

* Synchronization Primitives

New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.

3. Networking

Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.

4. Web

The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.

* ASP.NET Core Services

ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.

* ASP.NET Web Forms

Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:

  • The ability to set meta tags.
  • More control over view state.
  • Easier ways to work with browser capabilities.
  • Support for using ASP.NET routing with Web Forms.
  • More control over generated IDs.
  • The ability to persist selected rows in data controls.
  • More control over rendered HTML in the FormView and ListView controls.
  • Filtering support for data source controls.
* Dynamic Data

For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:

  • Automatic validation that is based on constraints defined in the data model.
  • The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.
* Visual Web Developer Enhancements

The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup code examples, and features a redesigned version of IntelliSense for JScript. In addition, two new deployment features called Web packaging and One-Click Publish make deploying Web applications easier.

5. Client

The following sections describe new features in Windows Presentation Foundation (WPF) and Managed Extensibility Framework (MEF).

* Windows Presentation Foundation

In the .NET Framework 4 Beta 1, Windows Presentation Foundation (WPF) contains changes and improvements in many areas. This includes controls, graphics, and XAML.

For more information, see What’s New in Windows Presentation Foundation Version 4.

* Managed Extensibility Framework

The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 Beta 1 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.

For more information, see Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.

6. Data

For more information, see What’s New in ADO.NET.

* Expression Trees

Expression trees are extended with new types that represent control flow, for example, LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.

7. Communications

Windows Communication Foundation (WCF) provides the new features and enhancements described in the following sections.

* Support for WS-Discovery

The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).

* Standard Endpoints

Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixed IMetadataExchange contract.

* Workflow Services

With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.

  1. Workflow

Windows Workflow Foundation (WF) in .NET Framework 4 Beta 1 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.

* Workflow Activity Model

The activity is now the base unit of creating a workflow, instead of using the SequentialWorkflowActivity or StateMachineWorkflowActivity classes. The WorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.

* Richer Composite Activity Options

The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.

* Expanded Built-in Activity Library

New features of the activity library include the following:

  • Data access activities for interacting with ODBC data sources.
  • New flow control activities such as DoWhile, ForEach, and ParallelForEach.
  • Activities for interacting with PowerShell and SharePoint.
* Enhanced Persistence and Unloading

Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.

* Improved Ability to Extend WF Designer Experience

The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when re-hosting the WF Designer outside Visual Studio. It also provides easier mechanisms for creating custom activity designers. For more information, see Extending the Workflow Designer.