Example code: Chat application




Скачать 281.96 Kb.
НазваниеExample code: Chat application
страница1/5
Дата26.09.2012
Размер281.96 Kb.
ТипДокументы
  1   2   3   4   5
Example code: Chat application:


Before I start bombarding people with the inner mechanisms of the attached WPF/WCF application, shall we have a quick look at the finished product? There are 3 main areas within the attached demo application:

A login screen



A main window, from which the user can choose who to chat with:



And a window where chatters may openly chat:



The application is based on using Visual Studio 2005 with The Visual Studio Designer for WPF installed, or using Expression BLEND and Visual Studio 2005 combination, or Wordpad if you prefer to write stuff in that. Obviously, as it's a WPF/WCF application, you will also need the .NET 3.0 Framework. This application will cover the following concepts:

  • WCF

    • The new service orientated attributes

    • The use of interfaces

    • The use of callbacks

    • Asynchronous delegates

    • Creating the proxy

  • WPF

    • Styles

    • Templates

    • Animations

    • Databinding

    • Multithreading a WPF application

However, this application is not really that orientated to WPF, as that is covered in numerous other WPF articles at The Code Project. The WPF stuff is really just a wrapper around the WCF article, which is the real guts of this article. Although there is some nice WPF stuff going on, just to make the chat application look nicer than an ordinary console application. I will, however, discuss interesting bits of the WPF implementation.

Prerequisites

  1. To run the code supplied with this article, you will need to install the May 2006 LINQ CTP, which is available here. There is a new March 2007 CTP available, but it's about 4GB for the full install (as its not just LINQ but the entire next generation of Visual Studio codenamed "Orcas") and quite fiddly, and probably going to change anyway. So, the May 2006 LINQ CTP will be OK for the purpose of what this article is trying to demonstrate.

  2. The .NET 3.0 Framework, which is available for download here.

A Brief Overview of the Demo App and What We are Trying to Achieve

In the attached demo application, we are trying to carry our the following functionality:

  1. Allow chatters to pick a name for themselves and pick an image (Avatar) that they would like to be presented by

  2. Allow the chatters to join a peer-to-peer chat

  3. Allow chatters to see who else is available to chat to

  4. Allow chatters to send private message

  5. Allow chatters to send global messages

  6. Allow chatters to leave the chat environment

  7. Make it all look pretty using WPF (not strictly a requirement for a chat app, but I like WPF, so humour me)

In order to achieve all of this I have developed 3 separate assemblies, which by the end I hope you will understand.

  • ChatService.Dll: the WCF chat server, that allows chat clients to connect and is the main message router

  • Common.Dll: is a simple serializable class which is used by both the ChatService.Dll and the WPFChatter.Dll files

  • WPFChatter.Dll: the pretty WPF wrapper around the client WCF functions

Some Key Concepts Explained

There are a number of key concepts that were mentioned earlier that need to be explained in order for the full application (which covers a lot of ground) to be understood. So I'll just explain each of these a little bit at a time, so the the final application should be a little easier to explain (well that's the idea anyway).

WCF: the New Service Orientated Attributes

There are a number of new attributes that may be used with WCF to adorn our NET classes/interfaces, shown below are the ones that are used as part of the attached demo application.

ServiceContractAttribute

Indicates that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application. It has the following members:

Name

Description

CallbackContract

Gets or sets the type of callback contract when the contract is a duplex contract.

ConfigurationName

Gets or sets the name used to locate the service in an application configuration file.

HasProtectionLevel

Gets a value that indicates whether the member has a protection level assigned.

Name

Gets or sets the name for the
element in Web Services Description Language (WSDL).

Namespace

Gets or sets the namespace of the
element in Web Services Description Language (WSDL).

ProtectionLevel

Specifies whether the binding for the contract must support the value of the ProtectionLevel property.

SessionMode

Gets or sets whether sessions are allowed, not allowed or required.

TypeId

(Inherited from Attribute)

See the MSDN article for more details.

OperationContractAttribute

Indicates that a method defines an operation that is part of a service contract in a Windows Communication Foundation (WCF) application. It has the following members:

Name

Description

Action

Gets or sets the WS-Addressing action of the request message.

AsyncPattern

Indicates that an operation is implemented asynchronously using a Begin and End method pair in a service contract.

HasProtectionLevel

Gets a value that indicates whether the messages for this operation must be encrypted, signed, or both.

IsInitiating

Gets or sets a value that indicates whether the method implements an operation that can initiate a session on the server (if such a session exists).

IsOneWay

Gets or sets a value that indicates whether an operation returns a reply message.

IsTerminating

Gets or sets a value that indicates whether the service operation causes the server to close the session after the reply message, if any, is sent.

Name

Gets or sets the name of the operation.

ProtectionLevel

Gets or sets a value that specifies whether the messages of an operation must be encrypted, signed, or both.

ReplyAction

Gets or sets the value of the SOAP action for the reply message of the operation.

TypeId

(Inherited from Attribute)

See the MSDN article for more details

ServiceBehaviorAttribute

Specifies the internal execution behavior of a service contract implementation. It has the following members:

Name

Description

AddressFilterMode

Gets or sets the AddressFilterMode that is used by the dispatcher to route incoming messages to the correct endpoint.

AutomaticSessionShutdown

Specifies whether to automatically close a session when a client closes an output session.

ConcurrencyMode

Gets or sets whether a service supports one thread, multiple threads, or reentrant calls.

ConfigurationName

Gets or sets the value used to locate the service element in an application configuration file.

IgnoreExtensionDataObject

Gets or sets a value that specifies whether to send unknown serialization data onto the wire.

IncludeExceptionDetailInFaults

Gets or sets a value that specifies that general unhandled execution exceptions are to be converted into a System.ServiceModel.FaultException of type System.ServiceModel.ExceptionDetail and sent as a fault message. Set this to true only during development to troubleshoot a service.

InstanceContextMode

Gets or sets the value that indicates when new service objects are created.

MaxItemsInObjectGraph

Gets or sets the maximum number of items allowed in a serialized object.

Name

Gets or sets the value of the name attribute in the service element in Web Services Description Language (WSDL).

Namespace

Gets or sets the value of the target namespace for the service in Web Services Description Language (WSDL).

ReleaseServiceInstanceOnTransactionComplete

Gets or sets a value that specifies whether the service object is released when the current transaction completes.

TransactionAutoCompleteOnSessionClose

Gets or sets a value that specifies whether pending transactions are completed when the current session closes without error.

TransactionIsolationLevel

Specifies the transaction isolation level for new transactions created inside the service, and incoming transactions flowed from a client.

TransactionTimeout

Gets or sets the period within which a transaction must complete.

TypeId

(Inherited from Attribute)

UseSynchronizationContext

Gets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution.

ValidateMustUnderstand

Gets or sets a value that specifies whether the system or the application enforces SOAP MustUnderstand header processing.

See the MSDN article or more details. Here is an example of how these new WCF attributes are used within the demo application, Service project -> ChatService.cs.

Collapse

[ServiceContract(SessionMode = SessionMode.Required,

CallbackContract = typeof(IChatCallback))]

interface IChat

{

[OperationContract(IsOneWay = true, IsInitiating = false,

IsTerminating = false)]

void Say(string msg);


[OperationContract(IsOneWay = true, IsInitiating = false,

IsTerminating = false)]

void Whisper(string to, string msg);


[OperationContract(IsOneWay = false, IsInitiating = true,

IsTerminating = false)]

Person[] Join(Person name);

[OperationContract(IsOneWay = true, IsInitiating = false,

IsTerminating = true)]

void Leave();

}

WCF: the Use of Interfaces

"The notion of a contract is the key to building a WCF service. Those of you that have a background in classic DCOM or COM technologies might be surprised to know that WCF contracts are expressed using interface-based programming techniques (everything old is new again!). While not mandatory, the vast amount your WCF applications will begin by defining a set of .NET interface types that are used to represent the set of members a given WCF type will support. Specifically speaking, interfaces that represent a WCF contract are termed service contracts. The classes (or structures) that implement them are termed service types."

Pro C# with .NET3.0, Apress. Andrew Troelsen

So there you are -- that's what a nice new book says -- but what does this look like to us in code? Well the actual ChatService.cs class implements the IChat interface just mentioned, and so looks like this:

Collapse

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,

ConcurrencyMode = ConcurrencyMode.Multiple)]

public class ChatService : IChat

{


}

WCF: the Use of Callbacks

Recall earlier, when I mentioned the ServiceContractAttribute I also mentioned that one of its properties was a CallBackContract that was defined as, which allows the WCF service to call the client back. This new WCF method is very nice. I remember trying to do something like this with remoting and events back to the client, and it was not fun at all. I much prefer this method. Let's have a look. Recall that the original service contract interface was declared like this:

Collapse

[ServiceContract(SessionMode = SessionMode.Required,

CallbackContract = typeof(IChatCallback))]

interface IChat

{

....

}

Well we still need to define an interface to allow the callback to work, so an example of this may be (as done in the demo app):

Collapse

interface IChatCallback

{

[OperationContract(IsOneWay = true)]

void Receive(Person sender, string message);


[OperationContract(IsOneWay = true)]

void ReceiveWhisper(Person sender, string message);


[OperationContract(IsOneWay = true)]

void UserEnter(Person person);


[OperationContract(IsOneWay = true)]

void UserLeave(Person person);

}

  1   2   3   4   5

Похожие:

Example code: Chat application iconUcas or Other Admissions Code Northumbria Programme Code

Example code: Chat application iconUcas or Other Admissions Code Northumbria Programme Code

Example code: Chat application iconUcas or Other Admissions Code Northumbria Programme Code

Example code: Chat application iconCode Pre-Requisite Module Code(s)

Example code: Chat application iconNorthumbria Programme Code(s) please indicate the programme code(s) for the main delivery in bold

Example code: Chat application iconGeneral Education Code: (enter a Gen Ed code only if the course is to be submitted to the General Education Review Committee; otherwise leave blank)

Example code: Chat application iconConcerning the implementation of the code of the republic of kazakhstan «concerning taxes and other obligatory payments to the budget (the tax code)»
«Concerning Taxes and Other Obligatory Payments to the Budget» (the Tax Code) shall enter into force form the 1st January 2009, except...
Example code: Chat application iconWork Safety (act code of Practice for Safe Demolition Work) Code of Practice 2010

Example code: Chat application iconChairman’s Chat Lyn West

Example code: Chat application iconCrisis Webinar Public Chat

Разместите кнопку на своём сайте:
Библиотека


База данных защищена авторским правом ©lib.znate.ru 2014
обратиться к администрации
Библиотека
Главная страница