RSS

Monthly Archives: July 2011

Create an EXE or Setup File in .NET Windows Application

Visual Studio Setup and deployment Projects provides to make an executable or installer file in .NET windows application is easy and rapidly.

Visual Studio provides templates for four types of deployment projects: Merge Module Project, Setup Project, Web Setup Project, and Cab Project. In addition, a Setup wizard is provided to help step you through the process of creating deployment projects. You can see the templates and the wizard in the New Project dialog box under theSetup and Deployment Projects node.

The following are guidelines for choosing the right type of deployment project for your project.

1)Merge Module Project : Packages components that might be shared by multiple applications.

2)Setup Project : Builds an installer for a Windows-based application.

3)Web Setup Project : Builds an installer for a Web application.

4)Cab Project : Creates a cabinet file for downloading to a legacy Web browser.

5)Smart Device Cab Project : Creates a Cab project to deploy device applications.

This topic demonstrates deployment using a Setup and Deployment Project.

Setup Projects

Setup projects allow you to create installers in order to distribute an application. The resulting Windows Installer (.msi) file contains the application, any dependent files, information about the application such as registry entries, and instructions for installation. When the .msi file is distributed and run on another computer, you can be assured that everything necessary for installation is included; if for any reason the installation fails (for example, the target computer does not have the required operating system version), the installation will be rolled back and the computer returned to its pre installation state.

I. Create Setup Project

The following steps will gives the elegant guidance to create an executable or installer file.

1. Go to file menu > click Add > new project >now “Add New Project” dialog will appear.

2. Select the “Other Project Types” and click “Setup and Deployment” projects,Choose “Setup Project” give name project name in name text box finally click OK.

3. New project appear in solution explorer,for eg., you have give the name “MyEXE” file will be displays with given name.

4.Right click the MyEXE > go View > click “File System”

5.You can see the “File System on TargetMachine”under  three folders
Application Folder
User’s Desktop
User’s Program Menu

6.Select Application Folder and right click Add>Project Output>select Primary output

7. Select User’s Desktop right click on the right side pane>click create new shortcut>select output file from Application folder>change the file name from  primary output name to MyEXE

next >>

Same procedure follows the user’s program menu also

8.If you want to change the Manufactures name, just right click the project go to properties

change the properties as per you requirement

9.Finally Build the new project After successfully Build the project myEXE(Setup) will be appear in Application Debug or Release folder(depend upon the properties settings)

EXE or installer will be available on his physical path…

When you want to install  the EXE on the client machine, before you should be installed .NET Framework on that machine because, Applications and controls written for the .NET Framework v2.0 requires the .NET Framework Redistributable Package version 2.0 to be installed on the computer where the application or control runs.

you can get it from here

II. Create shortcut icon  in User’s Desktop and User’s Program Menu

Step1: Select ‘User’s Desktop’ or ‘User’s Program Menu’  and right click on right side pane

Create short cut on user's desktop

Step 2: Add primary output of actual application and click ‘OK’ to select

Step 3: Rename the actual name to your desired project/product name

Step 4: Here the sample product name is ‘Your Product Name’ for demo purpose

Step 5: If we want to add icon on shortcut, Click Properties Window

Step 6: Select Icon, next Browse icon file

Step 7:  Browse Icon File (Format should be .ico, other formats are not acceptable)

Step 8: Click  ‘Application Folder’

Step 9: Add File button will enable once you have clicked Application Folder

Step 10: Select your product icon from somewhere in system and Click ‘OK’

User should follow the same steps for shortcut added to User’s Program Menu.

Install your setup in target machine, You can view the shortcuts in Desktop and Start Menu.

Figure: Shortcut icon in Desktop

Figure: Shortcut icon in User’s Program Menu

III. Add Prerequisites

Prerequisites are provide support resources to run the installed process on your target machine.

Visual Setup and Deployment projects are automatically detect the required prerequisites need to install the system. But the question is what is the source for install the prerequisites?  No need to worry, Visual Studio IDE provides three options to install the prerequisites on your system.

  • Download prerequisites from component vendor’s website (default option)
  • Download prerequisites from the same location as my application
  • Download prerequisites from the following location

How to add prerequisites in Visual Studio?

1. Select Project in Solution Explorer, Right click

2. Click the Prerequisites button in Property Pages

3. Select the required prerequisites from the window

Click ‘Ok’, prerequisites will associate based on your install location selection.

Referenced by: http://balanagaraj.wordpress.com/2007/05/29/create-exe-or-setup-file-in-net-windows-application/

Advertisements
 
4 Comments

Posted by on July 24, 2011 in C#

 

Google’s Go Language For Windows

Google’s new Go language is still in its infancy, and it has yet to find widespread real-world use or support. Even so, it seems like a promising experiment, and I wonder if it could have a future in game development. I haven’t been able to find much game-specific discussion of Go elsewhere, and figured a CW discussion may be appropriate.

Some thoughts:

  • According to golang.org, Go programs “run nearly as quickly as comparable C or C++ code”–quick enough?
  • Is Go’s garbage collection well suited for games?
  • How much mental re-tooling is necessary to create games in the land of concurrent goroutines?
  • Go is frequently called a “systems”-level language, with server software given as an example. It’s hard not to think of multiplayer game servers when hearing this.
Installing Go
here is a similar Linux version of gogo here.

The windows port can be downloaded from http://code.google.com/p/gomingw/downloads/list

I had a problem with the Installer version, so personally I downloaded the zipped version, and unzipped it to C:, resulting in the system being stored in c:\go and subfolders.

Windows Environment Variables

Go to Control Panel…Advanced System Settings…Advanced…Environment Variables.

Create these environment variables, which need to match where you installed Go. Here are my settings, for Go in C:\go.

GOARCH    386
GOBIN     c:\go\bin
GOOS      windows
GOROOT    c:\go

You can now use gogo. The first time you run it, use the Tools…Configure option. (Page edited 4/july/11)

Go Go IDE
There is a similar Linux version of gogo here.

v0.3 – 5 july 11 download gogo.zip (less than 1MB)

Unzip it into any folder, and run gogo.exe. The first time you run it, use tools | Configure to make it locate your Go software.

The source code(Delphi 6) will be released. I’m just tidying it up at present (1 july 2011)

 

Referenced by: http://gamedev.stackexchange.com/questions/3850/developing-games-in-go

 
Leave a comment

Posted by on July 18, 2011 in Go Language

 

Database-based High Performance Message Exchange Service for Enterprise Applications

Database Message Exchange Service allows messages to be stored in database in order to be picked up by a Windows service and delivered to external services and vice versa. A message can be anything – an order, some task, a message for a destination message queue, a payload for calling external webservice and so on. It decouples the client from the external services that are not in the same network or not always available or do not support high frequency poll needed by front-ends.

Introduction

Database Message Exchange Service allows messages to be stored in a database in order to be picked up by a Windows service and delivered to external services and vice versa. A message can be anything – an order, some task, a message for a destination message queue, a payload for calling an external web service and so on. It decouples the client from the external services that are not in the same network or not always available or do not support high frequency polling needed by clients. The client can perform high frequency polls on the database, without causing a hit on the external services on every poll. Since the messages are stored in a database, they can be replayed in case of failure, they can be archived, and they can be processed in some other priority order than first-in-first-out and so on. Moreover, reports can be generated from the database using the data available in the stored messages. Traditional queue services like MSMQ or IBM MQ aren’t always the right choice to be used directly from the client, especially if you have a Web front-end that performs millions of polls on them and you need to sometimes browse and replay messages in some specific order. Additionally, MIS reports from queue are not possible, so a database-based high performance message queuing and delivery service is preferred. The architecture of the service is flexible as it allows any external service to be integrated via a plug-in model and it can launch multiple threads to read and write in parallel to and from external services. It also offers connection throttling to external services by design and prevents external services from being adversely affected by a sudden increase in traffic on the client. Finally, the service can be deployed in multiple servers to support scalability without requiring any code change.

It’s currently used in production at BT, where we use it to queue messages from a high volume website and the messages are exchanged with an IBM MQ.

Architecture

Database Message Exchange Service uses database tables to store incoming and outgoing messages. There’s a windows service or console application that reads messages from the database and sends them to an external service. Similarly, it reads from an external service and stores them in a database so that a client can pick up the message from the database. The database tables simulate a FIFO queue as described in my earlier article on Building a high performance queue in a database. The architecture is like this:

Figure: Database Message Exchange Service architecture

The architecture of the service is kept very simple to make it easy to configure and deploy it for multiple external services. If you have four different external services, you just deploy four clones of the service. Each instance of the service can talk to only one type of external service but it can launch multiple reader/writer threads both for queueing and dequeueing on database and on external service. The Exchange Manager, which does the controller’s job, launches a configured number of threads to dequeue messages from the database and then launches a configured number of threads to connect and read from the external service. External Service can be anything – another webservice, queue, FTP, file system and so on. You just implement the IExternalProvider interface for each type of external service, configure the number of reader and writer threads you want, and you are done. The whole service is provided as a reusable library so that you can choose how you want to run it – as a console app or as a Windows service.

From the client’s point of view, the client needs to construct a message with a CorrelationID and then enqueue it in the Inbox. Then keep polling at some interval for a response to arrive in Outbox.

That’s from a client’s point of view. On the service side, the ExchangeManager launches N threads to keep polling for messages on Inbox. Once a message is found, it sends the message to the external service using the External Service Provider. Here’s how each thread does its job:

(Click on the image to enlarge it)

In the same way, ExchangeManager also launches N threads to keep polling on the external service. Once a message is found, it stores the message in the Outbox table. If a message arrives with the right CorrelationID, then the client can pick it up by calling RetrieveFromOutbox. Here’s how each thread does its job:

(Click on the image to enlarge it)

The following architecture issues are addressed:

  • Ensuring that a message isn’t picked up by multiple services.
  • Ensuring that messages can be queued at a very high frequency without blowing up the external services.
  • Ensuring that client/front-end can perform high frequency polls to check for arrival of a response to their queued messages.
  • Ensuring that messages are picked up from Inbox immediately by launching multiple database polling threads. If one thread is processing one message and the external service is taking a while to send the message, then the other threads can pick up other messages from Inbox and send them.
  • Ensuring that the external service read happens on multiple threads so that the delay in processing a received message and storing it in Outbox is minimized and maximum utilization of external services capability to deliver messages is ensured.
  • On the event of unavailability of the service, the messages are not lost. Messages are picked up and processed at a steady speed.
  • Ensuring that a sudden arrival of a large amount of messages does not cause high CPU on the service nor does it cause additional stress on the external service. A steady speed of reading and writing on both database and external service is maintained through configurable delays.
  • Easy to scale out. The service can be deployed multiple times on the same computer or in different computers.
  • Easy to start and stop.
  • Ability to debug on a production instance by attaching a debugger.

I have seen such issues from message exchange services in various companies I have worked for. So, I have tried my best to solve these once and for all. It’s a service that’s deployed on production and working very well.

Benefits

Why not use the SQL Server Service Broker? Firstly because it ties you to use the Standard or a higher edition of SQL Server, which has a hefty license cost. Using my approach you can use the free SQL Server Express and install a couple of them on a cheap VM and setup a pretty scalable “Service Broker” cluster. Scaling out is cheap – just install another VM, install the free SQL Express, and you are done. You can build a large cluster of message storage and distribution service without paying for any SQL Server license fee at all. Moreover, you can create the service using pure .NET code, unit test them and debug them easily on production without having to attach a debugger to SQL Server Service Broker. Anyone who has worked with CLR stored procedures knows the pain of releasing newer versions. Pure .NET code makes debugging, crash dumping, exception logging, etc. straightforward and cheap. It gives you the ultimate flexibility since you have full control over a .NET app doing the message exchange work reading from a very simple database schema.

Why not use MSMQ then? Firstly, because MSMQ does not allow you to read messages other than in the FIFO order. You might want to read messages using some other field than the queue date-time. MSMQ won’t let you retry messages once they are dequeued from the queue. You will have to queue them again. There’s no notion of changing message’s state. You either take the message out of the queue or you leave it, but you cannot change the message’s state to process it later. You cannot use any other custom filtering criteria to read messages from the queue besides the FIFO criteria.

Implementation

The controller class ExchangeManager manages a pool of threads of IDBQueueProvider and IExternalProvider implementations. IDBQueueProvider is implemented by SqlDBQueueProvider by default, which takes care of reading messages out of Inbox and writing messages to Outbox. IExternalProvider is what you need to implement depending on what is the external service you are trying to consume. It can be a file system, an external webservice, a MSMQ or IBMMQ, or just an FTP server. You need to implement the ReadAndWait and Send methods to support the message exchange. IExternalProvider takes messages as ExternalMessage, which you can inherit from and use your own class.

(Click on the image to enlarge it)

As a consumer, the only class you need to deal with is the ExchangeManager. It does everything for you. Here’s how you can use it form a console app:

static void Main(string[] args)

{

Console.WriteLine(“Starting…”);

var manager = new ExchangeManager(() => new ExternalProviderMQImpl(),

() => new SqlDBQueueProvider(Config.ConnectionString),

new Log4NetLogger(),

Config.ExternalThreadCount,

Config.DBThreadCount,

Config.DBPollInterval,

Config.ExternalReadInterval,

Config.ExternalReadTimeout,

Config.StopTimeout);

manager.Start();

Console.WriteLine(“Started. Press ENTER to close.”);

Console.ReadLine();

manager.Stop();

}

Once you call Start(), it launches the specified number of DB threads and External threads. The above code shows how to use it in a console app. For a Windows service, in the OnStart event, you just call Start() and in the OnStop event, call Stop().

ExchangeManager uses the SmartThreadPool library to manage the threads. It’s another open source library that allows fine control over threads, especially when you want to start a group of threads and then stop a group of threads.

During Start, ExchangeManager creates a number of threads to listen to the database:

/// <summary>

/// Launch the threads that will poll DB at certain intervals

/// and if any message found in Inbox, it will use the External Provider

/// to send the message to the Queue.

/// </summary>

private void StartDBReaderThreads()

{

var me = this;

for (int i = 0; i < this.DBPollerThreadCount; i++)

{

this.ThreadPool.QueueWorkItem(() =>

{

me.Logger.Debug(“Starting DB Reader Thread ” + i + “…”);

var dbQueueProvider = me.DBQueueProviderBuilder();

var externalProvider = me.ExternalProviderBuilder();

try

{

me.Logger.Debug(“Initializing DB Provider…”);

dbQueueProvider.Initialize();

me.Logger.Debug(“Initializing External Provider…”);

externalProvider.Connect();

while (!me.Stopped)

{

try

{

var inboxItems = dbQueueProvider.DequeueInbox();

if (inboxItems != null)

{

foreach (InboxItem item in inboxItems)

{

me.Logger.Debug(“Sending message to External ” + item.ItemID + “…”);

me.Logger.LogInboxItem(item);

try

{

externalProvider.Send(new ExternalMessage

{

CorrelationID = item.CorrelationID,

Data = item.TextData

});

}

catch (ThreadAbortException)

{

throw;

}

catch (Exception x)

{

if (!externalProvider.TryRecoverFromFault(x))

return;

}

me.Logger.Debug(“Sent message to External ” + item.CorrelationID);

}

}

}

catch (ThreadAbortException)

{

throw;

}

catch (Exception x)

{

me.Logger.Error(x);

if (!dbQueueProvider.TryRecoverFromFault(x))

return;

}

It first creates one instance of the IDBQueueProvider and one instance of IExternalProvider. Then it runs a continuous loop to periodically poll from DB and check if there’s any message in the Inbox table to pick it up. Once it finds a list of messages, it then sends each message through the IExternalProvder.Send() function.

Similarly it creates a number of threads to listen and wait on IExternalProvider. When a message arrives, it converts the ExternalMessage to OutboxItem and then stores in the Outbox folder for the client to pickup.

/// <summary>

/// Launch the threads for reading from external service.

/// </summary>

private void StartExternalReaderThreads()

{

var me = this;

for (int i = 0; i < this.ExternalReaderThreadsCount; i++)

{

me.ThreadPool.QueueWorkItem(() =>

{

me.Logger.Debug(“Starting DB Reader Thread ” + i + “…”);

var dbQueueProvider = me.DBQueueProviderBuilder();

var externalQueueProvider = me.ExternalProviderBuilder();

try

{

me.Logger.Debug(“Initializing DB Provider…”);

dbQueueProvider.Initialize();

me.Logger.Debug(“Initializing External Provider…”);

externalQueueProvider.Connect();

while (!me.Stopped)

{

var message = default(ExternalMessage);

try

{

// This is a blocking call, until message arrives or we get

// some exception, execution does not proceed

message = externalQueueProvider.ReadAndWait(this.ExternalReadTimeout);

}

catch (ThreadAbortException)

{

throw;

}

catch (Exception x)

{

if (!externalQueueProvider.TryRecoverFromFault(x))

return;

}

if (message != null)

{

me.Logger.Debug(“Received message: ” + message.CorrelationID);

me.Logger.LogMessage(message);

try

{

var outboxItem = new OutboxItem

{

CorrelationID = message.CorrelationID,

TextData = message.Data,

ItemDateTime = DateTime.Now

};

me.Logger.Debug(“Enqueue outbox item: ” + outboxItem.CorrelationID);

me.Logger.LogOutboxItem(outboxItem);

dbQueueProvider.EnqueueOutbox(outboxItem);

}

catch (ThreadAbortException)

{

throw;

}

catch (Exception x)

{

me.Logger.Error(x);

if (!dbQueueProvider.TryRecoverFromFault(x))

return;

}

me.Logger.Debug(“Queued message in Outbox: ” + message.CorrelationID);

}

else

{

me.Logger.Debug(“Got null message from External.”);

}

Thread.Sleep(this.ExternalReadInterval);

Here it calls IExternalProvider.ReadAndWait() which should make a blocking call to the external service and return a message. It’s fine if it does not return any message. For example, you might be checking a file path regularly for any new file to appear and when there’s no file, return null. If you are reading from MSMQ, then the ReadAndWait() is a blocking read.

Once a message is found, it stores the message in the Outbox table.

Each of the interfaces are documented in detail to tell you exactly what you need to do and what you should not do in the implementation. For example, the IExternalProvider is the one you implement for each and every external service.

public interface IExternalProvider : IDisposable

{

/// <summary>

/// Connect to the External provider. For MQ, establish the connection

/// to the MQ here. For http, open http connection here.

/// </summary>

void Connect();

 

/// <summary>

/// Disconnect from external provider. Eg close connection to MQ or http.

/// </summary>

void Disconnect();

 

/// <summary>

/// Disconnect and Connect. You can either just call Disconnect and Connect

/// or implement some custom code for handling a reconnection scenario.

/// Reconnect is called when there’s some problem with connection, say connection

/// dropped abnormally.

/// </summary>

void Reconnect();

 

/// <summary>

/// A blocking read call to the external service. This function should not

/// return unless some data is available. So, for MQ, you call Read() which

/// blocks thread until a message arrives. For http service, you can keep

/// polling an http endpoint here.

/// If you can’t implement a blocking call, then if there’s nothing to return,

/// return null.

/// The blocking call must not block more than the given timeout.

/// </summary>

///

/// <returns>Null if no data. Otherwise an ExternalMessage</returns>

ExternalMessage ReadAndWait(TimeSpan timeout);

 

/// <summary>

/// Send a message to destination. Destination can be a MQ.

/// </summary>

/// <param name=”message”>Message to send</param>

void Send(ExternalMessage message);

 

/// <summary>

/// Check if the exception is one of those exception that

/// can be recovered from. For example, connection dropped.

/// Try Reconnect() within this function. If there’s exception

/// from Reconnect(), then return false to indicate permanent

/// failure. Return true if the connection was recovered.

/// </summary>

/// <param name=”x”></param>

/// <returns>True if the exception is recoverable. False if permanent exception.</returns>

bool TryRecoverFromFault(Exception x);

}

Once you implement this interface as per the specification, ExchangeManager will take care of calling it right away, getting messages from external sources, sending messages queued in database and so on.

Installation

First you create a console application or a Windows service. The sample implementation comes with a console application. You can use it as is, all you need to do is write the code inside the ExternalProviderMQImpl class for the specific external service you want to connect to. Then you need to create a database and run the scripts in the DB folder of the resource file (MQtoDBQueue.zip). Then configure the app.Config with the right connection string and that’s it.

<configuration>

<connectionStrings>

<add name=”QueueDBConnectionString” connectionString=”Server=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=DBQueue;”/>

</connectionStrings>

<appSettings>

<add key=”PollFromDBDuration” value=”00:00:00.100″/>

<add key=”PollFromExternalDuration” value=”00:00:00.100″/>

<add key=”NoOfThreadsOnExternal” value=”4″/>

<add key=”NoOfThreadsOnDB” value=”4″/>

<add key=”ExternalReadTimeout” value=”00:00:05″/>

<add key=”StopTimeout” value=”00:00:10″/>

</appSettings>

Let’s go through the configuration settings as they are key to handle scalability and throttling:

  • PollFromDBDuration: This is the interval between two poll requests on the Inbox table to check for pending message to pick up. If it’s too high, then there’ll be lag in pickup up messages after they get queued. If it’s too low, then the Inbox table will get too frequent poll calls.
  • NoOfThreadsOnDB: How many parallel threads to run that will keep polling the database to pickup messages from the Inbox. “1” can be fine. But if you have a very high number of messages getting queued in Inbox and the external service is taking is too much time to send them and thus messages are getting piled up in Inbox, you can increase this number and launch more parallel threads to read messages from Inbox and send them.
  • PollFromExternalDuration: The interval between two ReadAndWait() calls on external service. If you have a blocking read call on external service, for ex MSMQ, then it can be very low. But if you are making some external webservice call, then you need adjust it according to the capacity of the external service.
  • NoOfThreadsExternal: How many parallel threads to run that will call ReadAndWait() on external service.
  • ExternalReadTimeout: How long to wait for a single ReadAndWait() call. It needs to be inside the implementation of ReadAndWait().
  • StopTimeout: How long to wait after Shutdown() has been called and threads are not stopping and need to abort them.

Once you have configured these, you are good to go.

Conclusion

Database Message Exchange Service helps you build a high performance scalable intermediate queue or storage for messages that need to be exchanged with external services. It allows high frequency poll from the client/front-end as it happens on the database, not directly on the external service, thus decoupling the front-end from the external services. It allows reliable storage, retry, failover and reporting of messages that aren’t available in traditional queueing solutions. Pure .NET code makes it easy to debug, crash dump, maintain and extend.

Resources: MQtoDBQueue.zip

About the Author

Omar AL Zabir is the Chief Architect of SaaS Platform at BT, UK. He was the co-founder and CTO of a popular Web 2.0 startup – Pageflakes, that got acquired by MySpace founder. Omar is a Microsoft MVP and CodeProject MVP. He writes articles mostly on AJAX and .NET Performance & Scalability. Omar has published “Building a Web 2.0 Portal using ASP.NET 3.5” from O’Reilly. He has several popular Open source projects and blogs at his site http://omaralzabir.com.

Referenced by: http://www.infoq.com/articles/Database-Message-Exchange-Service

 
Leave a comment

Posted by on July 14, 2011 in C#

 

Practical UML™: A Hands-On Introduction for Developers

Abstract: This tutorial provides a quick introduction to the Unified Modeling Language™

The heart of object-oriented problem solving is the construction of a model. The model abstracts the essential details of the underlying problem from its usually complicated real world. Several modeling tools are wrapped under the heading of the UML™, which stands for Unified Modeling Language™. The purpose of this course is to present important highlights of the UML.

At the center of the UML are its nine kinds of modeling diagrams, which we describe here.

Some of the sections of this course contain links to pages with more detailed information. And every section has short questions. Use them to test your understanding of the section topic.

Divider line

Why is UML important?

Let’s look at this question from the point of view of the construction trade. Architects design buildings. Builders use the designs to create buildings. The more complicated the building, the more critical the communication between architect and builder. Blueprints are the standard graphical language that both architects and builders must learn as part of their trade.

Writing software is not unlike constructing a building. The more complicated the underlying system, the more critical the communication among everyone involved in creating and deploying the software. In the past decade, the UML has emerged as the software blueprint language for analysts, designers, and programmers alike. It is now part of the software trade. The UML gives everyone from business analyst to designer to programmer a common vocabulary to talk about software design.

The UML is applicable to object-oriented problem solving. Anyone interested in learning UML must be familiar with the underlying tenet of object-oriented problem solving — it all begins with the construction of a model. A model is an abstraction of the underlying problem. The domain is the actual world from which the problem comes.

Models consist of objects that interact by sending each other messages. Think of an object as “alive.” Objects have things they know (attributes) and things they can do (behaviors oroperations). The values of an object’s attributes determine its state.

Classes are the “blueprints” for objects. A class wraps attributes (data) and behaviors (methods or functions) into a single distinct entity. Objects are instances of classes.

Divider line

Use case diagrams

Use case diagrams describe what a system does from the standpoint of an external observer. The emphasis is on what a system does rather than how.

Use case diagrams are closely connected to scenarios. A scenario is an example of what happens when someone interacts with the system. Here is a scenario for a medical clinic.

“A patient calls the clinic to make an appointment for a yearly checkup. The receptionist finds the nearest empty time slot in the appointment book and schedules the appointment for that time slot. ”

use case is a summary of scenarios for a single task or goal. An actor is who or what initiates the events involved in that task. Actors are simply roles that people or objects play. The picture below is a Make Appointment use case for the medical clinic. The actor is a Patient. The connection between actor and use case is a communication association (orcommunication for short).

Hide image
Use case

Actors are stick figures. Use cases are ovals. Communications are lines that link actors to use cases.

A use case diagram is a collection of actors, use cases, and their communications. We’ve put Make Appointment as part of a diagram with four actors and four use cases. Notice that a single use case can have multiple actors.

Hide image
Use case diagram

Use case diagrams are helpful in three areas.

  • determining features (requirements). New use cases often generate new requirements as the system is analyzed and the design takes shape.
  • communicating with clients. Their notational simplicity makes use case diagrams a good way for developers to communicate with clients.
  • generating test cases. The collection of scenarios for a use case may suggest a suite of test cases for those scenarios.

More details

Self test

Divider line

Class diagrams

A Class diagram gives an overview of a system by showing its classes and the relationships among them. Class diagrams are static — they display what interacts but not what happens when they do interact.

The class diagram below models a customer order from a retail catalog. The central class is the Order. Associated with it are the Customer making the purchase and the Payment. APayment is one of three kinds: CashCheck, or Credit. The order contains OrderDetails (line items), each with its associated Item.

Hide image
Click to see full-sized image

UML class notation is a rectangle divided into three parts: class name, attributes, and operations. Names of abstract classes, such as Payment, are in italics. Relationships between classes are the connecting links.

Our class diagram has three kinds of relationships.

  • association — a relationship between instances of the two classes. There is an association between two classes if an instance of one class must know about the other in order to perform its work. In a diagram, an association is a link connecting two classes.
  • aggregation — an association in which one class belongs to a collection. An aggregation has a diamond end pointing to the part containing the whole. In our diagram, Orderhas a collection of OrderDetails.
  • generalization — an inheritance link indicating one class is a superclass of the other. A generalization has a triangle pointing to the superclass. Payment is a superclass ofCashCheck, and Credit.

An association has two ends. An end may have a role name to clarify the nature of the association. For example, an OrderDetail is a line item of each Order.

navigability arrow on an association shows which direction the association can be traversed or queried. An OrderDetail can be queried about its Item, but not the other way around. The arrow also lets you know who “owns” the association’s implementation; in this case, OrderDetail has an Item. Associations with no navigability arrows are bi-directional.

The multiplicity of an association end is the number of possible instances of the class associated with a single instance of the other end. Multiplicities are single numbers or ranges of numbers. In our example, there can be only one Customer for each Order, but a Customer can have any number of Orders.

This table gives the most common multiplicities.

Multiplicities Meaning
0..1 zero or one instance. The notation n . . m indicates n to m instances.
0..*  or  * no limit on the number of instances (including none).
1 exactly one instance
1..* at least one instance

Every class diagram has classes, associations, and multiplicities. Navigability and roles are optional items placed in a diagram to provide clarity.

More details

Self test

Divider line

Packages and object diagrams

To simplify complex class diagrams, you can group classes into packages. A package is a collection of logically related UML elements. The diagram below is a business model in which the classes are grouped into packages.

Hide image
Package diagram

Packages appear as rectangles with small tabs at the top. The package name is on the tab or inside the rectangle. The dotted arrows are dependencies. One package depends on another if changes in the other could possibly force changes in the first.

Object diagrams show instances instead of classes. They are useful for explaining small pieces with complicated relationships, especially recursive relationships.

This small class diagram shows that a university Department can contain lots of other Departments.

Hide image
Recursive class diagram

The object diagram below instantiates the class diagram, replacing it by a concrete example.

Hide image
Object diagram

Each rectangle in the object diagram corresponds to a single instance. Instance names are underlined in UML diagrams. Class or instance names may be omitted from object diagrams as long as the diagram meaning is still clear.

Self test

Divider line

Sequence diagrams

Class and object diagrams are static model views. Interaction diagrams are dynamic. They describe how objects collaborate.

sequence diagram is an interaction diagram that details how operations are carried out — what messages are sent and when. Sequence diagrams are organized according to time. The time progresses as you go down the page. The objects involved in the operation are listed from left to right according to when they take part in the message sequence.

Below is a sequence diagram for making a hotel reservation. The object initiating the sequence of messages is a Reservation window.

Hide image
Click to see full-sized image

The Reservation window sends a makeReservation() message to a HotelChain. The HotelChain then sends a makeReservation() message to a Hotel. If theHotel has available rooms, then it makes a Reservation and a Confirmation.

Each vertical dotted line is a lifeline, representing the time that an object exists. Each arrow is a message call. An arrow goes from the sender to the top of the activation bar of the message on the receiver’s lifeline. The activation bar represents the duration of execution of the message.

In our diagram, the Hotel issues a self call to determine if a room is available. If so, then the Hotel creates a Reservation and a Confirmation. The asterisk on the self call meansiteration (to make sure there is available room for each day of the stay in the hotel). The expression in square brackets, [ ], is a condition.

The diagram has a clarifying note, which is text inside a dog-eared rectangle. Notes can be put into any kind of UML diagram.

More details

Self test

Divider line

Collaboration diagrams

Collaboration diagrams are also interaction diagrams. They convey the same information as sequence diagrams, but they focus on object roles instead of the times that messages are sent. In a sequence diagram, object roles are the vertices and messages are the connecting links.

Hide image
Click to see full-sized image

The object-role rectangles are labeled with either class or object names (or both). Class names are preceded by colons ( : ).

Each message in a collaboration diagram has a sequence number. The top-level message is numbered 1. Messages at the same level (sent during the same call) have the same decimal prefix but suffixes of 1, 2, etc. according to when they occur.

Self test

Divider line

Statechart diagrams

Objects have behaviors and state. The state of an object depends on its current activity or condition. A statechart diagram shows the possible states of the object and the transitions that cause a change in state.

Our example diagram models the login part of an online banking system. Logging in consists of entering a valid social security number and personal id number, then submitting the information for validation.

Logging in can be factored into four non-overlapping states: Getting SSNGetting PINValidating, and Rejecting. From each state comes a complete set of transitions that determine the subsequent state.

Hide image
Click to see full-sized image

States are rounded rectangles. Transitions are arrows from one state to another. Events or conditions that trigger transitions are written beside the arrows. Our diagram has two self-transition, one on Getting SSN and another on Getting PIN.

The initial state (black circle) is a dummy to start the action. Final states are also dummy states that terminate the action.

The action that occurs as a result of an event or condition is expressed in the form /action. While in its Validating state, the object does not wait for an outside event to trigger a transition. Instead, it performs an activity. The result of that activity determines its subsequent state.

More details

Self test

Divider line

Activity diagrams

An activity diagram is essentially a fancy flowchart. Activity diagrams and statechart diagrams are related. While a statechart diagram focuses attention on an object undergoing a process (or on a process as an object), an activity diagram focuses on the flow of activities involved in a single process. The activity diagram shows the how those activities depend on one another.

For our example, we used the following process.

“Withdraw money from a bank account through an ATM.”

The three involved classes (people, etc.) of the activity are CustomerATM, and Bank. The process begins at the black start circle at the top and ends at the concentric white/black stop circles at the bottom. The activities are rounded rectangles.

Hide image
Click to see full-sized image

Activity diagrams can be divided into object swimlanes that determine which object is responsible for which activity. A single transition comes out of each activity, connecting it to the next activity.

A transition may branch into two or more mutually exclusive transitions. Guard expressions (inside [ ]) label the transitions coming out of a branch. A branch and its subsequent mergemarking the end of the branch appear in the diagram as hollow diamonds.

A transition may fork into two or more parallel activities. The fork and the subsequent join of the threads coming out of the fork appear in the diagram as solid bars.

Self test

Divider line

Component and deployment diagrams

component is a code module. Component diagrams are physical analogs of class diagram. Deployment diagrams show the physical configurations of software and hardware.

The following deployment diagram shows the relationships among software and hardware components involved in real estate transactions.

Hide image
Click to see full-sized image

The physical hardware is made up of nodes. Each component belongs on a node. Components are shown as rectangles with two tabs at the upper left.

Self test

Referenced by: http://edn.embarcadero.com/article/31863#component-and-deployment-diagrans

 
Leave a comment

Posted by on July 8, 2011 in UML

 

AutoComplete TextBox in C#

Most of the developers are familiar with the auto completion text feature available in browsers, search controls and other controls. The auto completion feature is when you start typing some characters in a control, the matching data is loaded automatically for you.

In Visual Studio 2005, some of the controls support this feature including the ComboBox and the TextBox controls. By using these features, we can build Internet Explorer like auto completion functionality in our Windows Forms applications.

Now, we can have a combo box that completes URLs as soon as you type any character. For example, in Figure 1, I typed “c-s” and I see all the URLs starting with “c-s”.

AutoCompleteImg1.gif

Figure 1. Auto Completion in a ComboBox

The AutoCompleteSource and AutoCompleteMode properties of the TextBox and ComboBox controls allow developers to provide automatic completion text feature. You can set both of these properties at design-time as well as at run-time. If you click on AutoCompleteSource drop down, you will see all the options in the drop-down list. See Figure 2.

AutoCompleteImg2.GIF

Figure 2. AutoCompleteSource options

Figure 3 shows AutoCompleteMode options.

AutoCompleteImg3.GIF

Figure 3. AutoCompleteMode options

You can also set these properties at run-time using the following code:

comboBox1.AutoCompleteSource = AutoCompleteSource.AllSystemSources;
comboBox1.AutoCompleteMode = 
AutoCompleteMode.SuggestAppend;

The AutoCompleteSource Enumeration has following members:

  • AllSystemResources – Specifies the equivalent of FileSystem and AllUrl as the source. This is the default value when AutoCompleteMode has been set to a value other than the default.
  • AllUrl – Specifies the equivalent of HistoryList and RecentlyUsedList as the source.
  • CustomSource – Specifies strings from a built-in AutoCompleteStringCollection as the source.
  • FileSystem – Specifies the file system as the source.
  • FileSystemDirectories – Specifies that only directory names and not file names will be automatically completed.
  • HistoryList – Includes the Uniform Resource Locators (URLs) in the history list.
  • ListItems – Specifies that the items of the ComboBox represent the source.
  • None – Specifies that no AutoCompleteSource is currently in use. This is the default value of AutoCompleteSource.
  • RecentlyUsedList – Includes the Uniform Resource Locators (URLs) in the list of those URLs most recently used.

The AutoCompleteMode enumeration has following members:

  • Append – Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters.
  • None – Disables the automatic completion feature for the ComboBox and TextBox controls.
  • Suggest – Displays the auxiliary drop-down list associated with the edit control. This drop-down is populated with one or more suggested completion strings.
  • SuggestAppend – Applies both Suggest and Append options.

Loading Custom Source

We can also specify a custom source from where the listing will be loaded. If you click on the AutoCompleteCustomSource property, it will open the String Collection Editor, where we can add our strings. For example, I add following strings to the strings list. See Figure 4.

AutoCompleteImg4.GIF

Figure 4. Custom Source strings

Now we need to set AutoCompleteSource to CustomSource:

comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

And when I run and type “v” in the combo box, I see VB.NET Heaven. See Figure 5.

AutoCompleteImg5.GIF

Figure 5. Custom Source listing

We can also create AutoCompleteStringCollection programmatically. The following code creates an AutoCompleteStringCollection, adds strings to the collection, and sets it to the AutoCompleteCustomSource of the ComboBox.

// AutoCompleteStringCollection
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
data.Add(
“Mahesh Chand”);
data.Add(
“Mac Jocky”);
data.Add(
“Millan Peter”);
comboBox1.AutoCompleteCustomSource = data;

Now running the sample and typing “m” in the ComboBox loads the data as shown in Figure 6.

AutoCompleteImg6.GIF 

Figure 6. Loading custom data

Summary

The AutoComplete feature of ComboBox and TextBox controls allow us to set the auto complete text feature. In this article, we saw how to use this feature in our application at design-time as well as at run-time.

Referenced by: http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx

 
Leave a comment

Posted by on July 5, 2011 in C#, Window Application