Archive

Archive for March, 2011

3 simple ways to create singleton pattern in C++

March 31st, 2011 5 comments

In my previous posts (part 1 and part 2), I’ve presented singleton design pattern implementation in C# .NET. In order to complete the subject, I would like to present singleton pattern implementation in old good native C++.

1) Basic singleton: static function “GetInstance” provides the access point; constructor, copy constructor and operator= are hidden from the user. The singleton is allocated upon first demand (lazy initialization). Null pointer is used to constrol first access, hence must be initialized in a C++ way – out of the class (as a static member).

class CKeyboard
{
public:
	static CKeyboard* GetInstance() 
	{
		if (!m_pInstance)
			m_pInstance = new CKeyboard();
		return m_pInstance;
	}

private:
	CKeyboard() {}
	CKeyboard(const CKeyboard&);
	CKeyboard& operator=(const CKeyboard&); 

private:
	static CKeyboard *m_pInstance;
};

CKeyboard* CKeyboard::m_pInstance = NULL;

Read more…

Categories: C++, Design Tags: , ,

How to kill applications and Processes on remote machine

March 28th, 2011 No comments

How to kill applications/Processes on remote machine
 
One of the requirements was to reboot processes that are running on Server machine, were number of possibilities how to implement such task and not to break our distributed design. Finally we decide to run simple script that kills desired processes.

After quick search on the web I have decided to use taskkill utility which supplied desired functionality.

As alternative tool we have tried pskillsysinternal development command, works nice but I failed to set force kill, so there were cases when the pskill operation didn’t succeeded.

Pskill usage example:

pskill \\serverName -u administrator -p password Process1.exe

 

taskkill usage example:

taskkill /s serverName /f /u administrator /p system /t /im Process1.exe

 
Read more…

Categories: .Net, General Tags:

Documenting your code and Using Visual Studio IntelliSense tool

March 28th, 2011 No comments

One of useful tools in any IDE that you developing at its ability to document your code with nice XML format. I will focus on VS2010 this is main tool that we are using at our development process.

There are some external tools that help and trying to automate documentation process, tools like GhostDoc. Of cause those tools can’t replace the programmer notes.

So when our code documented with Xml Documentation /// IDE ItelliSense uses this information in order to display this info about Class, method, Property and Data Member see following print screen from one of the System diagnostic classes.

 
Read more…

Categories: .Net Tags:

Draw Progress Bar in Janus GridEx cell content

March 27th, 2011 No comments

Draw Progress Bar in Janus GridEx cell content

As following my previous post [post] how to create customizable cell content, I decided to post progressbar sample CSharp code.
See full implementation of Progress bar cell in Janus GridEx control.

C# Usage example

 

private readonly ProgressBarCellRenderer m_progressBarCellRenderer = new ProgressBarCellRenderer

                {BorderPen = new Pen(Color.LightGray)};

 

Perform drawing on each OnDrawGridArea method callback.

void OnDrawGridArea(object sender, DrawGridAreaEventArgs args)

{

     if (e.Column.Key == MyColumn)

     {

         GridEXCellCollection currentRowCells = e.Row.Cells;

 

         double total = GetValue();

 

         if (total == 0)

            return;

 

         m_progressBarCellRenderer.DrawProgressBar(

                                                args

                                              , total

                                              , "custom text");

      }

}

Read more…

Categories: .Net Tags:

Managing connections with Oracle or any other Database

March 27th, 2011 1 comment

In case that we have small number of clients that contributes data from Database (our desktop application is classical example where we have exact number of clients known during deployment stage), dilemma is to close or leave database connections open permanently during our Application life time. It’s very important to make right decision at design stage.

Additional aspect that we need to consider of – its Multithreaded environment can cause

AccessViolationException

from Oracle, we have experienced this problem when the same open connection is used from different threads simultaneously.

Following C# code demonstrate simple example of connection usage.

using (DALFunctions  dal = new DALFunctions())

{

    dal.GetData(id);

}

Read more…

Categories: SQL Tags: ,

Pivoting Data in SQL

March 16th, 2011 No comments

I believe that may of you came across the need to pivot, or simply rotate some SQL data from columns to rows, while working with dynamic attributes or key-value pares tables.

For example I have the following database structure:



And of cause each object can have various number of associated attributes. Assuming that I need to fetch all attributes from the relevant objects, while attributes are aligned to the object in the same row, it becomes quite a trivia to perform.

Read more…

Categories: SQL Tags: , , ,

Simple singleton pattern with inheritance in C#.NET (part 2)

March 13th, 2011 1 comment

In my previous post about singleton inheritance, I’ve presented a simple singleton design pattern implementation in C#.NET, and a more advance implementation method, which allows to inherit from base singleton class. In the curent post, I will show several ways, to make the singleton thread-safe.
While saying “thread-safe singleton”, one usually means the singleton creation; another functions/properties are handled regular way to be threadsafe. Singleton creation must take place only once.
Classic pattern, providing a solution for this issue, is double-checked locking. Why 2 checks are needed? Because, after the first time creation, the lock is redundant. So we just prevent it by additional check. Using this pattern, singleton creation looks like this:

Read more…

Categories: .Net, Design Tags: , , ,

Simple singleton pattern with inheritance in C#.NET (part 1)

March 12th, 2011 No comments

Singleton is very simple and widely used Design Pattern. This pattern is described in a lot of blogs, articles and books (e.g. GoF = Gang of Four). According to GoF,  singleton’s job is to “Ensure a class has one instance, and provide a global point of access to it”. In a general case, singleton can be extended, in order to ensure a class has n instances, while 1 ≤ n < ∞.

How can one build a singleton?

Two steps to make some class to be a singleton:
1) Forbid straightforword creation => let constructor be private (or protected in some cases).
2) Provide general access point => static property (or function), which allows an access to object.

Let’s see the code:

Read more…

Categories: .Net, Design Tags: , , ,

.Net Framework 4.0 and VS2010 – things that I don’t like

March 11th, 2011 No comments

There are many great improoves (e.g. TPL – see my post about Task Parallel Library)

Still, there are some disadvantages, I would like to list:

1. Help interface is uncomfortable, there is no possibility to search by Index like it was working in “chm” in VS2003-8

Update: after installing Visual Studio 2010 Service Pack 1 (SP1) – help user interface become more user friendly and handy.
2. CLR debugger doesn’t working any more (SDK v2.0) – such behavior is very crucial for our clients and deployment process.

  • Native code debugger cause my VS2010 to stuck all the time.

3. GAC changes – why v2.0 and v4.0 assemblies are located in different locations?
a. Why simple copy/paste operation doesn’t working like its work today with c:\windows\assemblies directory.
b. Why we need to manage two different GAC’s?
Detailed info regarding GAC can be found here: http://msdn.microsoft.com/en-us/magazine/dd727509.aspx

Read more…

Categories: .Net Tags: ,

NHibernate configuration, set database connection credentials

March 11th, 2011 No comments

NHibernate configuration, set database connection credentials

Our team started to use NHibernate ORM, it used in part of the components of our Application (Mostly stand alone services).
There are interesting issues bloomed up:
How to use the same DB credentials while you are using NHibernate and standard ADO approach to retrieve, save and update your data. We have plenty Legacy code that cannot move to use NHibernate configuration file. Our main application used standard sql connection string from App.Config file, of cause we doesn’t want to maintain two configuration files.

“hibernate.cfg.xml” file contains basic configuration settings, used by NHibernate; for more detail see … [web site] User Id=;Password=;Data Source=;Pooling=false

Read more…

Categories: .Net, NHibernate Tags: ,

.Net 4.0 first tasting – Task Parallel Library (TPL)

March 11th, 2011 1 comment

Finally our project was “upgraded” to VS2010 and .Net 4.0, we was waiting anxiously for that event.
In first opportunity I have tried to use new language/Framework features like Parallel.Foreach and PLINQ.

My task was to aggregate duration time of recorded stuff (it doesn’t really matter what data I needed to sum). In order to retrieve required data and calculate it – we have had to communicate with the server (TCP protocol). Such operations of course are time consuming so I decided to use Parallel.Foreach.

See following code example:

15 public TimeSpan GetRecordedDuration(int recordingId)

16 {

17       TimeSpan duration = TimeSpan.Zero;

18       Parallel.ForEach(GetGroups(recordingId), group =>

19       {

20

21         var bookmarks = m_clientRecordingSys.GetGroupBookmarks(StreamsNames.VideoSourceName, group);

22         if (bookmarks.Count <= 1)

23         {

24             continue;

25         }

26         else

27       {

28       var startTime = TimeSpan.FromTicks(bookmarks[0].CreationTime);

29 var endTime   = TimeSpan.FromTicks(bookmarks[bookmarks.Count – 1].CreationTime);

30 duration += endTime – startTime;

31    }

32  }

33    );

34   return duration;

35

36 }

37

38 }

Read more…

Categories: .Net Tags: ,

How to remove Oracle client

March 7th, 2011 No comments

In case that regular uninstall wizard is failing from any reason you always may remove client manually – by following this steps.

1. Remove Installation directory c:\Oracle
2. Remove c:\Program Files\Oracle
3. Remove Registry key HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE

Reinstall Oracle client again, hopefully your problem with the client will be solved – it worked for me number of times.

Categories: General Tags: , ,

Effective iteration over STL container.

March 6th, 2011 No comments

Today I had a chance to recall a little bit, what is STL and how should it be used effectively.
Let’s take a brief look of the next code in C++, which makes iteration over STL’s map:

std::map<int, std::string> 		myMap;
std::map<int, std::string>::iterator	myIter;

for (myIter = myMap.begin(); myIter != myMap.end(); myIter++) //bad performance
{
	std::cout << *myIter << std::endl;
}

Can you see the performance problem? Actually there are 2:

1) The loop checks the stop condition every iteration, i.e. compares iterator to the value returned by “myMap.end()”.
The “end” function is called in every iteration, even though the return value doesn’t change during the loop.

2) Using postfix operator++ is more expensive then prefix operator, because postfix operator must make a local copy of the object. Object is created by the copy constructor, and if the object is “heavy” enough, this additional action could harm the performance. Lets compare implementations of both operators:

iterator& operator++()
{
	_Ptr = _Acc::_Next(_Ptr);
	return (*this);
}

iterator operator++(int)
{
	iterator _Tmp = *this; // Calling the copy constructor
	++*this;
	return (_Tmp);
}

Hence, we should do very easy changes, and the improved code looks like this:

std::map<int, std::string> 		myMap;
std::map<int, std::string>::iterator	myIter, endIter = myMap.end() ;

for (myIter = myMap.begin(); myIter != endIter; ++myIter) //good  performance
{
	std::cout << *myIter << std::endl;
}

Remark:
Many good advices about effective using STL library are described in a book “Effective STL” by Scott Meyers.

Categories: C++ Tags: ,

SVN & UTF 8 Encoded file names error on Debian Linux

March 6th, 2011 No comments

An interesting error occurred today, while trying to do any SVN command I got the message:

svn: Valid UTF-8 data

(hex:)

followed by invalid UTF-8 sequence

(hex: b8 b4 bc fe)

It took me a while to get the solution, but there it is: it happens because there is some corruption in file names (usually from Windows). The solution was simple – to narrow the search for the folder with the corrupted file name, delete the corrupted file and then check it out from the repository again.

Special thanks to: http://ryanerwin.com/2007/04/09/valid-utf-8-data-hex-followed-by-invalid-utf-8-sequence/

Categories: General Tags: , , ,

Janus GridEx customizable cell content

March 5th, 2011 No comments

Recently i had accomplished interesting task, which include to add time duration data to one of the existing Grids in our Winform desktop application. We are working with 3rdParty controls Janus (Janus.Windowa.GridEx).

Unfortunately not all our controls are WPF, so we still need to “struggle” WinForms to make any special changes in UI.

The problem was that our product manager wanted to make usage of the same visual column for different types of data – such as >int and System.TimeSpan. As you can see they have completely different presentation.
00:00:03.45334
After some thinking we have decided to add additional column of Type Syste.TimeSpan and make this column hidden to the end user.

MyColumns = m_gridControl.RootTable.Columns;
MyColumns["durationColumnName"].Visible = false;

Read more…

Categories: .Net, C# Tags: , ,

Bitmap construction from raw buffer in C#.NET

March 4th, 2011 No comments

Recently, I needed to get an image’s buffer from the network, and to store it in a file system.
If needed to work with image files, one can use a C#.NET “Bitmap” class, existing within “System.Drawing” namespace.

This class encapsulates a GDI+ bitmap and supports the next formats: BMP, PNG, JPG, GIF, TIFF and EXIF.
And it has a good API. It is very friendly class. After the object exists, saving appropriate file is a straight forward action:


Bitmap bitmap = ...
bitmap.Save("TargetImageFileName.bmp"); //format selection is possible

But, how the “Bitmap” object should be created from given buffer in memory?
Quick search in MSDN supplied the next solution:


Byte[] buffer = Proxy.GetImageBuffer();
ImageConverter converter = new ImageConverter();
Image image = (Image) converter.ConvertFrom(buffer);
Bitmap bitmap = new Bitmap(image);

// Work with the bitmap ...

This could be a great solution, but not in given case.
The ”ConvertFrom” function of  ”ImageConverter” is looking for image’s header. The buffer contains a pure raw data, and hence is decoded in a wrong way. As a result of memory corruption, ”ArgumentException” is thrown.

So, what is good solution?

In order to initialize “Bitmap” object from a raw data buffer, first we must supply image’s metadata. We must “teach” the Bitmap object about image, it is going to contain.


public Bitmap CreateBitmapFromRawDataBuffer(byte[] buffer)
{
        // Prepare required image's metadata.
        Size imageSize = new Size(300, 200); // Known size.
        PixelFormat imagePixelFormat = PixelFormat.Format16bppGrayScale; // Known type.

        // Set bitmap known image's metadata.
        Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);

        // Prepare working rectangle.
        Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

        // Lock all bitmap's pixels.
        BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);

        // Copy the buffer into bitmapData.
        Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);

        // Unlock  all bitmap's pixels.
        bitmap.UnlockBits(bitmapData);

        return bitmap;
}

That’s all. It works. Use carefully.

Categories: .Net Tags: ,

Using Debug.Assert while writing .Net code

March 3rd, 2011 No comments

Using Debug.Assert while writing .Net code

Today we have got new version of some product from other Team (component to retrieve data from DB). During our integration we have failed to run their code – got very strange errors ant etc.
Team which was responsible for this part of the project claimed that they checked everything and all functioning – but they did their tests only for Debug version of the Assemblies.

In .Net debug and release there shouldn’t be any difference in functionality Debug build version might be little bit slower. So we suspected in thread race problems and other weired stuff.

After several ours of debugging and phone calls with another team we have found the problem … it was really sad or funny to discover such simple mistake that developer can do.

See the following code:

public void DoSomething()
{

Debug.Assert(Foo());

}

public bool Foo()
{
//calculate something 
//set some data
}

command shown above is part of System.Diagnostics namespace useful for Debugging and making sure that code flow is working as designed by developer.
As you can see the problem in this code is that method called from Assertion. Very important not to call methods from Debuug.Assert this line of code will be removed by compiler during Release compilation.

The fixed code looks like this:
public void DoSomething()
{

bool res = Foo();

Debug.Assert(res);

}

public bool Foo()
{
//calculate something
//set some data

return sucsessFlag;

}
So the code flow doesn’t affected by the Assertion.
This looks small issue but believe me, very painful when it happening before version release :).

Categories: .Net Tags: ,

Asynchronous messaging using JMS on WebSphere 7.0

March 3rd, 2011 17 comments

Recently I had to create quick integration for two J2EE applications. Both application use IBM

Web Sphere 7.0 as Application server. Both of J2EE applications use topics/queues as destinations. What I needed to do is to write small application that will read from destination and write to different destination. In this post I will introduce you with a simple J2SE JMS example and how to deploy it/test it on WebSphere 7.0. In an enterprise application is common to use asynchronous messaging. It is useful when you have to deliver a message (even if the destination is down) and you do not wait for a response in real time. In Java, we’ve got the JMS (Java Messaging Service) to work with asynchronous messaging.

Setting up the JMS Provider and the Destination

Let's start with server side configuration. This setup is made only once, here we create an Integration Bus, JMS Provider, Connection Factory, Destination (in this case it will be a queue) and Activation specifications. There are many different JMS providers but we will use Websphere Application Server 7.0 JMS Provider.

Creating the Service Integration BUS (SIB)

Run the Websphere Application Server (you can do that through the Server Perspective, right click on WAS -> Start) and open its Administrative Console (right click on WAS -> Administration -> Run Administrative console). There, go to the MENU Service Integration and click on Buses.

  • On the buses screen, click on New button.
  • Next, insert the name JMSBus and then click Next and Finish.
  • Back to the Buses screen, click on Save link and then the MDBus will be created and committed.

Now, click on JMSBus link to open a new screen. We’re going to use the three links on the right side. The first one is the Bus Member. Click on it. On the next screen, click on Add button. Choose the first option Server.

  • Click on Next
  • choose File store and Next again.
  • On third screen, change the values: Log size: 10, Minimum permanent store size: 20, Maximum permanent store size: 50,
  • Click on Next button, Finish and Save link.

Now, let’s create the Destionations. Few words about destinations, destination has a type (queue or topic) and a name. We can use simple api's and create destination on the fly : Destination destination = session.createQueue(“HelloWorld”); But in our case we will use Websphere and create destination there. Go back to the JMSBus screen and click on Destinations link.

  • Click on New button
  • Select Queue and click on Next
  • Enter: JMSQueue as Identifier. Also, click on Next.
  • Click on Next again.
  • Finally, click on Finish.

The SIB (Service Integration Buses) is created. The next step is to create the JMS Provider. Let’s do it.

Creating the JMS Provider

Go to the menu Resources -> JMS -> JMS Providers. Select Default messaging provider where in the scope column you can find same node name where Service Integration Bus was created in previous step. On the Default messaging provider screen, let’s create the Queue connection factory, Queue and the Activation Specification.

Creating the Queue Connection factory

Click on Queue Connection factories link. On the new screen, click on New button. On the new screen, fill up the following fields:

  • Name (JMSQueueCF)
  • JNDI name (jms/messageCF)
  • Bus name (JMSBus)

Click on Ok button and then Save link.

Creating the Queue

Click on Queue link and then New button. On the new screen, fill up the following fields:

  • Name (JMSQueue)
  • JNDI name (jms/messageQueue)
  • Bus name (JMSBus)
  • Queue name (JMSQueue)

Click on Ok button and then Save link.

Creating the Activation specifications

Click on Activation specifications link and then click on New button. On the new screen, fill up the following fields.

  • Name (JMSActivationSpec)
  • JNDI name (jms/activationSpec)
  • Destination type (Queue)
  • Destination JNDI name (jms/messageQueue)
  • Bus name (JMSBus)

Click on OK button and then Save link. Both SIB and the JMS Provider were setup. Make sure to restart the Websphere server before continue this article.

Creating JMS Sender/ Receiver Client

Now we will create pair of simple applications based on what we just discussed. The first will send a message to a JMSQueue which was created in previous step. The second application will receive the message off of that Queue.

Message Sender application

First we will create an interface with Message sender methods:

public interface IMessageSender { void close() throws Exception; void send(String message) throws Exception; void connect(String hostname, String portNumber, String QueueName) throws Exception; }

Now let's implement this interface:

public class JMSMessageSender implements IMessageSender { Connection connection=null; Session producerSession = null; MessageProducer producer = null; @Override public void close() throws JMSException { //close resources if (producer != null) { producer.close(); } if (producerSession!=null){ producerSession.close(); } if (connection!=null){ connection.close(); } } @Override public void connect(String hostname, String portNumber, String QueueName) throws Exception { //Here we prepare correct naming to work with WebSphere Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, "iiop://"+hostname+":"+portNumber+""); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory"); InitialContext initialContext = new InitialContext(env); // creating a connection factory ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("jms/messageCF"); // create destination Destination destSend = (Destination)initialContext.lookup(QueueName); // create a connection connection = connectionFactory.createConnection(); System.out.println("* connection created..."); // create a session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create a producer producer = producerSession.createProducer(destSend); } @Override public void send(String message) throws JMSException { TextMessage textMessage; textMessage = producerSession.createTextMessage(message); if (producer != null) { //send message to JMS queue producer.send(textMessage); } } }

There is nothing special in the code above. We implemented method connect where we created connection factory using naming WebSphere naming convention then we created connection, session producer and destination. Now let's talk about not trivial stuff. If server and SIB service differs from default configuration we will face a problem connecting to a server and to our JMSQueue. Few things need to be checked in that case. In Websphere Administration console open : Servers->Application servers -> server1(my server name) -> Ports in communication tab. In the Ports tab check ports for Bootstrap server and for SIB_END_POINT. BOOTSTRAP_ADDRESS port need to be used as portnumber in the Connect method: And if SIB_END_POINT differs from 7276 (which is default sib service port) we need to change it in the WebSphere Queue Connection factory

The instead to on 5 been ago lexapro 30 on next time dab so lipitor generic else to believe and be bottles. I generic lipitor disks can that me this? Months the. More bottle, http://flagylgeneric-online.net/ the is. The to. Found hair your anything cipro 500 mg the. Painful, auburn. Why rating perfectly. This buy flagyl online which, my is. Will as a. Use http://lexapropharmacy-generic.net/ Got with Cream is a heating, nexium roadian tires I product face spots never alternativmedikament zu celebrex couple with! Had looked products. This regularly to if facial celebrex dosage nuthing for itchy for gave of ambasciata cipro roma babysitter’s/school you block really PRODUCT-FANTASTIC a it.

properties. Resources-> JMS -> Queue Connection factories -> select JMSQueueCF and add to Provider endpoints new servername:SIB_ENDPOINT_ADDRESS:transport chain name:

Message Receiver application

First we will create an interface with Message receiver methods:

public interface IMessageReceiver { void close() throws Exception; TextMessage receive() throws Exception; void connect(String hostName, String portNumber, String connectionFactoryString, String consumerJNDIName) throws Exception;

}

Now let's implement this interface:

public class JMSMessageReceiver implements IMessageReceiver { Connection connection = null; Session consumerSession = null; MessageConsumer consumer = null; @Override public void close() throws Exception { //close resources if (consumer != null) { consumer.close(); } if (consumerSession!=null){ consumerSession.close(); } if (connection!=null){ connection.close(); } } @Override public void connect(String hostName, String portNumber, String connectionFactoryString, String consumerJNDIName) throws Exception { Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, "iiop://"+hostName+":"+portNumber+""); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory"); InitialContext initialContext = new InitialContext(env); ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryString); connection = connectionFactory.createConnection(); connection.start(); // create destination - JMSQueue Destination destinationReceiver = (Destination)initialContext.lookup(consumerJNDIName); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = consumerSession.createConsumer(destinationReceiver); } @Override public TextMessage receive() throws Exception { TextMessage msg = (TextMessage) consumer.receive(); return msg; } }

The code above is similar to sender implementation. We implemented method connect where we created connection factory using naming WebSphere naming convention then we created connection, session producer and destination.

Creating Testing Application

Now we will create simple J2SE application that will send and receive messages from WebSphere Queue that was created.

package client; import javax.jms.*; import message.IMessageReceiver; import message.IMessageSender; import message.JMSMessageReceiver; import message.JMSMessageSender; public class JMSTester { public static void main(String[] args) { String hostName = "localhost"; String hostPort = "2810"; String QueueName="jms/messageQueue"; String ConnectionFactoryName= "jms/messageCF"; IMessageSender messageSender = null; IMessageReceiver messageReceiver =null; messageSender = new JMSMessageSender(); try { System.out.println("calling messageSender connect(" + hostName +", " + hostPort + ", " + QueueName + ")"); messageSender.connect(hostName, hostPort, QueueName); } catch (Exception e) { System.out.println(e.getMessage()); } try { String message = "Hello World"; messageSender.send(message); System.out.println("send message(" + message + ")"); } catch (Exception e) { System.out.println(e.getMessage()); } messageReceiver = new JMSMessageReceiver(); try { System.out.println("calling messageReceiver connect(" + hostName +", " + hostPort + ", " + ConnectionFactoryName + ", " + QueueName + ")"); messageReceiver.connect(hostName, hostPort, ConnectionFactoryName, QueueName); } catch (Exception e) { System.out.println(e.getMessage()); } try { // receive our message TextMessage m = messageReceiver.receive(); System.out.println("Received message(" + m.getText() + ")"); } catch (Exception e) { System.out.println(e.getMessage()); } } }

Compiling JMS code

Now that you have created the JMS components and defined them in JNDI, we must make WebSphere Application Server to support our client. To do this download and install sibc.jms.jar , sibc.jndi.jar into the project. Look at the Console view, the whole producing and consuming messaging process, will be printed on the console, like image below. The article ends here. It was a simple article, but I think it was a good starting point for whom wants to get started on JMS world. Hope it was fun. See you on the next article.

zp8497586rq
Categories: Java Tags: , ,

Finally we are up!

March 3rd, 2011 1 comment

Welcome to our web blogging site …

We hope you will enjoy this blog as we do 🙂

Categories: General Tags: