top-image

OLDER ARTICLES

Hi,

Juste a mini-post concerning the configuation of DATASOURCE on Documentum server.
The DATASOURCE (DS) are configurable:

 
Here, the example for the DS “java:/MY_ARCHIVE_DS” :

<?xml version='1.0' encoding='UTF-8'?>
<server xmlns="urn:jboss:domain:1.2">
    <profile>
       <subsystem xmlns="urn:jboss:domain:datasources:1.0">

            <datasources>

                <datasource jndi-name="java:/MY_ARCHIVE_DS" pool-name="MY_ARCHIVE_DS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MYDBSERVER123)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=MYARCHIVE)))</connection-url>
                    <driver>oracle.jdbc</driver>
                    <pool>
                        <min-pool-size>5</min-pool-size>
                        <max-pool-size>100</max-pool-size>
                    </pool>
                    <security>
                        <user-name>MY_APP_USER</user-name>
                        <password>WD{HUO/dfdfdsfdsfh]-DUHi</password>
                    </security>
                    <validation>
                        <exception-sorter class-name="org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter"/>
                    </validation>
                </datasource>
	        <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                    <driver name="oracle.jdbc" module="oracle.jdbc">
                        <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
                    </driver>
                    <driver name="sqljdbc" module="com.microsoft.sqlserver">
                        <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>
    </profile>

    <interfaces>

    </interfaces>

    <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">

    </socket-binding-group>
</server>

 
 
The use of this DS in the JOB/JAVA code could be:

	private static final String DS = "MY_ARCHIVE_DS";
	private static final String JNDI_PREFIX[] = { "java:/", "java:", "jdbc/" };

	//...
		InitialContext ic = new InitialContext();
		for (int i = 0; i < JNDI_PREFIX.length && dataSource == null; i++) {
			try {
				dataSource = (DataSource) ic.lookup(JNDI_PREFIX[i] + DS);
			} catch (NamingException e) {
			}
		}
		if (dataSource == null) {
			throw new Exception("Unable to find datasource " + DS);
		}
	//...

	Connection connection = dataSource.getConnection();
	try {
		connection.setAutoCommit(false);

		PreparedStatement statement = connection.prepareStatement(MessageFormat.format(sql.toString(), StringUtils.upperCase(StringUtils.trimToEmpty(table)), year.format(coll.getTime("time_stamp").getDate())));

		//... Save the original data in a BLOB field in ARCHIVE database
		Blob blob = connection.createBlob();

		//...
		statement.executeUpdate();

		//...
		blob.free();

		//...
		statement.close();

		//...

	} finally {

		if(connection!=null){
	
			if (commit) {
				connection.commit();
				println("SqlConnection transaction commited !");
			} else {
				connection.rollback();
				println("SqlConnection transaction rollbacked !");
			}
			connection.close();
		}
	}

That’s all!!!

Huseyin OZVEREN

Hi,

Here, an simple example of use of logging platform NLog in C# projects. Or course, you need add reference to Nlog package in your project via NuGet Package Manager.

NLog is a free logging platform for .NET, NETSTANDARD, Xamarin, Silverlight and Windows Phone with rich log routing and management capabilities. NLog makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.

using System;
using NLog;
using NLog.Config;
using NLog.Targets;
using System.IO;
using System.Collections.ObjectModel;
using NLog.Layouts;

namespace HuoBlog.Logging
{

    public static class LoggerService
    {
        private static Logger logger;
        private static readonly string LOGGER_TARGET_FILE_NAME = "file";

        public static string ForceNewLoggerFile(string logFilePath = null)
        {
            logger = null;
            GetLogger(logFilePath);
            return GetLogFilePath();
        }

        public static string GetLogFilePath()
        {
            string logFilePath = null;
            if(logger != null)
            {
                foreach (Target target in LogManager.Configuration.AllTargets)
                {
                    if (target.GetType() == typeof(FileTarget) 
                        && ((FileTarget)target).FileName.GetType() == typeof(SimpleLayout))
                    {
                        SimpleLayout layout = (SimpleLayout) ((FileTarget)target).FileName;
                        return layout.Text;
                    }
                }
            }

            return logFilePath;
        }

        private static Logger GetLogger(string logFilePath = null)
        {
            if (logger == null)
            {
                // Log file
                {
                    if(logFilePath == null) // Generate a logfile
                    {
                        // OLD : 
                        //string outputPath = Path.Combine(Environment.CurrentDirectory, "output");
                        //if (!Directory.Exists(outputPath))
                        //    Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "output"));
                        // NEW: 
                        string outputPath = Environment.CurrentDirectory;
                        logFilePath = Path.Combine(outputPath, "HuoBlog_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log");
                    }
                }

                // Config logger
                {
                    var config = new LoggingConfiguration();
                    var fileTarget = new FileTarget();
                    fileTarget.FileName = logFilePath;
                    fileTarget.Layout = "${message}";
                    config.AddTarget(LOGGER_TARGET_FILE_NAME, fileTarget);
                    config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
                    LogManager.Configuration = config;
                }

                logger = LogManager.GetLogger("Extract");
            }

            return logger;
        }

        public static void Info(string message)
        {
            GetLogger().Info("INFO: " + message);
        }

        public static void Warn(string message)
        {
            GetLogger().Warn("WARNING: " + message);
        }

        public static void Error(string message)
        {
            GetLogger().Error("ERROR: " + message);
        }

        public static void Print(string message)
        {
            GetLogger().Info(message);
        }
        
    }
}

….

try{
	string logFilePath = LoggerService.ForceNewLoggerFile();
	// ...	

	LoggerService.Info("############ HuoBlog - Started at " + DateTime.Now);
	LoggerService.Print("\n\n");
	// ...	
}
catch (Exception ex)
{
	LoggerService.Error(ex.ToString());
}
finally
{
	LoggerService.Info("############ HuoBlog - ended at " + DateTime.Now);
	// ...	
	string logFileContent = File.ReadAllText(LoggerService.GetLogFilePath());
	// ...	
}

C:\Workspaces\MS_Visual_Studio_Projects\…\bin\Debug\output\HuoBlog_20171120165730.log.

That’s all!!

Huseyin

Hi,

Here, an example to get the source folder path of CSharp class via a static method and the package System.Runtime.CompilerServices. In fact, we solicit the compiler in order to get some informations about caller (caller line number, caller method, caller file path): https://msdn.microsoft.com/fr-fr/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx.

using System.IO;
using System.Runtime.CompilerServices;

namespace HuoBlog
{
    public class ModelUtility
    {
        public static string getProjectPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
            // new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
            string currentClassPath = getInternalPath();
            string currentProjectPath = Path.GetDirectoryName(currentClassPath);
            return currentProjectPath;
        }


        private static string getInternalPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
            return sourceFilePath;
        }
    }
}

 
…in the caller method, for example a simple Program.cs, some parameters Callerxxxx are set by compiler:

//...
string currentModelProjectPath = ModelUtility.getProjectPath();
//...
//...
// [CallerMemberName] string memberName = "Main"
// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\Program.cs"
// [CallerLineNumber] int sourceLineNumber = 38

        public static string getProjectPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
                //...
        }
//...
//...
// [CallerMemberName] string memberName = "getProjectPath"
// [CallerFilePath] string sourceFilePath = "C:\\Workspaces\\MS_Visual_Studio_Projects\\...\\ModelUtility.cs"
// [CallerLineNumber] int sourceLineNumber = 13

        private static string getInternalPath([CallerMemberName] string memberName = "",
                [CallerFilePath] string sourceFilePath = "",
                [CallerLineNumber] int sourceLineNumber = 0)
        {
                //...
        }
//...

That’s all!!!!

Huseyin OZVEREN

Hi,

A post with concrete examples concerning the generation of Types/POJO from a XSD file, the serialization of these objects/POJO to XML and finally the validation of XML with XSD.

Generate Custom Types from XSD file

  • XSD file myXsdFile.xsd:
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                targetNamespace="urn:books"
                xmlns:bks="urn:books">
    
      <xsd:element name="books" type="bks:BooksForm"/>
    
      <xsd:complexType name="BooksForm">
        <xsd:sequence>
          <xsd:element name="book"
                      type="bks:BookForm"
                      minOccurs="0"
                      maxOccurs="unbounded"/>
        </xsd:sequence>
      </xsd:complexType>
    
      <xsd:complexType name="BookForm">
        <xsd:sequence>
          <xsd:element name="author"   type="xsd:string"/>
          <xsd:element name="title"    type="xsd:string"/>
          <xsd:element name="genre"    type="xsd:string"/>
          <xsd:element name="price"    type="xsd:float" />
          <xsd:element name="pub_date" type="xsd:date" />
          <xsd:element name="review"   type="xsd:string"/>
        </xsd:sequence>
        <xsd:attribute name="id"   type="xsd:string"/>
      </xsd:complexType>
    </xsd:schema>
    

     

  • CSharp sources and types generator:
            /// <summary>
            /// Custom Types Generator from XSD file
            /// </summary>
            /// <param name="xsdFile"></param>
            /// <param name="outputFile"></param>
            private static bool generateCSharpFile(string xsdFile, string outputFile)
            {
                bool result = true;
                try
                {
                    var stream = new MemoryStream(File.ReadAllBytes(xsdFile));
    
                    var schema = XmlSchema.Read(XmlReader.Create(stream), null);
                    var schemas = new XmlSchemas();
                    schemas.Add(schema);
    
                    var ns = new CodeNamespace { Name = "books" };
                    ns.Imports.Add(new CodeNamespaceImport("System"));
                    ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
    
                    var exporter = new XmlCodeExporter(ns);
                    var importer = new XmlSchemaImporter(schemas);
    
                    foreach (XmlSchemaElement element in schema.Elements.Values)
                    {
                        var mapping = importer.ImportTypeMapping(element.QualifiedName);
                        exporter.ExportTypeMapping(mapping);
                    }
    
                    // Transform CodeDOM as required, adding new attributes, methods, modifying
                    // inheritance hierarchy, whatever.
                    var provider = new CSharpCodeProvider();
    
                    using (var writer = new StreamWriter(outputFile, false))
                    {
                        // Creates a new CodeGeneratorOptions.
                        CodeGeneratorOptions genOptions = new CodeGeneratorOptions();
    
                        // Sets a value indicating that the code generator should insert blank lines between type members.
                        genOptions.BlankLinesBetweenMembers = true;
    
                        // Sets the style of bracing format to use: either "Block" to start a
                        // bracing block on the same line as the declaration of its container, or 
                        // "C" to start the bracing for the block on the following line.
                        genOptions.BracingStyle = "C";
    
                        // Sets a value indicating that the code generator should not append an else, 
                        // catch or finally block, including brackets, at the closing line of a preceeding if or try block.
                        genOptions.ElseOnClosing = false;
    
                        // Sets the string to indent each line with.
                        genOptions.IndentString = "    ";
    
                        // Uses the CodeGeneratorOptions indexer property to set an
                        // example object to the type's string-keyed ListDictionary.
                        // Custom ICodeGenerator implementations can use objects 
                        // in this dictionary to customize process behavior.
                        genOptions["CustomGeneratorOptionStringExampleID"] = "BuildFlags: /A /B /C /D /E";
    
                        provider.GenerateCodeFromNamespace(ns, writer, genOptions);
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                    result = false;
                }
    
                return result;
            }
    
    

    //….

                string xsdFile = "C:\\Workspaces\\MS_Visual_Studio_Projects\\TestApps\\TestXmlXsd1\\myXsdFile.xsd";
                string outputFile = "C:\\Workspaces\\MS_Visual_Studio_Projects\\TestApps\\TestXmlXsd1\\generated\\MyCustomTypes.cs";
    
                generateCSharpFile(xsdFile, outputFile);
    

     
     

  • After execution, a CSharp file MyCustomTypes.cs containing all types of XSD file is generated:
    namespace books
    {
        using System;
        using System.Collections.Generic;
        
        
        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("TestXmlXsd1", "1.0.0.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:books")]
        [System.Xml.Serialization.XmlRootAttribute("books", Namespace="urn:books", IsNullable=false)]
        public partial class BooksForm
        {
            
            private BookForm[] bookField;
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute("book", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public BookForm[] book
            {
                get
                {
                    return this.bookField;
                }
                set
                {
                    this.bookField = value;
                }
            }
        }
        
        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("TestXmlXsd1", "1.0.0.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:books")]
        public partial class BookForm
        {
            
            private string authorField;
            
            private string titleField;
            
            private string genreField;
            
            private float priceField;
            
            private System.DateTime pub_dateField;
            
            private string reviewField;
            
            private string idField;
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string author
            {
                get
                {
                    return this.authorField;
                }
                set
                {
                    this.authorField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string title
            {
                get
                {
                    return this.titleField;
                }
                set
                {
                    this.titleField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string genre
            {
                get
                {
                    return this.genreField;
                }
                set
                {
                    this.genreField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public float price
            {
                get
                {
                    return this.priceField;
                }
                set
                {
                    this.priceField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date")]
            public System.DateTime pub_date
            {
                get
                {
                    return this.pub_dateField;
                }
                set
                {
                    this.pub_dateField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string review
            {
                get
                {
                    return this.reviewField;
                }
                set
                {
                    this.reviewField = value;
                }
            }
            
            /// <remarks/>
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string id
            {
                get
                {
                    return this.idField;
                }
                set
                {
                    this.idField = value;
                }
            }
        }
    }
    
    

 
 
 

Serialization of objects to XML

  • Instantiation of POJO objects and use of them in order to generate XML file myXmlFile.xml:
            /// <summary>
            /// Generate XML file for POJO annotated (System.Xml)
            /// </summary>
            /// <param name="model"></param>
            /// <param name="xmlFile"></param>
            private static bool generateXML(object model, string xmlFile)
            {
                bool result = true;
                try
                {
                    // Build POJO
                    var serializer = new XmlSerializer(model.GetType());
    
                    using (StreamWriter writer = new StreamWriter(xmlFile, true, new UTF8Encoding(false)))
                    {
                        serializer.Serialize(writer, model);
                    }
                }
                catch (XmlSchemaValidationException ex)
                {
                    Console.Write(ex.ToString());
                    result = false;
                }
    
                return result;
            }
    

    //….

                string xmlGeneratedFile = "C:\\Workspaces\\MS_Visual_Studio_Projects\\TestApps\\TestXmlXsd1\\myXmlFile.xml";
                BooksForm booksForm = new BooksForm();
                {
                    List<BookForm> booksList = new List<BookForm>();
                    {
                        BookForm book = new BookForm();
                        book.id = "bk001";
                        book.author = "Writer";
                        book.title = "The First Book";
                        book.genre = "Fiction";
                        book.price = 44.95F;
                        book.pub_date = DateTime.ParseExact("2000-10-01", "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        book.review = "An amazing story of nothing.";
                        booksList.Add(book);
                    }
                    {
                        BookForm book = new BookForm();
                        book.id = "bk002";
                        book.author = "Poet";
                        book.title = "The Poet's First Poem";
                        book.genre = "Poem";
                        book.price = 24.95F;
                        book.review = "Least poetic poems.";
                        booksList.Add(book);
                    }
                    booksForm.book = booksList.ToArray();
                }
    
    
                generateXML(booksForm, xmlGeneratedFile);
    

     
     

  • The generated XML file myXmlFile.xml would be:
    <?xml version="1.0" encoding="utf-8"?>
    <books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:books">
      <book id="bk001" xmlns="">
        <author>Writer</author>
        <title>The First Book</title>
        <genre>Fiction</genre>
        <price>44.95</price>
        <pub_date>2000-10-01</pub_date>
        <review>An amazing story of nothing.</review>
      </book>
      <book id="bk002" xmlns="">
        <author>Poet</author>
        <title>The Poet's First Poem</title>
        <genre>Poem</genre>
        <price>24.95</price>
        <pub_date>0001-01-01</pub_date>
        <review>Least poetic poems.</review>
      </book>
    </books>
    

 
 
 

Validation of XML with XSD file

  • Validation of generated XML myXmlFile.xml with original XSD file myXsdFile.xml:
            /// <summary>
            /// Validate XML file with XSD file
            /// </summary>
            /// <param name="xmlFilePath"></param>
            /// <param name="xsdFilePath"></param>
            /// <param name="namespaceName"></param>
            /// <returns></returns>
            private static bool IsValidXml(string xmlFilePath, string xsdFilePath, string namespaceName)
            {
                var xdoc = XDocument.Load(xmlFilePath);
                var schemas = new XmlSchemaSet();
                schemas.Add(namespaceName, xsdFilePath);
    
                bool result = true;
                try
                {
                    xdoc.Validate(schemas, (sender, e) =>
                    {
                        Console.Write("Error:" + e.Message);
                        result = false;
                    });
                }
                catch (XmlSchemaValidationException ex)
                {
                    Console.Write(ex.ToString());
                    result = false;
                }
                return result;
            }
    

    //….

                string xsdFile = "C:\\Workspaces\\MS_Visual_Studio_Projects\\TestApps\\TestXmlXsd1\\myXsdFile.xsd";
                string xmlGeneratedFile = "C:\\Workspaces\\MS_Visual_Studio_Projects\\TestApps\\TestXmlXsd1\\myXmlFile.xml";
    
                IsValidXml(xmlGeneratedFile, xsdFile, "urn:books");
    

 

Note: Below the import / using needed to these methods:

using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Text;
using books;
using System.Collections.Generic;
using System.Globalization;

 

Best regards,

Huseyin OZVEREN

Page 2 of 52:« 1 2 3 4 5 »Last »
bottom-img
Copyright ® 2012 Huseyin Ozveren. No reproduction, even partial, can be used from this site and all its contents including text, documents, images, etc.. without the express permission of the author.