tag:blogger.com,1999:blog-17853012469376721052024-02-20T13:14:36.411+00:00ESR Tech BlogUnknownnoreply@blogger.comBlogger12125tag:blogger.com,1999:blog-1785301246937672105.post-6121113818203346312016-12-29T13:27:00.004+00:002016-12-29T14:58:17.574+00:00Java syntax highlight in Blogger<span style="font-family: "trebuchet ms" , sans-serif;">SyntaxHighlighter is one of the most widely used syntax highlighter for webs and blogs. It is an open source Java Script client side library that adds an IDE look and feel view to your code snippets. </span><br />
<span style="font-family: "trebuchet ms" , sans-serif;">The documentation for version 3.0.83 (latest version at the time of writing this post) can be found </span><a href="http://alexgorbatchev.com/SyntaxHighlighter/" style="font-family: "Trebuchet MS", sans-serif;">here</a><span style="font-family: "trebuchet ms" , sans-serif;">.</span>
<br />
<br />
<h3>
<span style="font-family: "trebuchet ms" , sans-serif;">Using SyntaxHighlighter </span></h3>
<span style="font-family: "trebuchet ms" , sans-serif;">Before making any changes, please take a backup of your Blogger template you want to customize. Paste the following code before </head> tag in the HTML of your template and save the changes.</span><br />
<pre class="brush: xml" type="syntaxhighlighter">
<link href="http://agorbatchev.typepad.com/pub/sh/3_0_83/styles/shCore.css" rel="stylesheet" type="text/css" />
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shCore.js" type="text/javascript" />
<link href="http://agorbatchev.typepad.com/pub/sh/3_0_83/styles/shThemeDefault.css" rel="stylesheet" type="text/css" />
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushJava.js" type="text/javascript" />
<script language="javascript" type="text/javascript">
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = "http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/clipboard.swf";
SyntaxHighlighter.all();
</script>
</pre>
<br />
<span style="font-family: "trebuchet ms" , sans-serif;">First I added the base files </span><span style="font-family: "courier new" , "courier" , monospace;">shCore.css</span><span style="font-family: "trebuchet ms" , sans-serif;"> and </span><span style="font-family: "courier new" , "courier" , monospace;">shCore.js</span><span style="font-family: "trebuchet ms" , sans-serif;"> needed for the syntax highlighter to work. Then I chose the default theme </span><span style="font-family: "courier new" , "courier" , monospace;">shThemeDefault.css</span><span style="font-family: "trebuchet ms" , sans-serif;"> that comes with white background. Finally, I added the syntax highlighter for Java (</span><span style="font-family: "courier new" , "courier" , monospace;">shBrushJava.js</span><span style="font-family: "trebuchet ms" , sans-serif;">).</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><br /></span>
<span style="font-family: "trebuchet ms" , sans-serif;">Note that I used a specific version of the library here. Most examples I have seen point to the current version under </span><span style="font-family: "courier new" , "courier" , monospace;">http://agorbatchev.typepad.com/pub/sh/current</span><span style="font-family: "trebuchet ms" , sans-serif;">, which is fine. However, if you have the HTTPS redirection enabled in your blog, the syntax highlight will not work properly as the Blogger engine will try to get the files from </span><span style="font-family: "courier new" , "courier" , monospace;">https://agorbatchev.typepad.com/pub/sh/current</span><span style="font-family: "trebuchet ms" , sans-serif;">, which is not available throwing a 404 error</span><span style="font-family: "trebuchet ms" , sans-serif;">.</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><br /></span>
<span style="font-family: "trebuchet ms" , sans-serif;">After we configured the library in the template's head section we have to options make use of the functionality:</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><br /></span>
<span style="font-family: "trebuchet ms" , sans-serif;"><b>pre method:</b> It is the most reliable of the methods as it works everywhere. The only drawback is that any code within the tag has to be escaped.</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><b>script method:</b> If we don't want to escape your code we can use this method. Inside the CDATA we can put anything. The problem with </span><span style="font-family: "courier new" , "courier" , monospace;">script </span><span style="font-family: "trebuchet ms" , sans-serif;">is that it's not supported everywhere, including Blogger.</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><br /></span>
<span style="font-family: "trebuchet ms" , sans-serif;">We will make use of the </span><span style="font-family: "courier new" , "courier" , monospace;">pre </span><span style="font-family: "trebuchet ms" , sans-serif;">method here. Let's add a pre block with the escaped Java code snippet in your post HTML editor:</span><br />
<pre class="brush: xml"><pre class="brush: java">public static void printPersonsWithinAgeRange(
List&lt;Person&gt; roster, int low, int high) {
for (Person p : roster) {
if (low &lt;= p.getAge() &amp;&amp; p.getAge() &lt; high) {
p.printPerson();
}
}
}
</pre>
</pre>
<span style="font-family: "trebuchet ms" , sans-serif;">After we save the changes we should see the code highlighted in the post preview:
</span><br />
<pre class="brush: java">public static void printPersonsWithinAgeRange(
List<Person> roster, int low, int high) {
for (Person p : roster) {
if (low <= p.getAge() && p.getAge() < high) {
p.printPerson();
}
}
}
</pre>
<br />
<h3>
<span style="font-family: "trebuchet ms" , sans-serif;">Other Themes</span></h3>
<span style="font-family: "trebuchet ms" , sans-serif;">There are a few themes available in SyntaxHighlighter which can completely change the look and feel of the highlighted syntax by including the desired CSS. For more information about the themes visit the <a href="http://alexgorbatchev.com/SyntaxHighlighter/manual/themes/">themes page</a>.</span><br />
<span style="font-family: "trebuchet ms" , sans-serif;"><br /></span>
<span style="font-family: "trebuchet ms" , sans-serif;">If you want to try them out click on the link to theme:</span><br />
<ul>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeDefault.css')">Default</a></li>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeDjango.css')">Django</a></li>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeEmacs.css')">Emacs</a></li>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeFadeToGrey.css')">Fade To Grey</a></li>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeMidnight.css')">Midnight</a></li>
<li><a href="http://www.blogger.com/post-edit.do#" onclick="return addcss('shThemeRDark.css')">RDark</a></li>
</ul>
<br />
<br />
<h3>
<span ms="" sans-serif="" style="font-family: "trebuchet ms" , sans-serif;" trebuchet="">Available Brushes
</span></h3>
<div>
<span ms="" sans-serif="" style="font-family: "trebuchet ms" , sans-serif;" trebuchet="">Pretty much all main programming and scripting languages are supported by the library. We just have to include the brushes we want to use in the head section. Here is a list of the ones supported: </span></div>
<div>
<span data-blogger-escaped-style="font-family: " ms="" sans-serif="" trebuchet=""><br /></span></div>
<pre class="brush: xml" data-blogger-escaped-type="syntaxhighlighter">
<!-- Action Script 3 -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushAS3.js" type="text/javascript" />
<!-- Bash/Shell -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushBash.js" type="text/javascript" />
<!-- Cold Fusion -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushColdFusion.js" type="text/javascript" />
<!-- C# -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushCSharp.js" type="text/javascript" />
<!-- C++ -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushCpp.js" type="text/javascript" />
<!-- CSS -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushCss.js" type="text/javascript" />
<!-- Delphi -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushDelphi.js" type="text/javascript" />
<!-- Diff -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushDiff.js" type="text/javascript" />
<!-- Erlang -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushErlang.js" type="text/javascript" />
<!-- Groovy -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushGroovy.js" type="text/javascript" />
<!-- JavaScript -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushJScript.js" type="text/javascript" />
<!-- JavaFX -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushJavaFX.js" type="text/javascript" />
<!-- Perl -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushPerl.js" type="text/javascript" />
<!-- PHP -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushPhp.js" type="text/javascript" />
<!-- Plain Text -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushPlain.js" type="text/javascript" />
<!-- Power Shell -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushPowerShell.js" type="text/javascript" />
<!-- Python -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushPython.js" type="text/javascript" />
<!-- Ruby -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushRuby.js" type="text/javascript" />
<!-- Scala -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushScala.js" type="text/javascript" />
<!-- SQL -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushSql.js" type="text/javascript" />
<!-- Visual Basic -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushVb.js" type="text/javascript" />
<!-- XML -->
<script src="http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushXml.js" type="text/javascript" />
</pre>
<br />
<h3>
<span style="font-family: "trebuchet ms" , sans-serif;">New version</span></h3>
<span style="font-family: "trebuchet ms" , sans-serif;">If you want to try out the new version, the source code and documentation for SyntaxHighlighter can be found in <a href="https://github.com/syntaxhighlighter/syntaxhighlighter">GitHub</a>. There is a 4.0.1 tag in the repository but we could not find a hosted version to refer to. </span>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-11475765072661156122012-05-27T21:24:00.000+01:002012-05-28T22:00:13.884+01:00Getting started with PuppetPuppet is a system for automating system administration tasks. You can find a brief introduction <a href="http://puppetlabs.com/puppet/what-is-puppet/">here</a>.<br />
<br />
Although it is difficult to get your head around Puppet, once you understand the architecture and get acquainted with the language you wish you learnt it earlier. Here are some material that will help you get up to speed with Puppet:
<br />
<br />
<b>Books</b><br />
<br />
<ul>
<li><a href="http://www.amazon.co.uk/Managing-Infrastructure-Puppet-James-Loope/dp/1449307639">Managing Infrastructure with Puppet</a> </li>
<li><a href="http://books.sysadmins.su/system/files/Pro.Puppet.pdf">Pro Puppet</a> </li>
<li><a href="http://www.amazon.co.uk/Puppet-2-7-Cookbook-John-Arundel/dp/1849515387">Puppet Cookbook</a></li>
</ul>
<b>Source Code </b><br />
<br />
<ul>
<li><a href="http://forge.puppetlabs.com/">Puppet Forge</a> </li>
</ul>
<br />
<b>Documentation </b><br />
<br />
<ul>
<li><a href="http://docs.puppetlabs.com/">Puppet Labs Documentation</a> </li>
<li><a href="http://docs.puppetlabs.com/learning/">Learning Puppet</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-77783499628965497652011-05-24T21:50:00.003+01:002011-05-24T21:54:04.536+01:00How to bind session beans to JNDI in JBoss<b>Introduction</b><br />
To override the default way session beans bind to JNDI in JBoss you can use <b>@LocalBinding</b> or <b>@RemoteBinding</b> annotations. Please note that these annotations are not standard on the EJB3 specification, they are JBoss specific (they are located in org.jboss.ejb3.annotation). This post is based on JBoss Documentation - <a href="http://docs.jboss.org/ejb3/docs/tutorial/1.0.7/html/JNDI_Bindings.html">Binding your beans in JNDI</a>.<br />
<br />
<b>1. Maven configuration</b><br />
The following dependencies need to be added to your pom to get the LocalBinding and RemoteBinding working:<br />
<br />
<pre class="brush: xml"><dependency>
<groupid>org.jboss.ejb3</groupId>
<artifactid>jboss-ejb3-ext-api</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupid>org.jboss.javaee</groupId>
<artifactid>jboss-ejb-api</artifactId>
</exclusion>
<exclusion>
<groupid>org.jboss.metadata</groupId>
<artifactid>jboss-metadata</artifactId>
</exclusion>
</exclusions>
</dependency>
</pre><br />
<b>2. Local JNDI Binding</b><br />
The <b>@LocalBinding</b> annotation allows you to change the JNDI name for an EJB local interface. The following code snippet shows the usage:<br />
<br />
<pre class="brush: java">package com.example.local;
import org.jboss.ejb3.annotation.LocalBinding;
@Local
@LocalBinding(jndiBinding = "ExampleService/local")
public interface ExampleService {
}
</pre><br />
The previous EJB will bind with to JNDI as <b>ExampleService/local</b>. The server log shows the EJB has been deployed as described: <br />
<br />
<pre class="brush: xml">2011-05-08 08:20:20,306 117281 INFO [org.jboss.ejb3.session.SessionSpecContainer] (RMI TCP Connection(10)-127.0.0.1:) Starting jboss.j2ee:ear=example.ear,jar=example-ejbs-1.0.0.jar,name=ExampleServiceImpl,service=EJB3
2011-05-08 08:20:20,306 117281 INFO [org.jboss.ejb3.EJBContainer] (RMI TCP Connection(10)-127.0.0.1:) STARTED EJB: com.example.ejbs.ExampleServiceImpl ejbName: ExampleServiceImpl
2010-05-08 08:20:20,353 117328 INFO [org.jboss.ejb3.proxy.impl.jndiregistrar.JndiSessionRegistrarBase] (RMI TCP Connection(10)-127.0.0.1:) Binding the following Entries in Global JNDI:
ExampleService/local - EJB3.x Default Local Business Interface
example/ExampleServiceImpl/local-com.example.local.ExampleService - EJB3.x Local Business Interface
</pre><br />
<b>3. Remote Interface JNDI Binding</b><br />
The <b>@RemoteBinding</b> annotation allows you to change the JNDI name for an EJB remote interface. The following code snippet shows the usage:<br />
<br />
<pre class="brush: java">package com.example.remote;
import org.jboss.ejb3.annotation.RemoteBinding;
@Remote
@RemoteBinding(jndiBinding="ExampleService/remote")
public interface ExampleService {
}
</pre><br />
The server log shows the following JNDI names:<br />
<br />
<pre class="brush: xml">2010-05-08 08:20:21,306 117281 INFO [org.jboss.ejb3.session.SessionSpecContainer] (RMI TCP Connection(10)-127.0.0.1:) Starting jboss.j2ee:ear=example.ear,jar=example-ejbs-1.0.0.jar,name=ExampleServiceImpl,service=EJB3
2010-05-08 08:20:21,306 117281 INFO [org.jboss.ejb3.EJBContainer] (RMI TCP Connection(10)-127.0.0.1:) STARTED EJB: com.example.ejbs.ExampleServiceImpl ejbName: ExampleServiceImpl
2010-05-08 08:20:21,353 117328 INFO [org.jboss.ejb3.proxy.impl.jndiregistrar.JndiSessionRegistrarBase] (RMI TCP Connection(10)-127.0.0.1:) Binding the following Entries in Global JNDI:
ExampleService/remote - EJB3.x Default Remote Business Interface
example/ExampleServiceImpl/remote-com.example.remote.ExampleService - EJB3.x Remote Business Interface
</pre><br />
<b>4. More over RemoteBindings</b><br />
By default JBoss EJB3 uses a socket based invoker layer on port 3878 (i.e. socket://0.0.0.0:3878). It is possible, for example, to use SSL as the transport (i.e. sslsocket://0.0.0.0:3843). You can find plenty of documentation on how to enable SSL transport on your EJBs. <br />
<br />
You can also enable different types of communication for your beans:<br />
<br />
<pre class="brush: java">package com.example.remote;
import org.jboss.ejb3.annotation.RemoteBindings;
import org.jboss.ejb3.annotation.RemoteBinding;
@Remote
@RemoteBindings(
{
@RemoteBinding(jndiBinding="custom/ExampleService/remote"),
@RemoteBinding(jndiBinding="custom/ExampleServiceImpl/remote", clientBindUrl="socket://0.0.0.0:3333"),
@RemoteBinding(jndiBinding="ssl/ExampleServiceImpl/remote", clientBindUrl="sslsocket://0.0.0.0:3843")
}
)
public interface ExampleService {
}
</pre><br />
The server.log file shows the following JNDI names:<br />
<br />
<pre class="brush: xml">2010-05-08 08:20:20,306 117281 INFO [org.jboss.ejb3.session.SessionSpecContainer] (RMI TCP Connection(10)-127.0.0.1:) Starting jboss.j2ee:ear=example.ear,jar=example-ejbs-1.0.0.jar,name=ExampleServiceImpl,service=EJB3
2010-05-08 08:20:20,306 117281 INFO [org.jboss.ejb3.EJBContainer] (RMI TCP Connection(10)-127.0.0.1:) STARTED EJB: com.example.ejbs.ExampleServiceImpl ejbName: ExampleServiceImpl
2010-05-08 08:20:20,353 117328 INFO [org.jboss.ejb3.proxy.impl.jndiregistrar.JndiSessionRegistrarBase] (RMI TCP Connection(10)-127.0.0.1:) Binding the following Entries in Global JNDI:
custom/ExampleService/remote - EJB3.x Default Remote Business Interface
custom/ExampleServiceImpl/remote - EJB3.x Default Remote Business Interface
ssl/ExampleServiceImpl/remote - EJB3.x Default Remote Business Interface
example/ExampleServiceImpl/remote-com.example.remote.ExampleService - EJB3.x Remote Business Interface
</pre>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1785301246937672105.post-72377540727206437092011-04-20T21:34:00.003+01:002016-12-28T11:27:59.309+00:00How to configure XA transactions with Microsoft SQL Server and TIBCO EMS Server in JBossThis article describes the processes involved in enabling XA transactions within an SQL Server and TIBCO EMS environment.<br />
<br />
Prerequisites<br />
1. SQL Server JDBC Driver<br />
2. JBoss 5.1.0<br />
3. TIBCO EMS server <br />
4. An SQL Server 2000/2005 instance<br />
<br />
<b>Enabling XA transactions in SQL Server:</b><br />
1. Download the SQL Server JDBC Driver from <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=a737000d-68d0-4531-b65d-da0f2a735707">here</a> and unzip the file.<br />
<br />
2. Prior to running the SQL script you must copy the extended stored procedure dll SQLJDBC_XA.dll to the target SQL Server's Binn folder (typically in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn).<br />
<br />
3. Permissions to the distributed transaction support procedures for the Microsoft SQL Server JDBC Driver 2.0 are granted through the SQL Server role SqlJDBCXAUser. To maintain a secure default configuration, no user is granted access to this role by default.<br />
<br />
4. Run the following SQL script in the target SQL Server:<br />
<br />
<pre class="brush: sql">use master
go
-- Drop any existing procedure definitions.
exec sp_dropextendedproc 'xp_sqljdbc_xa_init'
exec sp_dropextendedproc 'xp_sqljdbc_xa_start'
exec sp_dropextendedproc 'xp_sqljdbc_xa_end'
exec sp_dropextendedproc 'xp_sqljdbc_xa_prepare'
exec sp_dropextendedproc 'xp_sqljdbc_xa_commit'
exec sp_dropextendedproc 'xp_sqljdbc_xa_rollback'
exec sp_dropextendedproc 'xp_sqljdbc_xa_forget'
exec sp_dropextendedproc 'xp_sqljdbc_xa_recover'
exec sp_dropextendedproc 'xp_sqljdbc_xa_rollback_ex'
exec sp_dropextendedproc 'xp_sqljdbc_xa_forget_ex'
exec sp_dropextendedproc 'xp_sqljdbc_xa_prepare_ex'
exec sp_dropextendedproc 'xp_sqljdbc_xa_init_ex'
go
-- Install the procedures.
exec sp_addextendedproc 'xp_sqljdbc_xa_init', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_start', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_end', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_prepare', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_commit', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_rollback', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_forget', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_recover', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_rollback_ex', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_forget_ex', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_prepare_ex', 'SQLJDBC_XA.dll'
exec sp_addextendedproc 'xp_sqljdbc_xa_init_ex', 'SQLJDBC_XA.dll'
go
-- Create the [SqlJDBCXAUser] role in master database.
-- The SQL administrator can later add users to this role to allow users to participate
-- in Microsoft SQL Server JDBC Driver 2.0 distributed transactions.
sp_addrole [SqlJDBCXAUser]
go
-- Grant privileges to [SqlJDBCXAUser] role to the extended stored procedures.
grant execute on xp_sqljdbc_xa_init to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_start to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_end to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_prepare to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_commit to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_rollback to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_recover to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_forget to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_rollback_ex to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_forget_ex to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_prepare_ex to [SqlJDBCXAUser]
grant execute on xp_sqljdbc_xa_init_ex to [SqlJDBCXAUser]
go
-- Add users to the [SqlJDBCXAUser] role as needed.
-- Example for adding a SQL authentication user to the SqlJDBCXAUser role.
-- exec sp_addrolemember [SqlJDBCXAUser], 'MySQLUser'
-- Example for adding a windows domain user to the SqlJDBCXAUser role.
-- exec sp_addrolemember [SqlJDBCXAUser], 'MyDomain\MyWindowsUser'
print ''
print 'SQLJDBC XA DLL installation script complete.'
print 'Check for any error messages generated above.'
</pre><br />
5. From Control Panel, open Administrative Tools, and then open Component Services. You can also click the Start button, click Run, type dcomcnfg in the Open box, and then press OK to open Component Services.<br />
<br />
6. Expand Component Services, Computers and right-click My Computer, and then select Properties.<br />
<br />
7. Click the MSDTC tab, and then click Security Configuration.<br />
<br />
8. Select the Enable XA Transactions check box, and then click OK. This will cause a MS DTC service restart.<br />
<br />
9. Click OK again to close the Properties dialog box, and then close Component Services.<br />
<br />
10. Stop and then restart SQL Server to ensure that it syncs up with the MS DTC changes.<br />
<br />
<b>Configuring an XA Datasource</b><br />
This is a sample XA Datasource to connect to SQL Server 2005 and SQL Server 2000. This -ds.xml file must be place under the deploy folder of your server.<br />
<br />
serviceName-ds.xml<br />
<br />
<pre class="brush: xml"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE datasources
PUBLIC "-//JBoss//DTD JBOSS JCA Config 1.5//EN"
"http://www.jboss.org/j2ee/dtd/jboss-ds_1_5.dtd">
<datasources>
<xa-datasource>
<jndi-name>nameOfDataSource</jndi-name>
<track-connection-by-tx/>
<xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
<xa-datasource-property name="ServerName">server</xa-datasource-property>
<xa-datasource-property name="DatabaseName">database</xa-datasource-property>
<xa-datasource-property name="SelectMethod">cursor</xa-datasource-property>
<xa-datasource-property name="User">username</xa-datasource-property>
<xa-datasource-property name="Password">password</xa-datasource-property>
<xa-datasource-property name="URL">jdbc:sqlserver://server:1433;databasename=database</xa-datasource-property>
<isSameRM-override-value>false</isSameRM-override-value>
<!-- sql to call when connection is created -->
<new-connection-sql>select 1</new-connection-sql>
<!-- sql to call on an existing pooled connection when it is obtained from pool -->
<check-valid-connection-sql>select 1</check-valid-connection-sql>
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml -->
<metadata>
<!-- This type-mapping applies both to MS SQLSERVER 2000 and MS SQLSERVER 2005-->
<type-mapping>MS SQLSERVER2000</type-mapping>
</metadata>
</xa-datasource>
</datasources>
</pre><br />
<b>Configuring TIBCO EMS Provider</b><br />
This is a sample JMS Provider to connect to TIBCO EMS Server. Please note that the Connection Factory uses tx-connection-factory element which tells the Transaction Manager that this connection will take part in JTA transactions. This -ds.xml file must be place under the deploy folder of your server.<br />
<br />
ems-ds.xml<br />
<br />
<pre class="brush: xml"><?xml version="1.0" encoding="UTF-8"?>
<connection-factories>
<mbean code="org.jboss.jms.jndi.JMSProviderLoader" name="org.jboss.jms.jndi:service=JMSProviderLoader,name=EmsQueueProvider">
<attribute name="ProviderName">EmsQueueProvider</attribute>
<attribute name="ProviderAdapterClass">org.jboss.jms.jndi.JNDIProviderAdapter</attribute>
<attribute name="FactoryRef">XAQueueConnectionFactory</attribute>
<attribute name="QueueFactoryRef">XAQueueConnectionFactory</attribute>
<attribute name="TopicFactoryRef">XATopicConnectionFactory</attribute>
<attribute name="Properties">
java.naming.factory.initial=com.tibco.tibjms.naming.TibjmsInitialContextFactory
java.naming.provider.url=tcp://server:port
java.naming.security.principal=username
java.naming.security.credentials=password
</attribute>
</mbean>
<tx-connection-factory>
<jndi-name>EMSQueueFactory</jndi-name>
<rar-name>jms-ra.rar</rar-name>
<connection-definition>org.jboss.resource.adapter.jms.JmsConnectionFactory</connection-definition>
<config-property name="SessionDefaultType" type="java.lang.String">javax.jms.Queue</config-property>
<config-property name="JmsProviderAdapterJNDI" type="java.lang.String">java:/EmsQueueProvider</config-property>
<max-pool-size>20</max-pool-size>
<config-property name="UserName" type="java.lang.String">username</config-property>
<config-property name="Password" type="java.lang.String">password</config-property>
</tx-connection-factory>
</connection-factories>
</pre><br />
Also add the following factories to your EMS Server as follows:<br />
<br />
<pre class="brush: java">create factory XAQueueConnectionFactory xaqueue url=tcp://server:port
create factory XATopicConnectionFactory xatopic url=tcp://server:port
create factory XAConnectionFactory xageneric url=tcp://server:port
</pre><b>Sending messages to destinations</b><br />
The following code snippet creates an Connection, creates a transacted session and sends a message to a queue. The message will appear in the queue when the container commits the transaction.<br />
<br />
<pre class="brush: java">Context ctx = new InitialContext();
// get the connection factory fron jndi and create a connection
ConnectionFactory connectionFactory = (ConnectionFactory)ctx.lookup("java:/EMSQueueFactory");
Connection connection = connectionFactory.createConnection();
// create a session
QueueSession session = connection.createQueueSession(true,javax.jms.Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
QueueSender sender = session.createSender(queue);
// create an send a message
msg = session.createTextMessage();
msg.setText("Hello");
sender.send(queue, msg);
// close the connection
connection.close();
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-26110805743756041292011-04-03T20:39:00.003+01:002011-04-20T20:55:23.323+01:00JBoss 5 + Apache Camel + Spring + EJBThe following is a step-by-step guide to how to make Apache Camel 2.6.0 and Spring work with JBoss 5.<br />
<br />
<b>Step 1. Install JBoss</b><br />
Download <a href="http://sourceforge.net/projects/jboss/files/JBoss/JBoss-5.1.0.GA">JBoss Application Server 5.1.0.GA</a>. Extract the contents of the zip file to a directory of your choice (i.e. c:\jboss-5.1.0.GA). We are going to use the default server for this example. <br />
<br />
<b>Step 2. Install Snowdrop</b><br />
Download <a href="http://downloads.jboss.org/snowdrop/1.1.0.GA/jboss-spring-deployer-3.3.zip">JBoss Snowdrop version 1.1.0.GA</a>. Snowdrop is a utility package that contains JBoss-specific extensions to the Spring Framework. Extract the contents of the zip file (spring.deployer) to the deployers folder (C:\jboss-5.1.0.GA\server\default\deployers):<br />
<br />
<b>Step 3. Download camel-jboss package scan loader</b><br />
Download camel-jboss from <a href="http://code.google.com/a/apache-extras.org/p/camel-extra/">camel-extra</a>. The lirary contains JBoss specific package scan classloader to be used when Camel is running inside JBoss Application Server. JBoss uses LPGL license which means that camel-jboss cannot be hosted at Apache. Alternatively you can get a copy of the library from <a href="http://code.google.com/p/camelinaction/source/detail">here</a>. <br />
<br />
<b>Step 4. Install camel-jboss in Maven repository</b><br />
Install the camel-jboss library in your Maven repository as follows:<br />
<br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">mvn install:install-file -DgroupId=org.apache.camel -DartifactId=camel-jboss -Dversion=2.3.0 -Dpackaging=jar -Dfile=/path/to/camel-jboss-2.3.0.jar</span><br />
<br />
<b>Step 5. Include Maven dependencies</b><br />
Add the following dependencies to your ejb's pom:<br />
<pre class="brush: xml"><dependency>
<groupid>org.jboss.ejb3</groupid>
<artifactid>jboss-ejb3-ext-api</artifactid>
<version>1.0.0</version>
<exclusions>
<exclusion>
<groupid>org.jboss.javaee</groupid>
<artifactid>jboss-ejb-api</artifactid>
</exclusion>
<exclusion>
<groupid>org.jboss.metadata</groupid>
<artifactid>jboss-metadata</artifactid>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>javax.ejb</groupid>
<artifactid>ejb-api</artifactid>
<version>3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-beans</artifactid>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-core</artifactid>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupid>org.jboss.snowdrop</groupid>
<artifactid>snowdrop-deployers</artifactid>
<version>1.1.0.GA</version>
</dependency>
<dependency>
<groupid>org.apache.camel</groupid>
<artifactid>camel-core</artifactid>
<version>2.6.0</version>
</dependency>
<dependency>
<groupid>org.apache.camel</groupid>
<artifactid>camel-spring</artifactid>
<version>2.6.0</version>
</dependency>
<dependency>
<groupid>org.apache.xbean</groupid>
<artifactid>xbean-spring</artifactid>
<version>3.4</version>
<exclusions>
<exclusion>
<groupid>org.springframework</groupid>
<artifactid>spring</artifactid>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>org.apache.camel</groupid>
<artifactid>camel-jboss</artifactid>
<version>2.3.0</version>
</dependency>
</pre><br />
<b>Step 6. Add JBoss class resolver</b><br />
You will have to set the class resolver on the CamelContext which can be done using Java DSL as follows:<br />
<br />
<pre class="brush: java">PackageScanClassResolver jbossResolver = new JBossPackageScanClassResolver();
CamelContext context = new DefaultCamelContext();
context.setPackageScanClassResolver(jbossResolver);
</pre><br />
or adding the following bean definition in the jboss-spring.xml file using Spring XML:<br />
<br />
<pre class="brush: xml"><bean class="org.apache.camel.jboss.JBossPackageScanClassResolver" id="jbossResolver"></bean>
</pre><br />
<b>Step 7. Create your RouteBuilder and add it to jboss-spring.xml</b><br />
By doing so you let JBoss Application Server container manage Camel’s lifecycle. First you define the route:<br />
<pre class="brush: java">package org.example.camel;
import org.apache.camel.builder.RouteBuilder;
/**
* @author <a href="mailto:esanchezros@yahoo.es">Eduardo Sanchez-Ros</a>
*/
public class ExampleRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("file:C:\\temp\\source")
.convertBodyTo(String.class)
.process(new ExampleRouteProcessor())
.to("file:C:\\temp\\destination");
}
}
</pre><br />
and then you add it to the jboss-spring.xml file:<br />
<br />
<pre class="brush: xml"><bean class="org.example.camel.ExampleRouteBuilder" id="exampleRouteBuilder"></bean>
<camelcontext xmlns="http://camel.apache.org/schema/spring">
<routebuilder ref="exampleRouteBuilder">
</routebuilder></camelcontext>
</pre><br />
<b>Step 8. Create your enterprise application</b><br />
To demonstrate the previous I have created an example project that will create a route from file://C:\temp\source folder to file://C:\temp\destination and display the content of the file by calling a Stateless session bean. <br />
<br />
<b>Step 9. Build and deploy your ear</b><br />
Copy your enterprise archive into the deploy folder.<br />
<br />
You can <a href="https://sites.google.com/site/eduardosanchezros/jbosscamelspringejb/example.zip">download the source code from here</a>.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-81705568021288007452011-03-27T19:38:00.002+01:002011-04-03T21:11:01.185+01:00Serializing Generics - SerializableSortedDictionary<T>The SerializableSortedDictionary<T> class extends <a href="http://msdn.microsoft.com/en-US/library/f7fta44c(v=VS.80).aspx">SortedDictionary<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic stack into XML:<br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a serializable collection of key/value pairs that are sorted on the key.
/// </summary>
/// <typeparam name="TKey">The type of the keys on the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values on the dictionary.</typeparam>
public class SerializableSortedDictionary<TKey, TValue> : SortedDictionary<TKey, TValue>, IXmlSerializable
{
// store key and value types
private readonly Type m_tKey = typeof(TKey);
private readonly Type m_tValue = typeof(TValue);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGenerics.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGenerics.GetKeyValuePairName(m_tKey, m_tValue);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Is keyValuePairName the start element
if (!reader.IsStartElement(keyValuePairName))
{
// Throw an exception
throw new XmlException("Starting element " + keyValuePairName + " not found.");
}
// Loop through key-value pairs
while (reader.IsStartElement(keyValuePairName))
{
// Read key-value pair and move to content
reader.ReadStartElement(keyValuePairName);
reader.MoveToContent();
// Deserialize key and value
TKey key = (TKey)keySerializer.Deserialize(reader);
TValue value = (TValue)valueSerializer.Deserialize(reader);
// Read end element and add key-value pair to dictionary
reader.ReadEndElement();
Add(key, value);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGenerics.GetKeyValuePairName(m_tKey, m_tValue);
Enumerator enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Get current key value pair
KeyValuePair<TKey, TValue> keyValuePair = enumerator.Current;
// Write start element with key-value pair name
writer.WriteStartElement(keyValuePairName);
// Serialize key and value
keySerializer.Serialize(writer, keyValuePair.Key);
valueSerializer.Serialize(writer, keyValuePair.Value);
// Write end element with key-value pair name
writer.WriteEndElement();
}
}
#endregion
}
}
</pre>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1785301246937672105.post-10208209886930607492011-03-27T19:36:00.002+01:002011-04-03T21:11:11.241+01:00Serializing Generics - SerializableSortedList<T>The SerializableSortedList<T> class extends <a href="http://msdn.microsoft.com/en-US/library/ms132319(v=VS.80).aspx">SortedList<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic sorted list into XML:<br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a serializable collection of key/value pairs that are sorted by key based on
/// the associated System.Collections.Generic.IComparer<T> implementation.
/// </summary>
/// <typeparam name="TKey">The type of the keys on the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values on the dictionary.</typeparam>
public class SerializableSortedList<TKey, TValue> : SortedList<TKey, TValue>, IXmlSerializable
{
// store key and value types
private readonly Type m_tKey = typeof(TKey);
private readonly Type m_tValue = typeof(TValue);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGenerics.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGenerics.GetKeyValuePairName(m_tKey, m_tValue);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Is keyValuePairName the start element
if (!reader.IsStartElement(keyValuePairName))
{
// Throw an exception
throw new XmlException("Starting element " + keyValuePairName + " not found.");
}
// Loop through key-value pairs
while (reader.IsStartElement(keyValuePairName))
{
// Read key-value pair and move to content
reader.ReadStartElement(keyValuePairName);
reader.MoveToContent();
// Deserialize key and value
TKey key = (TKey)keySerializer.Deserialize(reader);
TValue value = (TValue)valueSerializer.Deserialize(reader);
// Read end element and add key-value pair to dictionary
reader.ReadEndElement();
Add(key, value);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGenerics.GetKeyValuePairName(m_tKey, m_tValue);
IEnumerator<KeyValuePair<TKey, TValue>> enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Get current key value pair
KeyValuePair<TKey, TValue> keyValuePair = enumerator.Current;
// Write start element with key-value pair name
writer.WriteStartElement(keyValuePairName);
// Serialize key and value
keySerializer.Serialize(writer, keyValuePair.Key);
valueSerializer.Serialize(writer, keyValuePair.Value);
// Write end element with key-value pair name
writer.WriteEndElement();
}
}
#endregion
}
}
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-67657953349285190362011-03-27T19:34:00.002+01:002011-04-03T21:11:19.903+01:00Serializing Generics - SerializableStack<T>The SerializableStack<T> class extends <a href="http://msdn.microsoft.com/en-US/library/3278tedw(v=VS.80).aspx">Stack<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic stack into XML:<br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a variable size last-in-first-out (LIFO) serializable collection of instances
/// of the same arbitrary type.
/// </summary>
/// <typeparam name="T">The type of the items on the linked list.</typeparam>
public class SerializableStack<T> : Stack<T>, IXmlSerializable
{
// store list type
private readonly Type m_type = typeof(T);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGenerics.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Loop through elements
while (reader.NodeType != XmlNodeType.EndElement)
{
// Deserialize type
T item = (T)typeSerializer.Deserialize(reader);
// Add node to stack
Push(item);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
IEnumerator<T> enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Serialize type
typeSerializer.Serialize(writer, enumerator.Current);
}
}
#endregion
}
}
</pre><br />
The previous class uses the SerializableGenerics helper class which constructs the element name based on the key-value pair node.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-61899687911537424742011-03-27T19:26:00.003+01:002011-04-03T21:11:28.311+01:00Serializing GenericsThe following exceptions are thrown when you try to serialize a any of the types (except for List) in the System.Collections.Generic namespace:<br />
<br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">A first chance exception of type 'System.NotSupportedException' occurred in System.Xml.dll</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.</span><br />
<br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">System.InvalidOperationException: You must implement a default accessor on System.Collections.Generic.Queue`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] because it inherits from ICollection.</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)</span><br />
<span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;">at System.Xml.Serialization.XmlSerializer..ctor(Type type)</span><br />
<br />
A way around this problem is to implement the IXmlSerializable interface.<br />
<br />
The following classes will allow you serialize generic types to XML in .NET 2.0:<br />
<br />
<ul><li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics.html">SerializableDictionary<T></a></li>
<li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics_27.html">SerializableLinkedList<T></a></li>
<li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics-serializablequeue.html">SerializableQueue<T></a></li>
<li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics_606.html">SerializableSortedDictionary<T></a></li>
<li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics_1853.html">SerializableSortedList<T></a></li>
<li><a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics-serializablestack.html">SerializableStack<T></a></li>
</ul><br />
You can download the library's source code <a href="https://sites.google.com/site/eduardosanchezros/serializinggenerics/SerializableGenerics.zip?attredirects=0&d=1">here</a>.<br />
<br />
The previous classes use the SerializableGenerics helper class which constructs the element name based on the key-value pair node:<br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace SerializableGenerics
{
public static class SerializableGenerics
{
private const string OF = "Of";
/// <summary>
/// Gets the key-value pair name
/// </summary>
/// <param name="tKey"></param>
/// <param name="tValue"></param>
/// <returns></returns>
public static string GetKeyValuePairName(Type tKey, Type tValue)
{
// return key-value pair name
return GetTypeName(tKey) + GetTypeName(tValue);
}
/// <summary>
/// Returns the name of the type
/// </summary>
/// <param name="type">Type to generate the name from</param>
/// <returns>The name of the type</returns>
public static String GetTypeName(Type type)
{
String typeName;
// Is type generic
if (type.IsGenericType)
{
// Get type name - Generics
typeName = type.Name.Substring(0, type.Name.Length - 2);
typeName += OF;
// Get type's arguments
Type[] types = type.GetGenericArguments();
foreach (Type t in types)
{
// Append type's name
typeName += GetTypeName(t);
}
}
else if (type.IsArray)
{
// Compose array name as "ArrayOf" and get array element's type name
typeName = type.BaseType.Name;
typeName += OF;
typeName += GetTypeName(type.GetElementType());
}
else
{
// Append type's name
typeName = type.Name;
}
// return type's name
return typeName;
}
}
}
</pre>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1785301246937672105.post-75791403936792753752011-03-27T19:11:00.004+01:002011-03-27T19:29:55.174+01:00Serializing Generics - SerializableQueue<T>The SerializableQueue<t> class extends <a href="http://msdn.microsoft.com/en-us/library/7977ey2c(v=VS.80).aspx">Queue<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic queue into XML: <br />
<br />
</t><br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a first-in, first-out serializable collection of objects.
/// </summary>
/// <typeparam name="T">The type of the items on the queue.</typeparam>
public class SerializableQueue<T> : Queue<T>, IXmlSerializable
{
// store list type
private readonly Type m_type = typeof(T);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGenerics.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Loop through elements
while (reader.NodeType != XmlNodeType.EndElement)
{
// Deserialize type
T item = (T)typeSerializer.Deserialize(reader);
// Enqueue item on queue
Enqueue(item);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
IEnumerator<T> enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Serialize type
typeSerializer.Serialize(writer, enumerator.Current);
}
}
#endregion
}
}
</pre><br />
The previous class uses the <a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics_3120.html">SerializableGenerics</a> helper class which constructs the element name based on the key-value pair node.Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1785301246937672105.post-78722462306478895092011-03-27T19:03:00.004+01:002011-03-27T19:32:03.274+01:00Serializing Generics - SerializableLinkedList<T>The SerializableLinkedList<T> class extends <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7(v=VS.80).aspx">LinkedList<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic linked list into XML: <br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a strongly typed serializable list of objects that can be accessed by index.
/// </summary>
/// <typeparam name="T">The type of the items on the linked list.</typeparam>
public class SerializableLinkedList<T> : LinkedList<T>, IXmlSerializable
{
// store list type
private readonly Type m_type = typeof(T);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGenerics.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Loop through elements
while (reader.NodeType != XmlNodeType.EndElement)
{
// Deserialize type
T value = (T)typeSerializer.Deserialize(reader);
// Create a liked list node of T
LinkedListNode<T> node = new LinkedListNode<T>(value);
// Add node to linked list
AddLast(node);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializer for type
XmlSerializer typeSerializer = new XmlSerializer(m_type);
IEnumerator<T> enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Serialize type
typeSerializer.Serialize(writer, enumerator.Current);
}
}
#endregion
}
}
</pre><br />
The previous class uses the <a href="http://eduardosanchezros.blogspot.com/2011/03/serializing-generics_3120.html">SerializableGenerics</a> helper class which constructs the element name based on the key-value pair node.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1785301246937672105.post-5277422029627061952011-03-24T13:13:00.067+00:002011-03-27T19:32:51.293+01:00Serializing Generics - SerializableDictionary<T>The SerializableDictionary<T> class extends <a href="http://msdn.microsoft.com/en-us/library/xfhwa508(v=VS.80).aspx">Dictionary<T></a> and implements <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=VS.80).aspx">IXmlSerializable</a>, allowing you to serialize a generic dictionary into XML. The code was first inspired on Paul Welter's article <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx">XML Serializable Generic Dictionary</a>: <br />
<br />
<pre class="brush: csharp">/*
* SerializableGenerics
* Copyright (c) 2009, Eduardo Sanchez-Ros
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
namespace SerializableGenerics
{
/// <summary>
/// Represents a serializable collection of keys and values.
/// </summary>
/// <typeparam name="TKey">The type of the keys on the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values on the dictionary.</typeparam>
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
// store key and value types
private readonly Type m_tKey = typeof(TKey);
private readonly Type m_tValue = typeof(TValue);
/// <summary>
/// Returns a string that represents the current SerializableDictionary.
/// </summary>
/// <returns>
/// A string that represents the current SerializableDictionary.
/// </returns>
public override string ToString()
{
return SerializableGeneric.GetTypeName(GetType());
}
#region IXmlSerializable Members
/// <summary>
/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute
/// to the class instead.
/// </summary>
/// <returns>
/// An System.Xml.Schema.XmlSchema that describes the XML representation of the
/// object that is produced by the System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)
/// method and consumed by the System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)
/// method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The System.Xml.XmlReader stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGeneric.GetKeyValuePairName(m_tKey, m_tValue);
// Read start element and move to content
reader.ReadStartElement();
reader.MoveToContent();
// Is keyValuePairName the start element
if (!reader.IsStartElement(keyValuePairName))
{
// Throw an exception
throw new XmlException("Starting element " + keyValuePairName + " not found.");
}
// Loop through key-value pairs
while (reader.IsStartElement(keyValuePairName))
{
// Read key-value pair and move to content
reader.ReadStartElement(keyValuePairName);
reader.MoveToContent();
// Deserialize key and value
TKey key = (TKey)keySerializer.Deserialize(reader);
TValue value = (TValue)valueSerializer.Deserialize(reader);
// Read end element and add key-value pair to dictionary
reader.ReadEndElement();
Add(key, value);
}
// Read end element and move to content
reader.ReadEndElement();
reader.MoveToContent();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The System.Xml.XmlWriter stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Create xml serializers for key and value
XmlSerializer keySerializer = new XmlSerializer(m_tKey);
XmlSerializer valueSerializer = new XmlSerializer(m_tValue);
// Get key-value pair name
string keyValuePairName = SerializableGeneric.GetKeyValuePairName(m_tKey, m_tValue);
Enumerator enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
// Get current key value pair
KeyValuePair<TKey, TValue> keyValuePair = enumerator.Current;
// Write start element with key-value pair name
writer.WriteStartElement(keyValuePairName);
// Serialize key and value
keySerializer.Serialize(writer, keyValuePair.Key);
valueSerializer.Serialize(writer, keyValuePair.Value);
// Write end element with key-value pair name
writer.WriteEndElement();
}
}
#endregion
}
}
</pre><br />
As an example, let's say we have a Serializable Dictionary of Strings and String Arrays. The type will be declared as follows:<br />
<br />
<pre class="brush: csharp">SerializableDictionary<String, String[]>
</pre><br />
And the resulting serialized XML:<br />
<br />
<pre class="brush: xml"><serializabledictionaryofstringarrayofstring>
<stringarrayofstring>
<string>Key #0</string>
<arrayofstring xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string>Value 1 of 0</string>
<string>Value 2 of 0</string>
<string>Value 3 of 0</string>
</arrayofstring>
</stringarrayofstring>
<stringarrayofstring>
<string>Key #1</string>
<arrayofstring xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string>Value 1 of 1</string>
<string>Value 2 of 1</string>
<string>Value 3 of 1</string>
</arrayofstring>
</stringarrayofstring>
</serializabledictionaryofstringarrayofstring>
</pre>Unknownnoreply@blogger.com0