Sie sind auf Seite 1von 59

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
//using InterCOM.EDIProducts.Core;
using InterCOM.EDIProducts.Report;
using InterCOM.EDIProducts.Common;
using InterCOM.EDIProducts.Mapping;
using InterCOM.EDIProducts.CodeConvertLibrary;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Collections;
using System.Data;
namespace InterCOM.EDIProducts.Data.Builder
{
public class FixedBuilder : IObjectBuilder
{
private const string AssemblyVersion = "0.1";
private Writer _report = null;
private MappingDataBaton _baton = null;
ct
private XElement _tree = null;
private List<string>[] buffers = null;

// Module version
// Report object
// Application data obje
// Phase 2 XML tree
// Output Fixed buffer

private FileStream fsFixed;


private BinaryWriter bwFixed;
/// <summary>
/// Constructor
/// </summary>
/// <param name="baton">Application data object</param>
public FixedBuilder(MappingDataBaton baton)
{
_baton = baton;
_report = baton.Report;
_tree = baton.OutputData;
}
/// <summary>
/// Module version
/// </summary>
public void Version() {
_report.Add(string.Format("FIXEDBuilder. Version {0}", AssemblyVersi
on));
}
///
///
///
///

<summary>
Builder's main method to convert immediate tree to final data
</summary>
<returns>Method result</returns>

public long Convert()


{
MappingErrorCode bSuccess = MappingErrorCode.Success;

// Diagnostic
Watcher watcher = Watcher.Instance();
watcher.Start();
_report.Add(string.Format("[{0}] Converter is starting...", _baton.P
arameters.BuilderType.ToUpper()));
// Prepare output writer
#region Output File Open
try
{
// Create output file
fsFixed = new FileStream(_baton.Parameters.OutputDataFile, FileM
ode.Create, FileAccess.Write, FileShare.None);

// Get file encoding


Encoding enc = Encoding.GetEncoding("Shift_JIS");
DataStoreItem ds = _baton.OutputDataStore.GetItemByType(MappingL
ayoutType.DataStore, 0);
DataEncoding de = DataEncoding.Shift_JIS;
if (Util.HasKey(ds.Properties.Fixed, ""))
{
// Get file encoding through property
de = (DataEncoding)Util.ToInt(ds.Properties.Fixed.)
}
switch (de)
{
case DataEncoding.UTF_8: enc = Encoding.UTF8; break;
case DataEncoding.UTF_16LE: enc = Encoding.Unicode; break;
case DataEncoding.UTF_16BE: enc = Encoding.BigEndianUnicode;
break;
}
// Init stream writer with created file & given encoding
bwFixed = new BinaryWriter(fsFixed, enc);
}
catch (IOException)
{
_report.Add(string.Format("Could not create output file [{0}]",
_baton.Parameters.OutputDataFile));
bSuccess = MappingErrorCode.Failed;
}
catch (Exception ex)
{
// File open error.
bSuccess = MappingErrorCode.Failed;
_report.Add(string.Format("Exception.Message{0}", ex.Message));
_report.Add(string.Format("Exception.Source{0}", ex.Source));
_report.Add(string.Format("Exception.StackTrace{0}", ex.StackTrac
e));
}
#endregion
#region Converter
if (bSuccess == MappingErrorCode.Success)
{
// Number of threads to be spawned

int threadNum = AppSettings.ThreadCount;


threadNum = 1;
// Immediate data tree
List<XElement> elems = _baton.OutputData.Elements().ToList();
int elemCount = elems.Count();
int size = elemCount / threadNum;
// redundant items after devide into block.
// Eg: 13 Items / 4 CPU = 3 items per CPU & remain 1 will be red
undant.
int tail = elemCount % threadNum;
// Calculate block size
int[] sizes = new int[threadNum];
int[] tails = new int[1];
for (int i = 0; i < sizes.Length; i++)
{
// Calculate data size per thread
sizes[i] = (i * size);
//tails[i] = 0;
if (i == sizes.Length - 1) tails[0] = tail;
}
// Devide data into chunks. Number of chunks are given by total
thread numbers [AppSettings.ThreadCount]
List<XElement>[] chunks;
int numberChunks =threadNum;
if (tail > 0)
{
numberChunks =threadNum + 1;
chunks = new List<XElement>[threadNum + 1];
}
else
chunks = new List<XElement>[threadNum];
for (int i = 0; i < numberChunks; i++)
{
if (i <= numberChunks - 2 || (i == numberChunks - 1 && tail
== 0))
chunks[i] = elems.GetRange(sizes[i], size);
else if(tail!=0)
chunks[i] = elems.GetRange(sizes[i - 1] + size, tail);
}
// Prepare buffers
buffers = new List<string>[numberChunks];
// Creating thread's options
var converters = (from n in Enumerable.Range(0, numberChunks)
select new FixedConverter(n, chunks[n], _baton
.InputDataStore,
_baton.OutputDataStore, _baton.MappingLogi
c, _baton.Parameters, _report))
.ToList();
// Create & spawn threads
foreach (FixedConverter converter in converters)
{
converter.Setup();

}
foreach (FixedConverter converter in converters)
converter.Teardown();
// Converting done. Now saving to file
commitBufferToOutputFile(bwFixed, converters);
// Cleanup
if (bwFixed != null) bwFixed.Dispose();
if (fsFixed != null) fsFixed.Dispose();
}
#endregion
return (long)bSuccess;
}
/// <summary>
/// Write Fixed buffer to file
/// </summary>
/// <param name="sw">BinaryWriter</param>
/// <param name="converters">List<FixedConverter></param>
/// <exception cref="IndexOutOfRangeException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="IOException"></exception>
private long commitBufferToOutputFile(BinaryWriter sw, List<FixedConvert
er> converters)
{
long result = 0;
try
{
for (int i = 0; i < converters.Count(); i++)
{
if (converters[i].Buffers != null && converters[i].Buffers.C
ount > 0)
{
foreach (List<byte[]> Records in converters[i].Buffers)
{
foreach (byte[] Items in Records)
{
bwFixed.Write(Items);
}
}
}
}
}
catch (IndexOutOfRangeException ex)
{
_report.Add("Failed to commit data buffer to output file.");
_report.Add(ex.StackTrace);
result = (long)CommonError.IndexOutOfBound;
}
catch (ObjectDisposedException)
{
_report.Add("Failed to commit data buffer to output file. Writer
is inaccessible.");
result = (long)CommonError.NullPointerException;
}
catch (IOException)

{
_report.Add("Could not commit data buffer to output file. Report
file is inaccessible.");
result = (long)CommonError.BadFilePointer;
}
return result;
}
}
/// <summary>
/// Converter's option class
/// </summary>
public class FixedConverter:MultiThreadConverter
{
#region Member variable
// private Thread _Thread;
ResultFixedConvert mResultFixedConvert; // stores the processing result
of the time fixed length conversion
Hashtable htSpace;
adding to each code system
Hashtable htSpaceMiltuByte;
Hashtable htZero;
g to each code system
Cnv EdiEncoding;

// store the code of the space p


// store the code of zero paddin
//Realities of code conversion c

lass
string strDefaultGaijiFolder;
character table is placed
string strUserGaijiFolder;
ternal character table has been placed

// Folder name default external


// Folder name where the user ex

int i = 0;
#endregion
#region Properties
public IDataStoreFactory SourceLayout { get; set; }
public IDataStoreFactory TargetLayout { get; set; }
public List<List<byte[]>> Buffers { get; set; }
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public FixedConverter(int id, List<XElement> data, IDataStoreFactory sou
rceLayout,
IDataStoreFactory targetLayout, IMappingLogic logics, AppParams parm
s, Writer report)
: base(id, data, sourceLayout, targetLayout, logics, parms, report)
{
htSpace = new Hashtable();
htSpaceMiltuByte = new Hashtable();

htZero = new Hashtable();


//// Generation of code conversion class
EdiEncoding = new Cnv();
strDefaultGaijiFolder = "";
strUserGaijiFolder = "";
EdiEncoding.GaijiType = GJ_TYPE.Auto;
#region By using the character code conversion
//By using the character code conversion, it should be created in ad
vance padding characters
htSpace.Add(DataEncoding.Shift_JIS, mf_ConvString2Byte(DataEncoding.
Shift_JIS, " "));
htSpace.Add(DataEncoding.JIS, mf_ConvString2Byte(DataEncoding.JIS, "
"));
htSpace.Add(DataEncoding.EBCDIC, mf_ConvString2Byte(DataEncoding.EBC
DIC, " "));
htSpace.Add(DataEncoding.IBM, mf_ConvString2Byte(DataEncoding.IBM, " "))
;
htSpace.Add(DataEncoding.JEF_78, mf_ConvString2Byte(DataEncoding.JEF
_78, " "));
htSpace.Add(DataEncoding.JEF_83, mf_ConvString2Byte(DataEncoding.JEF
_83, " "));
htSpace.Add(DataEncoding.KEIS_78, mf_ConvString2Byte(DataEncoding.KE
IS_78, " "));
htSpace.Add(DataEncoding.KEIS_83, mf_ConvString2Byte(DataEncoding.KE
IS_83, " "));
htSpace.Add(DataEncoding.UNISYS, mf_ConvString2Byte(DataEncoding.UNI
SYS, " "));
htSpace.Add(DataEncoding.EUC_JP, mf_ConvString2Byte(DataEncoding.EUC
_JP, " "));
htSpace.Add(DataEncoding.UTF_8, mf_ConvString2Byte(DataEncoding.UTF_
8, " "));
htSpace.Add(DataEncoding.UTF_16BE, mf_ConvString2Byte(DataEncoding.U
TF_16BE, " "));
htSpace.Add(DataEncoding.UTF_16LE, mf_ConvString2Byte(DataEncoding.U
TF_16LE, " "));
htSpace.Add(DataEncoding.UTF_32BE, mf_ConvString2Byte(DataEncoding.U
TF_32BE, " "));
htSpace.Add(DataEncoding.UTF_32LE, mf_ConvString2Byte(DataEncoding.U
TF_32LE, " "));
htSpace.Add(DataEncoding.JIPSJ, mf_ConvString2Byte(DataEncoding.JIPS
J, " "));
htSpace.Add(DataEncoding.JIPSE, mf_ConvString2Byte(DataEncoding.JIPS
E, " "));
htZero.Add(DataEncoding.Shift_JIS, mf_ConvString2Byte(DataEncoding.S
hift_JIS, "0"));
htZero.Add(DataEncoding.JIS, mf_ConvString2Byte(DataEncoding.JIS, "0
"));
htZero.Add(DataEncoding.EBCDIC, mf_ConvString2Byte(DataEncoding.EBCD
IC, "0"));
htZero.Add(DataEncoding.IBM, mf_ConvString2Byte(DataEncoding.IBM, "0"));
htZero.Add(DataEncoding.JEF_78, mf_ConvString2Byte(DataEncoding.JEF_
78, "0"));
htZero.Add(DataEncoding.JEF_83, mf_ConvString2Byte(DataEncoding.JEF_
83, "0"));
htZero.Add(DataEncoding.KEIS_78, mf_ConvString2Byte(DataEncoding.KEI
S_78, "0"));
htZero.Add(DataEncoding.KEIS_83, mf_ConvString2Byte(DataEncoding.KEI

S_83, "0"));
htZero.Add(DataEncoding.UNISYS, mf_ConvString2Byte(DataEncoding.UNIS
YS, "0"));
htZero.Add(DataEncoding.EUC_JP, mf_ConvString2Byte(DataEncoding.EUC_
JP, "0"));
htZero.Add(DataEncoding.UTF_8, mf_ConvString2Byte(DataEncoding.UTF_8
, "0"));
htZero.Add(DataEncoding.UTF_16BE, mf_ConvString2Byte(DataEncoding.UT
F_16BE, "0"));
htZero.Add(DataEncoding.UTF_16LE, mf_ConvString2Byte(DataEncoding.UT
F_16LE, "0"));
htZero.Add(DataEncoding.UTF_32BE, mf_ConvString2Byte(DataEncoding.UT
F_32BE, "0"));
htZero.Add(DataEncoding.UTF_32LE, mf_ConvString2Byte(DataEncoding.UT
F_32LE, "0"));
htZero.Add(DataEncoding.JIPSJ, mf_ConvString2Byte(DataEncoding.JIPSJ
, "0"));
htZero.Add(DataEncoding.JIPSE, mf_ConvString2Byte(DataEncoding.JIPSE
, "0"));
htSpaceMiltuByte.Add(DataEncoding.Shift_JIS, mf_ConvString2ByteEx(Da
taEncoding.Shift_JIS, ""));
htSpaceMiltuByte.Add(DataEncoding.JIS, mf_ConvString2ByteEx(DataEnco
ding.JIS, ""));
htSpaceMiltuByte.Add(DataEncoding.EBCDIC, mf_ConvString2ByteEx(DataE
ncoding.EBCDIC, ""));
htSpaceMiltuByte.Add(DataEncoding.IBM, mf_ConvString2ByteEx(DataEncodi
ng.IBM, ""));
htSpaceMiltuByte.Add(DataEncoding.JEF_78, mf_ConvString2ByteEx(DataE
ncoding.JEF_78, ""));
htSpaceMiltuByte.Add(DataEncoding.JEF_83, mf_ConvString2ByteEx(DataE
ncoding.JEF_83, ""));
htSpaceMiltuByte.Add(DataEncoding.KEIS_78, mf_ConvString2ByteEx(Data
Encoding.KEIS_78, ""));
htSpaceMiltuByte.Add(DataEncoding.KEIS_83, mf_ConvString2ByteEx(Data
Encoding.KEIS_83, ""));
htSpaceMiltuByte.Add(DataEncoding.UNISYS, mf_ConvString2ByteEx(DataE
ncoding.UNISYS, ""));
htSpaceMiltuByte.Add(DataEncoding.EUC_JP, mf_ConvString2ByteEx(DataE
ncoding.EUC_JP, ""));
htSpaceMiltuByte.Add(DataEncoding.UTF_8, mf_ConvString2ByteEx(DataEn
coding.UTF_8, ""));
htSpaceMiltuByte.Add(DataEncoding.UTF_16BE, mf_ConvString2ByteEx(Dat
aEncoding.UTF_16BE, ""));
htSpaceMiltuByte.Add(DataEncoding.UTF_16LE, mf_ConvString2ByteEx(Dat
aEncoding.UTF_16LE, ""));
htSpaceMiltuByte.Add(DataEncoding.UTF_32BE, mf_ConvString2ByteEx(Dat
aEncoding.UTF_32BE, ""));
htSpaceMiltuByte.Add(DataEncoding.UTF_32LE, mf_ConvString2ByteEx(Dat
aEncoding.UTF_32LE, ""));
htSpaceMiltuByte.Add(DataEncoding.JIPSJ, mf_ConvString2ByteEx(DataEn
coding.JIPSJ, ""));
htSpaceMiltuByte.Add(DataEncoding.JIPSE, mf_ConvString2ByteEx(DataEn
coding.JIPSE, ""));
#endregion
}
#endregion
#region Convert methods

public override void Convert()


{
// Diagnostic
Watcher wch = Watcher.Instance();
wch.Start();
Report.Add(string.Format("Thread {0} started", Id));
List<XElement> Data = (List<XElement>)base.Data;
SourceLayout = base.InputDataStore;
TargetLayout = base.OutputDataStore;
IMappingLogic mlLogics = base.MappingLogic;
AppParams parms = base.Params;
int lineCount = 0;
// Use this to output total of rows which ha
d been processed to report.
int numberRecord = Data.Count(); // number of Record
List<List<byte[]>> threadBuffer = new List<List<byte[]>>(); // Initi
alize buffer
//Get the external character folder information than the conversion
parameters
//strDefaultGaijiFolder = vParam.GetValue(Setting.NAME_GAIJI_DEFAULT
);
//strUserGaijiFolder = vParam.GetValue(Setting.NAME_GAIJI_USER);
// Get data store
DataStoreItem store = TargetLayout.GetItemByType(MappingLayoutType.D
ataStore, 0);
//process all of the Records
foreach (XElement record in Data)
{
// Get the layout ID of the record
int recordId = Util.ToInt(Util.GetItemId(record.Name.ToString())
);
//get all child item at current Record
List<DataStoreItem> drsItem= TargetLayout.GetChildItems(recordId
);
// Looping through mapping layout (Fixed's record fields)
List<byte[]> byValue = new List<byte[]>();
// processing for all child
foreach (DataStoreItem drs in drsItem)
{
int targetID = drs.Id;
if (drs.ItemType == MappingLayoutType.ItemGroup)
{
// Convert group item node
convertGroupItem(store, record, drs, targetID, ref byVal
ue, numberRecord);
}
else if (drs.ItemType == MappingLayoutType.Item)
{
// item value
convertItem(store, record, drs, targetID, ref byValue, n
umberRecord);
}
}
//Record Split
byte[] RecordSplit; // store Record Split

MappingFixedRecordSplit mfrs = MappingFixedRecordSplit.None;


if (Util.HasKey(store.Properties.Fixed, "
{
mfrs = (MappingFixedRecordSplit)Util.ToInt(store.Properties.F
}
switch (mfrs)
{
case MappingFixedRecordSplit.None:
//No separator
break;
case MappingFixedRecordSplit.CR:
// CR
RecordSplit = new byte[1];
RecordSplit[0] = 0x0D;
byValue.Add(RecordSplit);
break;
case MappingFixedRecordSplit.LF:
// LF
RecordSplit = new byte[1];
RecordSplit[0] = 0x0A;
byValue.Add(RecordSplit);
break;
case MappingFixedRecordSplit.CRLF:
// CRLF
RecordSplit = new byte[2];
RecordSplit[0] = 0x0D;
RecordSplit[1] = 0x0A;
byValue.Add(RecordSplit);
break;
case MappingFixedRecordSplit.Any:
// any
if (Util.IsHexStr(Util.ToBool(store.Properties.Fixed.
{
// If the hexadecimal string
byte[] byRecordSplit = Util.Hex2Byte(store.Propertie
s.Fixed.);
byValue.Add(byRecordSplit);
}
else
{
// mResultFixedConvert = ResultFixedConvert.ErrRecord
SplitCode;
}
break;
}

// check EOF Insertion when last Record's finished


if (lineCount == numberRecord - 1)
{
EOFInsertion EOFI = EOFInsertion.None;
if (Util.HasKey(store.Properties.Fixed, "EOF"))
{
EOFI = (EOFInsertion)Util.ToInt(store.Properties.Fixed.EO
}
if (EOFI == EOFInsertion.Execute)
{
//output EOF(0x1A)
byte []byEOF = new byte[1];
byEOF[0] = 0x1A;
byValue.Add(byEOF);
}
}
threadBuffer.Add(byValue);
lineCount++;

}
Buffers = threadBuffer;
threadBuffer = null;
Report.Add(string.Format("Converter done in {0}.{1}", wch.Second, wc
h.mSecond));
}
private void convertGroupItem(DataStoreItem store, XElement record, Data
StoreItem targetItem, int targetItemId, ref List<byte[]> byValue, int recordNumb
er)
{
List<XElement> xmlTargetNodes = record.Elements(Util.CreateNodeName(
targetItem.ItemType, targetItemId)).ToList();
if (xmlTargetNodes.Count() > 0)
{
foreach (XElement targetNode in xmlTargetNodes)
{
int itemId = Util.ToInt(Util.GetItemId(targetNode.Name.ToStr
ing()));
// Get item layout info
List<DataStoreItem> ListItem = TargetLayout.GetChildItems(it
emId);
foreach (DataStoreItem lItem in ListItem)
{
int targetID = lItem.Id;
if (lItem.ItemType == MappingLayoutType.ItemGroup)
{
convertGroupItem(store, targetNode, lItem, targetID,
ref byValue, recordNumber);
}
else
{
convertItem(store, targetNode, lItem, targetID, ref
byValue, recordNumber);
}
}
}
}
}
private void convertItem(DataStoreItem store, XElement record, DataStore
Item targetItem, int targetItemId, ref List<byte[]> byValue, int recordNumber)
{
string itemValue = "";
//Get the item node
List<XElement> xmlTargetNode = record.Elements(Util.CreateNodeName(t
argetItem.ItemType, targetItemId)).ToList();
// item value
if (xmlTargetNode.Count != 0)
itemValue = Util.GetText(xmlTargetNode[0]);
//check Output Value Type and Final output value
#region check Output Value Type and Final output value
OutputValueType OVTypes = OutputValueType.Normal;
if (Util.HasKey(targetItem.Properties., ""))

OVTypes = (OutputValueType)Util.ToInt(targetItem.Properties..
}
switch (OVTypes)
{
case OutputValueType.Normal:
// itemValue = "";
break;
case OutputValueType.Fixed: // if Fixed load value from targetI
tem.Properties..
itemValue = targetItem.Properties..;
break;
case OutputValueType.Variable:
itemValue = targetItem.Properties..;
if (itemValue == "") //Output number of record
itemValue = recordNumber.ToString(); // Output number o
f record
break;
case OutputValueType.DateTime: // datetime
itemValue = targetItem.Properties..;
break;
}
#endregion
bool isOutput = true;
if (Util.HasKey(targetItem.Properties., ""))
{
isOutput = Util.ToBool(targetItem.Properties..);
}
if (!isOutput) itemValue = "";
//check data layout for convert
#region check data for Convert a string to the byte array

int ItemCount = Util.ToInt(targetItem.Properties.Fixed.);


DataEncoding de = (DataEncoding)Util.ToInt(targetItem.Properties.Fixed
.);
MappingSISO mSISO = mSISO = (MappingSISO)Util.ToInt(targetItem.Prope
rties.Fixed.SISO);
bool bSISOOut = Util.ToBool(targetItem.Properties.Fixed.SISO);
MappingEBCDICType mEBCIDICType = (MappingEBCDICType)Util.ToInt(targe
tItem.Properties.Fixed.EBCDIC);
MappingJEF_KEIS_Type JEF_KEIS_Type = (MappingJEF_KEIS_Type)Util.ToIn
t(targetItem.Properties.Fixed.JEF_KEIS);
MappingConvertError ConvertError = (MappingConvertError)Util.ToInt(t
argetItem.Properties.Fixed.);
string strErrorCode = targetItem.Properties.Fixed.;
Attributes mCharAttribute = (Attributes)Util.ToInt(targetItem.Proper
ties..);
Padding mPadding = (Padding)Util.ToInt(targetItem.Properties.Fixed.
Position mPosition = (Position)Util.ToInt(targetItem.Properties.Fixed.);
MappingZeroOut mZeroOut = (MappingZeroOut)Util.ToInt(store.Propertie
s.Fixed.);
bool bGaijiConvert = Util.ToBool(targetItem.Properties.Fixed.);
MappingDecimalZeroFormat mDecimalZeroFormat = (MappingDecimalZeroFor
mat)Util.ToInt(store.Properties.Fixed.);
int iDecimalCount = Util.ToInt(targetItem.Properties.Fixed.);

PaddingZenkakuSpaceCode mZenkakuSpaceCodes = PaddingZenkakuSpaceCode


.4040;
if (Util.HasKey(store.Properties.Fixed, "")
mZenkakuSpaceCodes = (PaddingZenkakuSpaceCode)Util.ToInt(store.Prope
rties.Fixed.);
#endregion
//Convert a string to write to the byte array
byte[] byOutBuf;
long lRet = ConvertString2ByteArray(
store,
itemValue,
out byOutBuf,
ItemCount,
de,
mSISO,
bSISOOut,
mEBCIDICType,
JEF_KEIS_Type,
ConvertError,
strErrorCode,
mCharAttribute,
mPadding,
mPosition,
mZeroOut,
bGaijiConvert,
mDecimalZeroFormat,
iDecimalCount,
targetItem,
mZenkakuSpaceCodes
);
// If fail to character conversion
i += byOutBuf.Length;
if (mResultFixedConvert != ResultFixedConvert.Success)
{
string strItemName = targetItem.Properties..;
Report.Add(string.Format(": {0} ", strItemName));
if (mResultFixedConvert == ResultFixedConvert.ErrStringConvert)
{
string strConvErrMsglRet = EdiEncoding.GetReurnCodeMsg(lRet)
;

Report.Add(string.Format("[{0}] [{1}]", (int)

rrMsglRet));
}
else
{

Report.Add(string.Format("[{0}]", (int)mResultFixedConve
}
}
byValue.Add(byOutBuf);
}
#region Convert methods Convert String to Byte Array
/// <summary>
/// From string to byte array

/// </summary>
/// <param name="store">DataStoreItem</param>
/// <param name="strBuf"></param>
/// <param name="byOutBuf">(Out)</param>
/// <param name="iItemCount"></param>
/// <param name="mEncordType"></param>
/// <param name="mSISO"></param>
/// <param name="mEBCIDICType">EBCDIC</param>
/// <param name="mJEF_KEIS_Type">JEFKEIS</param>
/// <param name="mConvertError"></param>
/// <param name="strErrorCode"></param>
/// <param name="mCharAttribute"></param>
/// <param name="mPadding"></param>
/// <param name="mPosition"></param>
/// <param name="mZeroOut"></param>
/// <param name="bGaijiConvert"></param>
/// <param name="mDecimalZeroFormat"></param>
/// <param name="iDecimalCount"></param>
/// <param name="targetItem">DataStoreItem</param>
/// <param name="mZenkakuSpaceCodes">PaddingZenkakuSpaceCode</param>
/// <returns></returns>
private long ConvertString2ByteArray(
DataStoreItem store,
string strBuf,
out byte[] byOutBuf,
int iItemCount,
DataEncoding mEncordType,
MappingSISO mSISO,
bool bSISOOut,
MappingEBCDICType mEBCIDICType,
MappingJEF_KEIS_Type mJEF_KEIS_Type,
MappingConvertError mConvertError,
string strErrorCode,
Attributes mCharAttribute,
Padding mPadding,
Position mPosition,
MappingZeroOut mZeroOut,
bool bGaijiConvert,
MappingDecimalZeroFormat mDecimalZeroFormat,
int iDecimalCount,
DataStoreItem targetItem,
PaddingZenkakuSpaceCode mPaddingZenkakuSpaceCodes
)
{
long lRet = 0;
byte[] byFormatTemp = new byte[0];
ing padding etc.
byte[] byConvString2Byte = new byte[0];
yte array
byte[] byValue = new byte[0];
length is stored
decimal dcValue = 0;
string strValue = strBuf;
//If numeric attributes
if (mCharAttribute == Attributes.CHAR_9)
{
strValue = strValue.Trim();

// Work area for perform


// The code conversion b
// Adjust the byte array

}
//Get the padding character
string strPaddings = GetPaddingString(mPadding);
switch (mPosition)
{
case Position.Left:
// Left
//left-justified, because the padding is in the end, it is r
emoved from the end
strValue = strValue.TrimEnd(strPaddings.ToCharArray());
break;
case Position.Right:
// right
// right-justified, because the padding is in the beginning,
it is deleted from the beginning
strValue = strValue.TrimStart(strPaddings.ToCharArray());
break;
}

//To convert a number to a number (Overflow check and numeric conver


sion)
// if (iDecimalCount> 0) changed as follows:
//In the case of 9 attributes, remove the decimal point
if (mCharAttribute == Attributes.CHAR_9 || mCharAttribute == Attribu
tes.CHAR_N)
{
// after Padding removal. Set strValue=0 if strValue is null
if (strValue.Length == 0)
{
strValue = "0";
}
//To convert a number to a number (Overflow check and numeric co
nversion)
dcValue = NumericConvert(store, strValue, mCharAttribute, iItemC
ount, iDecimalCount);
if (mResultFixedConvert == ResultFixedConvert.Success)
{
//Add a 0 decimal digits specified on the layout output as a
string
string strDecimalFormat = new string('0', iDecimalCount);
string strFormat = "{0:0." + strDecimalFormat + "}";
strValue = string.Format(strFormat, dcValue);
//In the case of 9 attributes, remove the decimal point
if (mCharAttribute == Attributes.CHAR_9)
{
int iDecimalPoint = strValue.IndexOf('.');
if (iDecimalPoint > -1)
{
// If it contains a decimal point, I except the deci
mal point
strValue = strValue.Remove(iDecimalPoint, 1);
}
//remove 0 at The leading

string strZero = "0";


strValue = strValue.TrimStart(strZero.ToCharArray());
}
}
}
//initialize the specified byte in the padding character
int nPaddingLen = 0;
ByteInit(
out byFormatTemp,
iItemCount,
mPadding,
mEncordType,
mPosition,
mPaddingZenkakuSpaceCodes,
ref nPaddingLen
);
// If Success
if (mResultFixedConvert == ResultFixedConvert.Success)
{
//when converting to JIS, because that would be insufficient SIS
O worth of space in the case of the conversion of only one character
byte[] byConvertWorkBuf = new byte[strValue.Length * 10];
/
/ Change the size 10 times
int iConvertLen = 0;
//Set the conversion conditions
initializeEdiEncoding(
mEncordType,
mSISO,
bSISOOut,
mEBCIDICType,
mJEF_KEIS_Type,
mConvertError,
strErrorCode,
bGaijiConvert);
lRet = EdiEncoding.StringToAny(byConvertWorkBuf, ref iConvertLen
, strValue);
if (lRet == Cnv.RC_NORMAL)
{
byConvString2Byte = new byte[iConvertLen];
// ensure the
area for the number of bytes of conversion result
System.Buffer.BlockCopy(byConvertWorkBuf, 0, byConvString2By
te, 0, iConvertLen);
}
else
{
// If fail to code conversion
byConvString2Byte = new byte[0];
//Create a byte 0 of byte array
mResultFixedConvert = ResultFixedConvert.ErrStringConvert;
//Set the conversion error
}

}
if (mResultFixedConvert == ResultFixedConvert.Success)
{
//To determine whether the character code conversion byte array
fits into fixed-length area
if (iItemCount < byConvString2Byte.Length)
{
MappingColumnOverflow ofl = MappingColumnOverflow.RetError;
if (Util.HasKey(store.Properties.Fixed, ""))
{
ofl = (MappingColumnOverflow)Util.ToInt(store.Properties
.Fixed.);
}
if (ofl == MappingColumnOverflow.Truncate)

//If you tr

uncate the
{
byte[] byConvertWorkBuf = new byte[strValue.Length * 10]
;
int iConvertLen = 0;
for (int n = 0; n < strValue.Length; n++)
{
EdiEncoding.StringToAny(byConvertWorkBuf, ref iConve
rtLen, strValue.Substring(0, n + 1));
if (iItemCount < iConvertLen)
//I was over.
{
EdiEncoding.StringToAny(byConvertWorkBuf, ref iC
onvertLen, strValue.Substring(0, n)); // And over taking one step forward.
byValue = new byte[iConvertLen];
System.Buffer.BlockCopy(byConvString2Byte, 0, by
Value, 0, iConvertLen);
//Report.Add(string.Format("truncation process [
{0}][{1}]", strValue, strValue.Substring(0, n)));
break;
}
}
}
else
{
// error
mResultFixedConvert = ResultFixedConvert.ErrOverFlow;
byOutBuf = new byte[0];
return 0;
}
}
else
{
//If you do not exceed the number of digits of the layout, c
opy the exact value
byValue = byConvString2Byte;
}
}
//If the error is not happening only
if (mResultFixedConvert == ResultFixedConvert.Success)
{
//To byFormatTemp that you created earlier, to store the byte se
quence encoding conversion.

if (mPosition == Position.Left)
{
//In the case of left-justified, put at the beginning
System.Buffer.BlockCopy(byValue, 0, byFormatTemp, 0, byValue
.Length);
}
else
{
// In the case of right-justified, put at the end
System.Buffer.BlockCopy(byValue, 0, byFormatTemp, byFormatTe
mp.Length - byValue.Length, byValue.Length);
}
}
//Padding is "SpaceMultiByte space", the size of the padding part is
you were an odd number of bytes, entitled to receive out.
if (mResultFixedConvert == ResultFixedConvert.Success)
{
if (mPadding == Padding.SpaceMultiByte)
{
int len = byFormatTemp.Length - byValue.Length;
if (len % nPaddingLen != 0)
{
mResultFixedConvert = ResultFixedConvert.ErrPaddingOverF
low;
}
}
}
// Output
byOutBuf = byFormatTemp;
return lRet;
}
#endregion
#endregion
#region return the padding string (UNICODE)
/// <summary>
/// return the padding string (UNICODE)
/// </summary>
/// <param name="mPadding"></param>
/// <returns></returns>
private string GetPaddingString(Padding mPadding)
{
string strPadding = "";
switch (mPadding)
{
case Padding.NULL:
strPadding = "\x00";
break;
case Padding.Space:
strPadding = " ";
break;
case Padding.Zero:

// If NULL
// In the case of space
// In the case of zero

strPadding = "0";
break;
case Padding.SpaceMultiByte:

// In the case of SpaceM

ultiByte
strPadding = "";
break;
}
return strPadding;
}
#endregion
#region Overflow check and, number numeric conversion of numeric attribu
tes (N 9)
/// <summary>
/// Overflow check and numeric conversion
/// </summary>
/// <param name="dbValue">Number to be converted (9 If attributes, numbe
r after already was decimal digit alignment)</param>
/// <param name="mCharAttribute"></param>
/// <param name="iItemCount"></param>
/// <param name="iDecimalCount"></param>
/// <returns></returns>
private decimal NumericConvert(DataStoreItem store, string strValue, Att
ributes mCharAttribute, int iItemCount, int iDecimalCount)
{
bool bMinusSymbol = false;
bool bPlusSymbol = false;
string strReal = "";
string strDecimal = "";
string strOutNumeric = "";
decimal dcOutValue = 0;
// check sign
if (strValue.Length > 1)
{
// Minus sign was attached
if (strValue.Substring(0, 1) == "-")
{
bMinusSymbol = true;
strValue = strValue.Remove(0, 1);
g of the sign
}
// Plus sign was attached
if (strValue.Substring(0, 1) == "+")
{
bPlusSymbol = true;
strValue = strValue.Remove(0, 1);
g of the sign
}
}

// take the beginnin

// take the beginnin

//Locates the decimal point, to separate the integer and fractional


parts
int iDecimalPoint = strValue.IndexOf('.');
if (iDecimalPoint > -1)
{

// If the point is found


strReal = strValue.Substring(0, iDecimalPoint);
strDecimal = strValue.Substring(iDecimalPoint + 1);
}
else
{
// If it doesn't contains a decimal point
strReal = strValue;
}
//To estimate the maximum number of digits of the integer part from
the layout
int iLayoutMaxRealLen = 0;
if (mCharAttribute == Attributes.CHAR_9)

// In the case of 9 attri

butes
{
iLayoutMaxRealLen = iItemCount - iDecimalCount;
// Number o
f digits - number of decimal digits
}
if (mCharAttribute == Attributes.CHAR_N) // In the case of N attr
ibutes
{
iLayoutMaxRealLen = iItemCount - iDecimalCount;
// Number o
f digits - number of decimal digits
//If it contains a sign
if (bPlusSymbol == true || bMinusSymbol == true) //fail to char
acter conversion
{
iLayoutMaxRealLen--;
}
//If that contain a decimal point
if (strValue.IndexOf('.') > -1)
{
iLayoutMaxRealLen--;
}
}
// check overflow
if (strReal.Length > iLayoutMaxRealLen || strDecimal.Length > iDecim
alCount)
{

MappingColumnOverflow ofl = MappingColumnOverflow.RetError;


if (Util.HasKey(store.Properties.Fixed, ""))
{
ofl = (MappingColumnOverflow)Util.ToInt(store.Properties.Fixe
}
if (ofl == MappingColumnOverflow.Truncate)
{
//If the integer part has caused the overflow
if (strReal.Length > iLayoutMaxRealLen)
{
//cut out up to a maximum of integer digits that were es
timated from the end
strReal = strReal.Substring(strReal.Length - iLayoutMaxR
ealLen);
}
// If the decimal part is causing the overflow
if (strDecimal.Length > iDecimalCount)
{
//cut out up to the length specified on the layout from

the beginning
strDecimal = strDecimal.Substring(0, iDecimalCount);
}
}
else
{
// If error
mResultFixedConvert = ResultFixedConvert.ErrOverFlow;
}
}
if (mResultFixedConvert == ResultFixedConvert.Success)
{
//Create a numeric string
if (bMinusSymbol == true)
{
// If there is a minus sign
strOutNumeric = "-" + strReal + "." + strDecimal;
}
else
{
// If there isn't a minus sign
strOutNumeric = strReal + "." + strDecimal;
}

if (!decimal.TryParse(strOutNumeric, out dcOutValue))


{
// rwReport.Write(string.Format("[{0}]Decimal
mResultFixedConvert = ResultFixedConvert.ErrDecimalConvert;
}
}
return dcOutValue;
}
#endregion
#region return the length that has been initialized
/// <Summary>
// I initialize the specified byte in the padding character.Ensure the
byte array I perform in the function.
/// </ Summary>
/// <The param name = "byBuf"> byte array to initialize </ param>
/// <Param name = "iBufLen"> length of the byte array </ param>
/// <Param name = "mPadding"> padding type </ param>
/// <Param name = "mEncodeType"> character code type </ param>
/// <returns>return the length that has been initialized </ returns>
private int ByteInit(
out byte[] byBuf,
int iBufLen,
Padding mPadding,
DataEncoding mEncodeType,
Position pos,
PaddingZenkakuSpaceCode spc,
ref int nPaddingLen)
{
object objPaddingCode = null; // To store the padding character obj
ects than hash array (associative array)
byte[] byPaddingCode;
// Area that padding characters are s
tored

int i = 0;

// length that has been initialized

// Partitioning
byBuf = new byte[iBufLen];
switch (mPadding)
{
case Padding.Space:
// In the case of space padding
objPaddingCode = htSpace[mEncodeType];
break;
case Padding.Zero:
objPaddingCode = htZero[mEncodeType];
break;
case Padding.SpaceMultiByte:
objPaddingCode = htSpaceMiltuByte[mEncodeType];
break;
}
if (objPaddingCode != null)
{
// To store the padding character
byPaddingCode = new byte[((byte[])objPaddingCode).Length];
byPaddingCode = (byte[])objPaddingCode;
switch (mEncodeType)
{
case DataEncoding.JEF_78:
case DataEncoding.JEF_83:
case DataEncoding.KEIS_78:
case DataEncoding.KEIS_83:
if (spc == PaddingZenkakuSpaceCode.A1A1)
{
byPaddingCode[0] = 0xA1;
byPaddingCode[1] = 0xA1;
}
break;
}
// when iBufLen % byPaddingCode.Length !=0 and mPadding == Paddi
ng.SpaceMultiByte. right-justified / left-justified
bool bNormal = true;
nPaddingLen = byPaddingCode.Length;
int nSpaceMultiLen = iBufLen % byPaddingCode.Length;
if (mPadding == Padding.SpaceMultiByte)
{
if (nSpaceMultiLen != 0)
bNormal = false;
}
if (bNormal)
{
try
{
// I fill all the specified number of digits in the padd
ing value
for (i = 0; i < byBuf.Length; i += byPaddingCode.Length)
{
System.Buffer.BlockCopy(byPaddingCode, 0, byBuf, i,
byPaddingCode.Length);
}
}

catch (Exception ex)


{
mResultFixedConvert = ResultFixedConvert.ErrPaddingOverF
low;
}
}
else
{
if (pos == Position.Left)
{
for (i = nSpaceMultiLen; i < byBuf.Length; i += byPaddin
gCode.Length)
{
System.Buffer.BlockCopy(byPaddingCode, 0, byBuf, i,
byPaddingCode.Length);
}
}
else
{
// right justified, to fill up the front.
for (i = 0; i < byBuf.Length - nSpaceMultiLen; i += byPa
ddingCode.Length)
{
System.Buffer.BlockCopy(byPaddingCode, 0, byBuf, i,
byPaddingCode.Length);
}
}
}
}
return i;

// return the initialized padding length

}
#endregion
#region convert string to byte
/// <summary>
/// Encodes the given string and returns a byte array
/// </summary>
/// <param name="mEncodeType"></param>
/// <param name="strValue"></param>
/// <returns></returns>
private byte[] mf_ConvString2Byte(DataEncoding mEncodeType, string strVa
lue)
{
initializeEdiEncoding(mEncodeType, MappingSISO.Do, true, MappingEBCD
ICType.Default, MappingJEF_KEIS_Type.Normal, MappingConvertError.Break, "", fals
e);
byte[] byWorkBuf = new byte[strValue.Length * 10];
// when converting to JIS, because that would be insufficient SISO w
orth of space in the case of the conversion of only one character
int iConvertLen = 0;
byte[] byOutBuf;
// Output buffer area
EdiEncoding.StringToAny(byWorkBuf, ref iConvertLen, strValue);
byOutBuf = new byte[iConvertLen];
// ensure by the length of t
he area after conversion
System.Buffer.BlockCopy(byWorkBuf, 0, byOutBuf, 0, iConvertLen);
return byOutBuf;

}
/// <summary>
/// Although the collection of character codes padding in the constructo
r, the SISO is in the em space (!), And the state of no SISO.
/// </summary>
/// <param name="mEncodeType"></param>
/// <param name="strValue"></param>
/// <returns></returns>
private byte[] mf_ConvString2ByteEx(DataEncoding mEncodeType, string str
Value)
{
initializeEdiEncoding(mEncodeType, MappingSISO.None, false, MappingE
BCDICType.Default, MappingJEF_KEIS_Type.Normal, MappingConvertError.Break, "", f
alse);
byte[] byWorkBuf = new byte[strValue.Length * 10];
//when converting to JIS, because that would be insufficient SISO wo
rth of space in the case of the conversion of only one character
int iConvertLen = 0;
byte[] byOutBuf;

// Output buffer area

EdiEncoding.StringToAny(byWorkBuf, ref iConvertLen, strValue);


byOutBuf = new byte[iConvertLen];
System.Buffer.BlockCopy(byWorkBuf, 0, byOutBuf, 0, iConvertLen);
return byOutBuf;
}
/// <summary>
/// set the properties of the code conversion class
/// </summary>
/// <param name="mEncordType"></param>
/// <param name="mSISO"></param>
/// <param name="mEBCIDICType"></param>
/// <param name="mJEF_KEIS_Type"></param>
/// <param name="mConvertError"></param>
/// <param name="strErrorCode"></param>
/// <param name="bGaijiConvert"></param>
private void initializeEdiEncoding(
DataEncoding mEncordType,
MappingSISO mSISO,
bool bSISOOut,
MappingEBCDICType mEBCIDICType,
MappingJEF_KEIS_Type mJEF_KEIS_Type,
MappingConvertError mConvertError,
string strErrorCode,
bool bGaijiConvert
)
{
switch (mEncordType)
{
case DataEncoding.Shift_JIS:
EdiEncoding.CodeType = CODE_TYPE.SJIS;
break;
case DataEncoding.JIS:
EdiEncoding.CodeType = CODE_TYPE.JIS;
break;

case DataEncoding.EBCDIC:
EdiEncoding.CodeType = CODE_TYPE.EBCDIC;
break;
case DataEncoding.IBM:
EdiEncoding.CodeType = CODE_TYPE.IBM;
break;
case DataEncoding.JEF_78:
EdiEncoding.CodeType = CODE_TYPE.JEF78;
break;
case DataEncoding.JEF_83:
EdiEncoding.CodeType = CODE_TYPE.JEF83;
break;
case DataEncoding.KEIS_78:
EdiEncoding.CodeType = CODE_TYPE.KEIS78;
break;
case DataEncoding.KEIS_83:
EdiEncoding.CodeType = CODE_TYPE.KEIS83;
break;
case DataEncoding.BINARY:
EdiEncoding.CodeType = CODE_TYPE.BINARY;
break;
case DataEncoding.UNISYS:
EdiEncoding.CodeType = CODE_TYPE.UNISYS;
break;
case DataEncoding.EUC_JP:
EdiEncoding.CodeType = CODE_TYPE.EUC_JP;
break;
case DataEncoding.UTF_8:
EdiEncoding.CodeType = CODE_TYPE.UTF_8;
break;
case DataEncoding.UTF_16BE:
EdiEncoding.CodeType = CODE_TYPE.UTF_16BE;
break;
case DataEncoding.UTF_16LE:
EdiEncoding.CodeType = CODE_TYPE.UTF_16LE;
break;
case DataEncoding.UTF_32BE: EdiEncoding.CodeType = CODE_TYPE.UTF
_32BE; break;
case DataEncoding.UTF_32LE: EdiEncoding.CodeType = CODE_TYPE.UTF
_32LE; break;
case DataEncoding.JIPSJ: EdiEncoding.CodeType = CODE_TYPE.JIPSJ;
break;
case DataEncoding.JIPSE: EdiEncoding.CodeType = CODE_TYPE.JIPSE;
break;
}
//EBCDIC type standard (default value), HITACHI, NEC, IBM
switch (mEBCIDICType)
{
case MappingEBCDICType.Default:
EdiEncoding.EbcdicType = EBCDIC_TYPE.STANDARD;
break;
case MappingEBCDICType.Hitachi:
EdiEncoding.EbcdicType = EBCDIC_TYPE.HITACHI;
break;
case MappingEBCDICType.IBM:
EdiEncoding.EbcdicType = EBCDIC_TYPE.IBM;
break;

case MappingEBCDICType.NEC:
EdiEncoding.EbcdicType = EBCDIC_TYPE.NEC;
break;
case MappingEBCDICType.Fal32Jis: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal32Jis; break;
case MappingEBCDICType.Fal32JisEx: EdiEncoding.EbcdicType = EBCD
IC_TYPE.Fal32JisEx; break;
case MappingEBCDICType.Fal32Asc: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal32Asc; break;
case MappingEBCDICType.Fal32AscEx: EdiEncoding.EbcdicType = EBCD
IC_TYPE.Fal32AscEx; break;
case MappingEBCDICType.Fal52Jis: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal52Jis; break;
case MappingEBCDICType.Fal52JisEx: EdiEncoding.EbcdicType = EBCD
IC_TYPE.Fal52JisEx; break;
case MappingEBCDICType.Fal52Asc: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal52Asc; break;
case MappingEBCDICType.Fal52AscEx: EdiEncoding.EbcdicType = EBCD
IC_TYPE.Fal52AscEx; break;
case MappingEBCDICType.Fal66Jis: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal66Jis; break;
case MappingEBCDICType.Fal66Jis2: EdiEncoding.EbcdicType = EBCDI
C_TYPE.Fal66Jis2; break;
case MappingEBCDICType.Fal66Asc: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal66Asc; break;
case MappingEBCDICType.JipsAsc: EdiEncoding.EbcdicType = EBCDIC_
TYPE.JipsAsc; break;
case MappingEBCDICType.JipsKana: EdiEncoding.EbcdicType = EBCDIC
_TYPE.JipsKana; break;
}
// JEF Kanji level first second level (the default), expansion Kanji
switch (mJEF_KEIS_Type)
{
case MappingJEF_KEIS_Type.Normal:
EdiEncoding.JefKjLevel = JEF_LEVEL.STANDARD;
break;
case MappingJEF_KEIS_Type.Extension:
EdiEncoding.JefKjLevel = JEF_LEVEL.EXTEND;
break;
}
// SISO flag true: single-byte, double-byte mixed mode (the default)
. false: em only mode
switch (mSISO)
{
case MappingSISO.Do:
EdiEncoding.bSISO = true;
break;
case MappingSISO.None:
EdiEncoding.bSISO = false;
break;
}
// Flag to output the SISO true: to output (default value), it is fa
lse: not output
EdiEncoding.bInsSISO = bSISOOut;
// Continue on failure. flag false: Do not continue on failure (defa

ult value), true: to continue on failure


switch (mConvertError)
{
case MappingConvertError.Break:
EdiEncoding.bErrorContinue = false;
break;
case MappingConvertError.Continue:
EdiEncoding.bErrorContinue = true;
break;
}
// Error when the replacement code (Hex code that represents a strin
g)
EdiEncoding.ReplaceCode = strErrorCode;
EdiEncoding.GaijiFolder = strDefaultGaijiFolder;
// Standard external character folder
EdiEncoding.UserGaijiFolder = strUserGaijiFolder;
// User-specified external character folder
if (!string.IsNullOrEmpty(strUserGaijiFolder))
{
EdiEncoding.GaijiFolder = strUserGaijiFolder;
}
// Unicode, EUC-JP Flag whether the external character process in th
e case of true: the extended character processing (default value), false: not
extended character processing
EdiEncoding.bUseGaiji = bGaijiConvert;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
//using InterCOM.EDIProducts.Core;
using InterCOM.EDIProducts.Report;
using InterCOM.EDIProducts.Common;
using InterCOM.EDIProducts.Mapping;
using System.IO;
using System.Diagnostics;
using InterCOM.EDIProducts.CodeConvertLibrary;
using System.Data;
namespace InterCOM.EDIProducts.Data.Reader
{
public class FixedReader : IObjectReader
{
private const string AssemblyVersion = "0.1";
private Writer _report;
private MappingDataBaton _baton = null;

// Module version
// Report object
// Application data obj

ect
private ResultFixedConvert mResultFixedConvert;
private Cnv EdiEncoding;
private int m_iConvertItemNo;
private int m_iConvertRecordNo;
// Number of Record
private int m_iConvertItemGroupNo;
// Group number (fixed
length file)
private FileStream fsFixed;
private BinaryReader brFixed;
private List<List<KeyValuePair<int, string>>>[] buffers = null;
private List<KeyValuePair<int, int>> htRecord;
// List Reocord
private List<KeyValuePair<int, string>> ListData; // List Data
private List<List<KeyValuePair<int, string>>> ListDataFinal; // List Dat
a final
private byte[] byFixedRecordBuf;
// Byte array to store
the contents of one record of fixed length
private int iFixedRecordBufCounter;
private long m_lConvertByte;
private int loopMax = 0;
/// <summary>
/// Constructor
/// </summary>
/// <param name="baton">Application data object</param>
public FixedReader(MappingDataBaton baton)
{
this._baton = baton;
htRecord = new List<KeyValuePair<int, int>>();
ListData = new List<KeyValuePair<int, string>>();
ListDataFinal = new List<List<KeyValuePair<int, string>>>();
EdiEncoding = new Cnv();
byFixedRecordBuf = new byte[0];
this._report = baton.Report;
// Reporting
Version();
}
/// <summary>
/// Return reader module version
/// </summary>
public void Version()
{
_report.Add(string.Format("FixedReader. Version {0}", AssemblyVersio
n));
}
public MappingDataBaton Baton
{
get { return _baton; }
}
/// <summary>
/// NO-OP. Reserved for future use
/// </summary>
/// <returns></returns>
public long Normalize()
{
return 0;
}

/// <summary>
/// NO-OP. Reserved for future use
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public long Validate(object input)
{
return 0;
}
public long Load()
{
long lConvLen = 0;
// Start processing time measurement
Stopwatch stwatch = new Stopwatch();
stwatch.Start();
// _baton.Report.Add("Read File Fixed and Convert");//Start fixed le
ngth mapping data conversion
long lFileSize = 0;
// Opening a fixed-length file (read-only binary)
try
{
fsFixed = new FileStream(this._baton.Parameters.InputDataFile, F
ileMode.Open, FileAccess.Read, FileShare.None);
brFixed = new BinaryReader(fsFixed);
}
catch (Exception ex)
{
mResultFixedConvert = ResultFixedConvert.ErrFixedFileOpen;
_baton.Report.Add(string.Format("Exception.Message{0}", ex.Messag
e));
_baton.Report.Add(string.Format("Exception.Source{0}", ex.Source)
);
_baton.Report.Add(string.Format("Exception.StackTrace{0}", ex.Sta
ckTrace));
return (long)LoadState.Failed;
}
// If successfully opened
if (mResultFixedConvert == ResultFixedConvert.Success)
{
lFileSize = fsFixed.Length;
List<DataStoreItem> listRecordsLayout = new List<DataStoreItem>(
); // List Records in Fixed layout file
listRecordsLayout = _baton.InputDataStore.GetRecords();
// Load Records from Fixed layout file
if (listRecordsLayout.Count == 0)
// If the record is not registered
{
_baton.Report.Add("Record processing (failure information: R
ecord is not registered)");
mResultFixedConvert = ResultFixedConvert.ErrRecordExist;
}
else

{ // If the record has been registered


foreach (DataStoreItem dr in listRecordsLayout)
{
// Retrieve the ID Record
int IdRecord = (int)dr.Id;
// To estimate the size of the record
int iRecSize = getSize(dr);
// Registered in associative array
htRecord.Add(new KeyValuePair<int, int>(IdRecord, iRecSi
ze));
}
// Conversion from fixed-length file to the data store
lConvLen = FixedFile2DataSet();
}
}
// Processing time measurement completion
stwatch.Stop();
// Cleanup
if (brFixed != null) brFixed.Dispose();
if (fsFixed != null) fsFixed.Dispose();
_baton.Report.Add(string.Format("Processing size {0} Byte / file siz
e {1} Byte. Processing time {2} seconds", lConvLen, lFileSize, stwatch.ElapsedMi
lliseconds / 1000));
// Build input tree
XElement xmlTree = createInputTree();
_baton.InputTree = new XDocument(xmlTree);
_baton.Report.Add(string.Format("Create input tree done"));
return (long)LoadState.Success;
}
#region convert input data to tree xml
/// <summary>
/// Create input data tree nodes
/// </summary>
/// <returns></returns>
private long createInputDataTree()
{
long result = 0;
// Number of threads to be spawned
int threadNum = AppSettings.ThreadCount;
// Immediate data tree
int elemCount = ListDataFinal.Count;
int size = elemCount / threadNum;
// redundant items after devide into block.
// Eg: 13 Items / 4 CPU = 3 items per CPU & remain 1 will be redunda
nt.
int tail = elemCount % threadNum;
// Calculate block size
int[] sizes = new int[threadNum];

int[] tails = new int[threadNum];


for (int i = 0; i < sizes.Length; i++)
{
// Calculate data size per thread
sizes[i] = (i * size);
tails[i] = 0;
if (i == sizes.Length - 1) tails[i] = tail;
}
// Devide data into chunks. Number of chunks are given by total thre
ad numbers [AppSettings.ThreadCount]
List<List<KeyValuePair<int, string>>>[] chunks;
int numberChunks = threadNum;
if (tail > 0)
{
numberChunks = threadNum + 1;
}
chunks = new List<List<KeyValuePair<int, string>>>[numberChunks];
for (int i = 0; i < numberChunks; i++)
{
if (i <= numberChunks - 2 || (i == numberChunks - 1 && tail == 0
))
chunks[i] = ListDataFinal.GetRange(sizes[i], size);
else if (tail != 0)
chunks[i] = ListDataFinal.GetRange(sizes[i - 1] + size, tail
);
}
// Prepare buffers
buffers = new List<List<KeyValuePair<int, string>>>[numberChunks];
// Creating thread's options
var converters = (from n in Enumerable.Range(0, numberChunks)
select new FixedInputConverter(n, chunks[n], _bato
n.InputDataStore,
_baton.OutputDataStore, _baton.MappingLogic, _
baton.Parameters, _report))
.ToList();
// Create & spawn threads
foreach (FixedInputConverter converter in converters) converter.Setu
p();
foreach (FixedInputConverter converter in converters) converter.Tear
down();
XElement xmlTree = createXmlTree(converters);
_baton.InputTree = new XDocument(xmlTree);
return result;
}
/// <summary>
/// Create input data tree nodes without multithread
/// </summary>
/// <returns>Input data tree</returns>
private XElement createInputTree()
{
IDataStoreFactory dsSource = _baton.InputDataStore;
List<DataStoreItem> layout = dsSource.GetDataStore().Items;

DataStoreItem dsInput = dsSource.GetItemByType(MappingLayoutType.Dat


aStore);
XElement rootNode = new XElement(Util.CreateNodeName(MappingLayoutTy
pe.DataStore, dsInput.Id));
foreach (List<KeyValuePair<int, string>> record in ListDataFinal)
{
int iRecordID = 0;
List<DataStoreItem> listRecordsLayout = new List<DataStoreItem>(
);
listRecordsLayout = dsSource.GetRecords();

foreach (DataStoreItem item in listRecordsLayout)


{
if (Util.HasKey(item.Properties, "Fixed"))
{
if (item.Properties.Fixed. == record[0].V
iRecordID = item.Id;
}
else
if (Util.HasKey(item.Properties, "Fixed"))
if (item.Properties.Fixed. == record[0].Value)
iRecordID = item.Id;
}
string RecordName = Util.CreateNodeName(dsSource.GetItem(iRecord
ID).ItemType, iRecordID);
XElement Xrecord = new XElement(RecordName);
int loopID = 0;
while (loopID < record.Count)
{
DataStoreItem item = dsSource.GetItem(record[loopID].Key);
string ItemName = Util.CreateNodeName(item.ItemType, item.Id
);
switch (item.ItemType)
{
case MappingLayoutType.Record:
loopID += 1;
break;
case MappingLayoutType.ItemGroup:
loopID += 1;
XElement iItemGroup = null;
DataStoreItem itemGroup = dsSource.GetItem(item.Id);
int numItemInGroup = Util.ToInt(itemGroup.Properties
..);
for (int i=0;i<numItemInGroup;i++)
{
iItemGroup = new XElement(ItemName);
DataStoreItem childitem = dsSource.GetItem(recor
d[loopID + i].Key);
string ItemNameNode = Util.CreateNodeName(childi
tem.ItemType, childitem.Id);
XElement iItem = new XElement(ItemNameNode, reco
rd[loopID + i].Value);
if (!iItem.Value.Equals(""))
iItemGroup.Add(iItem);
if (iItemGroup != null) Xrecord.Add(iItemGroup);
}
loopID += numItemInGroup;
break;
case MappingLayoutType.Item:

XElement iItemNode = new XElement(ItemName, record[l


oopID].Value);
if (!iItemNode.Value.Equals(""))
Xrecord.Add(iItemNode);
loopID += 1;
break;
}
}
rootNode.Add(Xrecord);
}
return rootNode;
}
/// <summary>
/// create xml tree
/// </summary>
/// <param name="converters"></param>
/// <returns></returns>
private XElement createXmlTree(List<FixedInputConverter> converters)
{
// Create root node
DataStoreItem dsInput = _baton.InputDataStore.GetItemByType(MappingL
ayoutType.DataStore);
XElement rootNode = new XElement(Util.CreateNodeName(MappingLayoutTy
pe.DataStore, dsInput.Id));
for (int i = 0; i < converters.Count(); i++)
{
var converter = converters[i];
foreach (XElement node in converter.Buffer)
{
XElement nonEmptyNode = new XElement(node.Name);
foreach (XElement childNode in node.Elements())
{
if (!childNode.Value.Equals(""))
nonEmptyNode.Add(childNode);
}
XElement treeNode = (XElement) nonEmptyNode;
rootNode.Add(treeNode);
}
}
return rootNode;
}
#endregion
/// <summary>
/// Get size of a Record from layout
/// </summary>
/// <param name="record"></param>
/// <returns>return size</returns>
private int getSize(DataStoreItem record)
{
int size = 0;
List<DataStoreItem> listChild = _baton.InputDataStore.GetChildItems(
record.Id);
foreach (DataStoreItem child in listChild)

switch (child.ItemType)
{
case MappingLayoutType.Record:
size += getSize(child);
break;
case MappingLayoutType.ItemGroup:
size += Util.ToInt(child.Properties..
break;
case MappingLayoutType.Item:
size += Util.ToInt(child.Properties.Fixed.);
break;
}
}
return size;
}
/// <summary>
/// Read number byte from fixed file
/// </summary>
/// <param name="iByte">Read size</param>
/// <returns></returns>
private int ReadFixedFileByByte(int iByte)
{
int iReadSize = 0;
// Already After confirming that can lead binary object
if (brFixed != null)
{
try
{
// Read a specified number of digits
byFixedRecordBuf = brFixed.ReadBytes(iByte);
iFixedRecordBufCounter = 0;
iReadSize = byFixedRecordBuf.Length;
}
catch (Exception ex)
{
mResultFixedConvert = ResultFixedConvert.ErrFixedFileRead;
_report.Add(string.Format("An error has occurred during file
[{0}] reading.", fsFixed.Name));
}
}
return iReadSize;
}
/// <summary>
/// The current file pointer, a check is made to determine to match any
records on the layout, if you have the appropriate, and returns the ID
/// </summary>
/// <returns></returns>
private int mf_RecordDistinction()
{
DataStoreItem store = _baton.InputDataStore.GetItemByType(MappingLay
outType.DataStore, 0); // get DataStore Fixed
int iRetID = 0; // Check the results and set the value if applicable
ID was able to discover
bool bDistinctionMath = false; // A Boolean value that indicates wh
ether a match is found
List<string> arReadKubun = new List<string>();
// Area to k
eep the status of the comparison

// Keep save the current location of the current stream


long lRefugePosition = fsFixed.Position;
// Loop list Record in htRecord
foreach (KeyValuePair<int, int> de in htRecord)
{
string strCmpMsg = "";
// Record comparison
string strValue = "";
int iRecordID = (int)de.Key;
// Get record ID
int iRecSize = (int)de.Value;
// Get number of bytes curre
nt record
DataStoreItem CurentRecordLayout = _baton.InputDataStore.GetItem
(iRecordID);
// Get record name
string strRecordName = CurentRecordLayout.LocalName;
// If the length read large remaining size of the fixed-length f
ile
if (fsFixed.Length - fsFixed.Position < iRecSize)
{
continue;
// Search for another record
}
// Reads a fixed file bye record size, a result of the read is s
tored in "byFixedRecordBuf"
ConvertFromReadProcess(iRecSize);
// If the read result error
if (mResultFixedConvert != ResultFixedConvert.Success)
{
// Stop
break;
}
// If the settings there are more than one, run the number of ti
mes of a set number
List<DataStoreItem> dt = _baton.InputDataStore.GetRecords();
List<DataStoreItem> Rows = new List<DataStoreItem>();
foreach (DataStoreItem data in dt)
{
if (Util.HasKey(data.Properties, "Fixed")) {
if (Util.ToInt(data.Properties.Fixed.ParentID)
RecordLayout.Properties..ID))
Rows.Add(data);
} else
if (Util.HasKey(data.Properties.Fixed, "ID"))
{
if (Util.ToInt(data.Properties.Fixed.ID) == Util.ToInt(Curen
tRecordLayout.Properties..ID))
Rows.Add(data);
}
}
foreach (DataStoreItem dr in Rows)
{
bDistinctionMath = false;
int iID = 0;
if (Util.HasKey(dr.Properties.Fixed, "ID"))
{
iID = Util.ToInt(dr.Properties.Fixed.ID);
}

if (iID < 0)
{
continue;
}

int size = 0;
if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""))
size = Util.ToInt(CurentRecordLayout.Properties.Fixed.);
byte[] byDistinction = new byte[size];
// Check the starting column is set to 1 or more
if (size < 1)
{
_baton.Report.Add(string.Format("Record name starts digi
ts of [{0}] has become 0. You must specify one or more of the value.", strRecord
Name));
break;
}
// Digit number of records classification values, respond to
problems that an application error occurs if you are over the size of the recor
d.
if (iRecSize < ((Util.ToInt(CurentRecordLayout.Properties.Fixed.
1) + size))
{
_baton.Report.Add(string.Format("Record name [{0}] of th
e division value order of magnitude as the start position of will not exceed the
record size.", strRecordName));
break;
}
// From the read byte array, to retrieve the number of digit
s from the specified start digit
Buffer.BlockCopy(byFixedRecordBuf, Util.ToInt(CurentRecordLa
yout.Properties.Fixed.) - 1, byDistinction, 0, size);
// Convert a byte array segment value is in the string
// Check data layout for convert
#region check data for Convert a string to the byte array

DataEncoding dec = DataEncoding.Shift_JIS;


if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""
{
dec = (DataEncoding)Util.ToInt(CurentRecordLayout.Proper
ties.Fixed.);
}
MappingSISO mSISO = MappingSISO.None;
if (Util.HasKey(CurentRecordLayout.Properties.Fixed, "SISO"))
{
mSISO = (MappingSISO)Util.ToInt(CurentRecordLayout.Prope
rties.Fixed.SISO);
}

MappingEBCDICType mEBCIDICType = MappingEBCDICType.Default;


if (Util.HasKey(CurentRecordLayout.Properties.Fixed, "EBCDIC
{
mEBCIDICType = (MappingEBCDICType)Util.ToInt(CurentRecor
dLayout.Properties.Fixed.EBCDIC);

}
MappingJEF_KEIS_Type JEF_KEIS_Type = MappingJEF_KEIS_Type.No
rmal;

if (Util.HasKey(CurentRecordLayout.Properties.Fixed, "JEF_KEIS
{
JEF_KEIS_Type = (MappingJEF_KEIS_Type)Util.ToInt(CurentR
ecordLayout.Properties.Fixed.JEF_KEIS);
}
MappingConvertError ConvertError = MappingConvertError.Break
;

if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""
{
ConvertError = (MappingConvertError)Util.ToInt(CurentRec
ordLayout.Properties.Fixed.);
}

string strErrorCode = "";


if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""
{
strErrorCode = CurentRecordLayout.Properties.Fixed.
}
Attributes mCharAttribute = Attributes.CHAR_X;
if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""))
{
mCharAttribute = (Attributes)Util.ToInt(CurentRecordLayo
ut.Properties.Fixed.);
}

Padding mPadding = Padding.Space;


if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""
{
mPadding = (Padding)Util.ToInt(CurentRecordLayout.Proper
ties.Fixed.);
}
Position mPosition = Position.Left;
if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""))
{
mPosition = (Position)Util.ToInt(CurentRecordLayout.Prop
erties.Fixed.);
}

bool bGaijiConvert = true;


if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""))
{
bGaijiConvert = Util.ToBool(CurentRecordLayout.Propertie
s.Fixed.);
}

MappingZeroOut mZeroOut = MappingZeroOut.Null;


if (Util.HasKey(store.Properties.Fixed, ""))
{
mZeroOut = (MappingZeroOut)Util.ToInt(store.Properties.Fi
}
MappingDecimalZeroFormat mDecimalZeroFormat = MappingDecimal
ZeroFormat.None;

if (Util.HasKey(store.Properties.Fixed, "")
{
mDecimalZeroFormat = (MappingDecimalZeroFormat)Util.ToIn
t(store.Properties.Fixed.);
}

int iDecimalCount = 0;
if (Util.HasKey(CurentRecordLayout.Properties.Fixed, ""
{
iDecimalCount = Util.ToInt(CurentRecordLayout.Properties
.Fixed.);
}
#endregion
// Initialize encoding
initializeEdiEncoding(dec, mSISO, true, mEBCIDICType, JEF_KE
IS_Type, ConvertError, strErrorCode, bGaijiConvert);
long lRet = -1;
// Convert byte array to string
lRet = ConvertByteArray2String(
byDistinction,
out strValue,
size,
mCharAttribute,
mPadding,
mPosition,
mZeroOut,
mDecimalZeroFormat,
iDecimalCount);
if (mResultFixedConvert != ResultFixedConvert.Success)
{
mResultFixedConvert = ResultFixedConvert.Success;
fsFixed.Position = lRefugePosition;
strCmpMsg = string.Format("Record name [{0}] or the comp
arison> Kanji code conversion to fail. The read byte array = [{1}] character cod
e []", strRecordName, BitConverter.ToString(byDistinction));
arReadKubun.Add(strCmpMsg);
continue;
}
strCmpMsg = string.Format("Record name [{0}] or Compare> lay
out classification value]: read segment value = [{1}]>", strRecordName, strValue
);

string[] arDistinction = new String[5];


if (Util.HasKey(CurentRecordLayout.Properties, "Fixed
arDistinction = CurentRecordLayout.Properties.Fixed
else
if (Util.HasKey(CurentRecordLayout.Properties, "Fixed"))
arDistinction = CurentRecordLayout.Properties.Fixed..Sp
;
foreach (string strDistinction in arDistinction)
// In all the given values classified comparison, whether a match is found?
{
// Compare they match
if (strDistinction == strValue)

{
bDistinctionMath = true;
break;

// Consistent

}
}
// escape the loop because the classification values do not
match
if (bDistinctionMath == false)
{
break;
}
}
// If there is a matching record classification
if (bDistinctionMath == true)
{
strCmpMsg += "";
iRetID = iRecordID;
// To store the argument
s of ID
break;

// After the match escap

e
}
else
{
strCmpMsg += "";
fsFixed.Position = lRefugePosition;
}
// Record the converted contents
arReadKubun.Add(strCmpMsg);
}
if (bDistinctionMath == false && arReadKubun.Count > 0)
{
foreach (string strReadKubun in arReadKubun)
{
_baton.Report.Add(string.Format("Classification value judgme
nt:{0}", strReadKubun));
}
mResultFixedConvert = ResultFixedConvert.ErrRecordDistinction;
}
//_baton.Report.Add(string.Format("convert status:{0}/{1}", fsFixed.
Position, fsFixed.Length));
return iRetID;
}
#region convert string to byte
/// <summary>
/// Read Specified number of bytes from file
/// </summary>
/// <param name="byteSize">Specified number of bytes</param>
/// <returns>number of bytes read</returns>
private long ConvertFromReadProcess(int byteSize)
{
long readSize = 0;
//Already After confirming that can lead binary object
if (brFixed != null)
{

// read a specified number of digits


byFixedRecordBuf = brFixed.ReadBytes(byteSize);
iFixedRecordBufCounter = 0;
readSize = byFixedRecordBuf.Length;
}
return readSize;
}
/// <summary>
/// Convert byte array to string
/// </summary>
private long ConvertByteArray2String(
byte[] byBuf,
out string strOutBuf,
int iItemCount,
Attributes mCharAttribute,
Padding mPadding,
Position mPosition,
MappingZeroOut mZeroOut,
MappingDecimalZeroFormat mDecimalZeroFormat,
int iDecimalCount
)
{
long lRet;
string strValue = "";
strOutBuf = "";
// Kanji code conversion
lRet = EdiEncoding.AnyToString(byBuf, byBuf.Length, ref strValue);
// Check the results of Kanji conversion
if (lRet > 0)
{
strOutBuf = "";
mResultFixedConvert = ResultFixedConvert.ErrStringConvert;
// Conversion failed
return lRet;
}
// In the case of non-binary padding removal
if (mCharAttribute != Attributes.CHAR_B)
{
// Get the padding character
string strPaddings = GetPaddingString(mPadding);
// Divided the padding process by right-justified, left-justifie
d
switch (mPosition)
{
case Position.Left:
// In the case of left-justified, padding is in the end,
it's removed from the end
strValue = strValue.TrimEnd(strPaddings.ToCharArray());
// Corresponding to the full-width space padding
if (mPadding == Padding.Space || mPadding == Padding.Spa
ceMultiByte)
{
char[] trimChars = { ' ', '' };
strValue = strValue.TrimEnd(trimChars);
}

break;
case Position.Right:
// In the case of right-justified, padding is in the beg
inning, it's deleted from the beginning
strValue = strValue.TrimStart(strPaddings.ToCharArray())
;
// Corresponding to the full-width space padding
if (mPadding == Padding.Space || mPadding == Padding.Spa
ceMultiByte)
{
char[] trimChars = { ' ', '' };
strValue = strValue.TrimStart(trimChars);
}
break;
}
}
// In the case of 9 attributes N attributes
if (mCharAttribute == Attributes.CHAR_9 || mCharAttribute == Attribu
tes.CHAR_N)
{
decimal dcValue;
// After removing the padding value to complement 0 by consideri
ng the case where is NULL
if (strValue.Length == 0)
{
strValue = "0";
}
// In the case of 9 attributes are added, because there is no de
cimal point, the decimal point to the specified location on the layout
if (mCharAttribute == Attributes.CHAR_9 && iDecimalCount > 0)
{
int iDecimalPont = strValue.Length - iDecimalCount;
// By padding removal, because in some cases 0 of the end of
the need had been removed, complement the specified number of decimals
if (iDecimalPont > 0)
// If the length after p
adding removal is greater than the number of decimals
{
strValue = strValue.Insert(iDecimalPont, "."); // Inser
t a decimal point
}
if (iDecimalPont == 0)
// If the length of the
padding after removal of all the number of decimals
{
strValue = "0." + strValue;
// put a
"0." to head
}
if (iDecimalPont < 0)
// If the length of the
post-padding removal is less than the number of decimals
{
string strDecimalValue = "0.";
strDecimalValue += new string('0', System.Math.Abs(iDeci
malPont));
strDecimalValue += strValue;
strValue = strDecimalValue;
}

}
// Overflow do check.
// Case when overflow is truncation as a result, it has been tru
ncated to the return value is to be returned
// Case when overflow is now returns an error, the value to "mRe
sultFixedConvert" is set
dcValue = NumericConvert(strValue, mCharAttribute, iItemCount, i
DecimalCount);
// If not result problems of processing up to the above
if (mResultFixedConvert == ResultFixedConvert.Success)
{
// Divide processing when the real is otherwise the case tha
t has become 0
if (dcValue == 0)
{
// If the value is 0
// Divide the processing by the value of the zero output
int zeroOutput = 1;
if (Util.HasKey(_baton.InputDataStore.GetItemByType(Mapp
ingLayoutType.DataStore).Properties.Fixed, ""))
zeroOutput = Util.ToInt(_baton.InputDataStore.GetIte
mByType(MappingLayoutType.DataStore).Properties.Fixed.);
switch ((MappingZeroOut)(zeroOutput))
{
// If there is an instruction so as to output a NULL
character
case MappingZeroOut.Null:
strValue = "";
// Output is
empty
break;
// When there is support so as to output a 0
case MappingZeroOut.Zero:
strValue = "0";
// Output is
0
break;
}
}
else
{ // If the value is not 0
string strFormat = "{0}";
string strDecimalFormat;
// Handling processing of the end in the decimal point
switch (mDecimalZeroFormat)
{
// If you remove the extra 0 in the fractional part
case MappingDecimalZeroFormat.Remove:
// If you remove the extra 0 in the fractional p
art...
strDecimalFormat = new string('#', iDecimalCount
);
strFormat = "{0:0." + strDecimalFormat + "}";
break;
// If you do not remove the extra 0 in the fractiona
l part
case MappingDecimalZeroFormat.None:
// Specify digit number 0 padding the fractional

part
strDecimalFormat = new string('0', iDecimalCount
);
strFormat = "{0:0." + strDecimalFormat + "}";
break;
}
strValue = string.Format(strFormat, dcValue);
}
}
}
// Copy the value to the output area
strOutBuf = strValue;
return lRet;
}
/// <summary>
/// Set the properties of the code conversion class
/// </summary>
private void initializeEdiEncoding(
DataEncoding mEncordType,
MappingSISO mSISO,
bool bSISOOut,
MappingEBCDICType mEBCIDICType,
MappingJEF_KEIS_Type mJEF_KEIS_Type,
MappingConvertError mConvertError,
string strErrorCode,
bool bGaijiConvert
)
{
// Specifies the conversion type to property
switch (mEncordType)
{
case DataEncoding.Shift_JIS:
EdiEncoding.CodeType = CODE_TYPE.SJIS;
break;
case DataEncoding.JIS:
EdiEncoding.CodeType = CODE_TYPE.JIS;
break;
case DataEncoding.EBCDIC:
EdiEncoding.CodeType = CODE_TYPE.EBCDIC;
break;
case DataEncoding.IBM:
EdiEncoding.CodeType = CODE_TYPE.IBM;
break;
case DataEncoding.JEF_78:
EdiEncoding.CodeType = CODE_TYPE.JEF78;
break;
case DataEncoding.JEF_83:
EdiEncoding.CodeType = CODE_TYPE.JEF83;
break;
case DataEncoding.KEIS_78:
EdiEncoding.CodeType = CODE_TYPE.KEIS78;
break;
case DataEncoding.KEIS_83:
EdiEncoding.CodeType = CODE_TYPE.KEIS83;
break;
case DataEncoding.BINARY:

EdiEncoding.CodeType = CODE_TYPE.BINARY;
break;
case DataEncoding.UNISYS:
EdiEncoding.CodeType = CODE_TYPE.UNISYS;
break;
case DataEncoding.EUC_JP:
EdiEncoding.CodeType = CODE_TYPE.EUC_JP;
break;
case DataEncoding.UTF_8:
EdiEncoding.CodeType = CODE_TYPE.UTF_8;
break;
case DataEncoding.UTF_16BE:
EdiEncoding.CodeType = CODE_TYPE.UTF_16BE;
break;
case DataEncoding.UTF_16LE:
EdiEncoding.CodeType = CODE_TYPE.UTF_16LE;
break;
// 2007/10/30
case DataEncoding.UTF_32BE: EdiEncoding.CodeType = CODE_TYPE.UTF
_32BE; break;
case DataEncoding.UTF_32LE: EdiEncoding.CodeType = CODE_TYPE.UTF
_32LE; break;
case DataEncoding.JIPSJ: EdiEncoding.CodeType = CODE_TYPE.JIPSJ;
break;
case DataEncoding.JIPSE: EdiEncoding.CodeType = CODE_TYPE.JIPSE;
break;
}
// EBCDIC type standard (default value), HITACHI, NEC, IBM
switch (mEBCIDICType)
{
case MappingEBCDICType.Default:
EdiEncoding.EbcdicType = EBCDIC_TYPE.STANDARD;
break;
case MappingEBCDICType.Hitachi:
EdiEncoding.EbcdicType = EBCDIC_TYPE.HITACHI;
break;
case MappingEBCDICType.IBM:
EdiEncoding.EbcdicType = EBCDIC_TYPE.IBM;
break;
case MappingEBCDICType.NEC:
EdiEncoding.EbcdicType = EBCDIC_TYPE.NEC;
break;
case MappingEBCDICType.Fal32Jis: EdiEncoding.EbcdicType =
_TYPE.Fal32Jis; break;
case MappingEBCDICType.Fal32JisEx: EdiEncoding.EbcdicType
IC_TYPE.Fal32JisEx; break;
case MappingEBCDICType.Fal32Asc: EdiEncoding.EbcdicType =
_TYPE.Fal32Asc; break;
case MappingEBCDICType.Fal32AscEx: EdiEncoding.EbcdicType
IC_TYPE.Fal32AscEx; break;
case MappingEBCDICType.Fal52Jis: EdiEncoding.EbcdicType =
_TYPE.Fal52Jis; break;
case MappingEBCDICType.Fal52JisEx: EdiEncoding.EbcdicType
IC_TYPE.Fal52JisEx; break;
case MappingEBCDICType.Fal52Asc: EdiEncoding.EbcdicType =
_TYPE.Fal52Asc; break;
case MappingEBCDICType.Fal52AscEx: EdiEncoding.EbcdicType

EBCDIC
= EBCD
EBCDIC
= EBCD
EBCDIC
= EBCD
EBCDIC
= EBCD

IC_TYPE.Fal52AscEx; break;
case MappingEBCDICType.Fal66Jis: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal66Jis; break;
case MappingEBCDICType.Fal66Jis2: EdiEncoding.EbcdicType = EBCDI
C_TYPE.Fal66Jis2; break;
case MappingEBCDICType.Fal66Asc: EdiEncoding.EbcdicType = EBCDIC
_TYPE.Fal66Asc; break;
case MappingEBCDICType.JipsAsc: EdiEncoding.EbcdicType = EBCDIC_
TYPE.JipsAsc; break;
case MappingEBCDICType.JipsKana: EdiEncoding.EbcdicType = EBCDIC
_TYPE.JipsKana; break;
}
// JEF Kanji level first second level (the default), expansion Kanji
switch (mJEF_KEIS_Type)
{
case MappingJEF_KEIS_Type.Normal:
EdiEncoding.JefKjLevel = JEF_LEVEL.STANDARD;
break;
case MappingJEF_KEIS_Type.Extension:
EdiEncoding.JefKjLevel = JEF_LEVEL.EXTEND;
break;
}
// SISO flag true: single-byte, double-byte mixed mode (the default)
, false: em only mode
switch (mSISO)
{
case MappingSISO.Do:
EdiEncoding.bSISO = true;
break;
case MappingSISO.None:
EdiEncoding.bSISO = false;
break;
}
EdiEncoding.bInsSISO = bSISOOut;
switch (mConvertError)
{
case MappingConvertError.Break:
EdiEncoding.bErrorContinue = false;
break;
case MappingConvertError.Continue:
EdiEncoding.bErrorContinue = true;
break;
}
EdiEncoding.ReplaceCode = strErrorCode;
EdiEncoding.bUseGaiji = bGaijiConvert;
}
#endregion
#region return the padding string (UNICODE)
/// <summary>
/// return the padding string (UNICODE)
/// </summary>
/// <param name="mPadding"></param>
/// <returns></returns>
private string GetPaddingString(Padding mPadding)
{

string strPadding = "";


switch (mPadding)
{
case Padding.NULL:
strPadding = "\x00";
break;
case Padding.Space:
strPadding = " ";
break;
case Padding.Zero:
strPadding = "0";
break;
case Padding.SpaceMultiByte:
strPadding = "";
break;
}
return strPadding;
}
#endregion
#region Overflow check and, number numeric conversion of numeric attribu
tes (N 9)
/// <summary>
/// Overflow check and numeric conversion
/// </summary>
/// <param name="strValue"></param>
/// <param name="mCharAttribute"></param>
/// <param name="iItemCount"></param>
/// <param name="iDecimalCount"></param>
/// <returns></returns>
private decimal NumericConvert(string strValue, Attributes mCharAttribut
e, int iItemCount, int iDecimalCount)
{
bool bMinusSymbol = false;
bool bPlusSymbol = false;
string strReal = "";
string strDecimal = "";
string strOutNumeric = "";
decimal dcOutValue = 0;
if (strValue.Length > 1)
{
if (strValue.Substring(0, 1) == "-")
{
bMinusSymbol = true;
strValue = strValue.Remove(0, 1);
}
if (strValue.Substring(0, 1) == "+")
{
bPlusSymbol = true;
strValue = strValue.Remove(0, 1);
}
}
int iDecimalPoint = strValue.IndexOf('.');
if (iDecimalPoint > -1)
{
strReal = strValue.Substring(0, iDecimalPoint);

strDecimal = strValue.Substring(iDecimalPoint + 1);


}
else
{
strReal = strValue;
}
int iLayoutMaxRealLen
if (mCharAttribute ==
{
iLayoutMaxRealLen
}
if (mCharAttribute ==
{
iLayoutMaxRealLen

= 0;
Attributes.CHAR_9)
= iItemCount - iDecimalCount;
Attributes.CHAR_N)
= iItemCount - iDecimalCount;

if (bPlusSymbol == true || bMinusSymbol == true)


{
iLayoutMaxRealLen--;
}
if (strValue.IndexOf('.') > -1)
{
iLayoutMaxRealLen--;
}
}
// If the actual length of the fractional part, integer part has fal
len more than the number of digits on the layout
if (strReal.Length > iLayoutMaxRealLen || strDecimal.Length > iDecim
alCount)
{
// If you have the data store "when overflow specified" is, has
become a truncated
MappingColumnOverflow Overflow = MappingColumnOverflow.RetError;
Overflow = (MappingColumnOverflow)Util.ToInt(_baton.InputDataSto
re.GetItemByType(MappingLayoutType.DataStore).Properties.Fixed.);
if (Util.HasKey(_baton.InputDataStore.GetItemByType(MappingLayou
tType.DataStore).Properties.Fixed, ""))
if (Overflow == MappingColumnOverflow.Truncate)
{
// If the integer part has caused the overflow
if (strReal.Length > iLayoutMaxRealLen)
{
// I take out up to a maximum of integer digits that
were estimated from the end
strReal = strReal.Substring(strReal.Length - iLayout
MaxRealLen);
}
//If the fractional part is causing the overflow
if (strDecimal.Length > iDecimalCount)
{
// I cut out up to the length specified on the layou
t from the beginning
strDecimal = strDecimal.Substring(0, iDecimalCount);
}
}
else
{
// If the "specified at the time of overflow" is an erro
r

mResultFixedConvert = ResultFixedConvert.ErrOverFlow;
}
}
if (mResultFixedConvert == ResultFixedConvert.Success)
{
// Create a numeric string
if (bMinusSymbol == true)
{
// If there is a minus sign
strOutNumeric = "-" + strReal + "." + strDecimal;
}
else
{
// No minus sign
strOutNumeric = strReal + "." + strDecimal;
}
// When the classification value judgment, there is a possibilit
y that through here
if (!decimal.TryParse(strOutNumeric, out dcOutValue))
{
_baton.Report.Add(string.Format("[{0}] Could not be converte
d to Decimal type", strOutNumeric));
mResultFixedConvert = ResultFixedConvert.ErrDecimalConvert;
}
}
return dcOutValue;
}
#endregion
#region Fixed to DataSet
/// <summary>
/// Read a fixed file to data set
/// </summary>
/// <param name="iID">ID of the root</param>
/// <returns>The read size</returns>
private long FixedFile2DataSet()
{
long lReadByte = 0; // Storing the read length (byte length)
if (mResultFixedConvert != ResultFixedConvert.Success)
{
return 0;
}
DataStoreItem IDataStore = _baton.InputDataStore.GetItemByType(Mappi
ngLayoutType.DataStore);
MappingRecordDistinction recordDiscrimination = (MappingRecordDistin
ction) Util.ToInt(IDataStore.Properties.Fixed.);
switch ((MappingRecordDistinction)recordDiscrimination)
{
case MappingRecordDistinction.Length: // If the record length d
etermination

List<DataStoreItem> RecordList = _baton.InputDataStore.GetRe


cords();
int RecordMax = RecordList.Count;
// Number of Record
int RecordCount = 0;
// Record counter (increment for e
ach record)
while (fsFixed.Position < fsFixed.Length)
{
// Loop until the record information is lost
for (RecordCount = 0; RecordCount < RecordMax; RecordCou
nt++)
{
DataStoreItem CurrentRecord = RecordList[RecordCount
];
int RecordID = CurrentRecord.Id; // Get the record I
D
int iLoopMax = Util.ToInt(CurrentRecord.Properties.Fixed
.);
int iLayoutLoopMax = iLoopMax;

int valueOfCurrentRecord = ValueFromKey(RecordID);


// If the size of the record is 0 bytes
if (valueOfCurrentRecord == 0)
{
string RecordName = CurrentRecord.Properties..
_baton.Report.Add(string.Format("Size of the rec
ord name [{0}] is 0 bytes.", RecordName));
mResultFixedConvert = ResultFixedConvert.ErrReco
rdZero;
fsFixed.Position = fsFixed.Length;
break;
}
// Record number of loops (not limited to a specifie
d number of records, be sure to run once)
int i = 0;
do
{
// It has reached the end of the file, the last
1 byte to determine whether 0x1A
if (fsFixed.Position == fsFixed.Length - 1)
{
long lStackPosition = fsFixed.Position; // S
ave the current file pointer
ReadFixedFileByByte(1);
fsFixed.Position = lStackPosition;
// B
ack because read
if (byFixedRecordBuf[0] == '\x1A')
{
RecordCount = RecordMax;
// Set the
conditions to escape the record information loop
fsFixed.Position = fsFixed.Length; // Si
nce become a permanent loop, seek to the end of file
break;
// Force escape
}
}
// If a record is being read and it is exceeds t
he remaining file size

if (fsFixed.Length - fsFixed.Position < valueOfC


urrentRecord)
{
RecordMidwayEOF;

mResultFixedConvert = ResultFixedConvert.Err
// File is the end in the middle of a record
fsFixed.Position = fsFixed.Length;
// Seek to the end of the file
break;
}
// Reading of the record
ReadFixedFileByByte(valueOfCurrentRecord);
// if error
if (mResultFixedConvert != ResultFixedConvert.Su

ccess)
{
fsFixed.Position = fsFixed.Length;

// S

eek to the end of the file


break;
}
// Handle the relevant record
lReadByte += FixedRecord2DataSet(RecordID);
if (mResultFixedConvert != ResultFixedConvert.Su
ccess)
{
fsFixed.Position = fsFixed.Length;

// S

eek to the end of the file


}
// In consideration of the case the record was o
ver halfway, confirm the exit record information is a file even during repeated
if (fsFixed.Position == fsFixed.Length)
{
RecordCount = RecordMax;
// Set the con
ditions to escape the record information loop
// If read byte Success, add all data 1 reco
rd to ListDataFinal and reset ListData
ListDataFinal.Add(ListData);
ListData = new List<KeyValuePair<int, string
>>();
break;
}
// The number of repetitions counter
i++;
// If the number of records in the layout is spe
cified as 0, there is a need to continue to the end of the file
// Since the last file that is detected by the a
bove process, there remains a read file size at the time of this
if (iLayoutLoopMax == 0)
{
// Set the conditions that must always so th
at the next is executed
iLoopMax = i + 1;
}

ListDataFinal.Add(ListData);
ListData = new List<KeyValuePair<int, string>>()
;
} while (i < iLoopMax);
if (mResultFixedConvert == ResultFixedConvert.Succes
s)
{
// When the record information table reaches the
end, and since repeated from the beginning, and initializes the counter
if (RecordCount == RecordMax - 1)
{
RecordCount = -1;
// Since the position
is incremented by one in a loop back to the original "-1".
}
}
else
{
break;
}
}
}
break;
case MappingRecordDistinction.Value:
//Loop until a fixed-length file is lost
while (fsFixed.Position < fsFixed.Length)
{
// It is the last to reach the file, the last 1 byte to
determine whether 0x1A
if (fsFixed.Position == fsFixed.Length - 1)
{
long lStackPosition = fsFixed.Position; // To save
the current file pointer
ReadFixedFileByByte(1);
fsFixed.Position = lStackPosition;
// Back bec
ause read
if (byFixedRecordBuf[0] == '\x1A')
{
break; // Force escape
}
}
// Determine the current position of the fixed length fi
le belongs to which record
int iTargetID = mf_RecordDistinction(); // Determines t
he record division value, and returns the ID if it is applicable
if (iTargetID > 0)
{
// The results of the judgment record, if the record
is found
lReadByte += FixedRecord2DataSet(iTargetID);
// An error occurred during the record process
if (mResultFixedConvert != ResultFixedConvert.Succes
s)
{
// Forced termination
break;
}
else

// If read byte Success, add all data 1 record t


o ListDataFinal and reset ListData
ListDataFinal.Add(ListData);
ListData = new List<KeyValuePair<int, string>>()
;
}
}
else
{
// If error
if (mResultFixedConvert == ResultFixedConvert.ErrRec
ordDistinction)
// If the classification value collation error has occur
red
{
// Check (Unknown Record Skip) from data
bool UnknownRecordSkip = false;
if (Util.HasKey(IDataStore.Properties.Fixed, "
{
UnknownRecordSkip = Util.ToBool(IDataStore.P
roperties.Fixed.);
}

int SkipSize = 0;
if (Util.HasKey(IDataStore.Properties.Fixed, "
{
SkipSize = Util.ToInt(IDataStore.Properties.F
}
if (UnknownRecordSkip == true) // If the skip i
s specified
{
if (SkipSize != 0)
{
fsFixed.Seek(SkipSize, SeekOrigin.Curren
t);
m_iConvertRecordNo++;
m_lConvertByte += SkipSize;
// Keep initialize the error code
mResultFixedConvert = ResultFixedConvert
.Success;
}
else
{
// If skip size is 0, the forced termina
tion
_report.Add("Skip size is set to 0. Plea
se specify a value greater than or equal to 0.");
mResultFixedConvert = ResultFixedConvert
.ErrSkipSizeZero;
break;
}
}
else
{
// The collation error, and if there is no s
kip specified, the forced termination
break;
}

}
else
{
// If non-matching error, exit without doing any
thing
break;
}
}
}
break;
}
// Processing end if already contains the error status
return lReadByte;
}
/// <summary>
/// Incorporate the subordinate record to DataSet
/// </summary>
/// <param name="iID">ID of the record</param>
/// <returns></returns>
private long FixedRecord2DataSet(int iID)
{
DataStoreItem mLayout = _baton.InputDataStore.GetItem(iID);
long lReadByte = 0;
// Processing end if if already contains the error status
if (mResultFixedConvert != ResultFixedConvert.Success)
{
return lReadByte;
}
// Create a counter information for creating an error message when a
n error occurs
m_iConvertRecordNo++;
// Increments the record counter of
fixed length
m_iConvertItemNo = 0;
// Initialization of item

//_baton.Report.Add(string.Format("Record number [{0}] is processing


.", m_iConvertRecordNo));
List<DataStoreItem> drs = _baton.InputDataStore.GetChildItems(iID);
ListData.Add(new KeyValuePair<int, string>(iID, mLayout.Properties.Fixed
// I handle all the elements of the child
foreach (DataStoreItem dr in drs)
{
int iTargetID = dr.Id;
switch (dr.ItemType)
{
case MappingLayoutType.ItemGroup:
// If the item group
lReadByte += FixedItemGroup2DataSet(iTargetID);
break;
case MappingLayoutType.Item:
// In the case of items
lReadByte += FixedItem2DataSet(iTargetID);
break;
}
}

// If the operation has been completed successfully


if (mResultFixedConvert == ResultFixedConvert.Success)
{
// If the record separator is present, I leave in addition to it
s minute size processing
MappingFixedRecordSplit recordSeparatorFlag = MappingFixedRecord
Split.None;
if (Util.HasKey(_baton.InputDataStore.GetItemByType(MappingLayou
tType.DataStore).Properties.Fixed, ""))
recordSeparatorFlag = (MappingFixedRecordSplit)Util.ToInt(_b
aton.InputDataStore.GetItemByType(MappingLayoutType.DataStore).Properties.Fixed.
switch (recordSeparatorFlag)
{
case MappingFixedRecordSplit.None:
break;
case MappingFixedRecordSplit.Any:
long lSeekSize = 0;
if (Util.HasKey(_baton.InputDataStore.GetItemByType(Mapp
ingLayoutType.DataStore).Properties.Fixed., "Length"))
lSeekSize = Util.ToInt(_baton.InputDataStore.GetItem
ByType(MappingLayoutType.DataStore).Properties.Fixed..Len
lReadByte += lSeekSize;
m_lConvertByte += lSeekSize;
break;
case MappingFixedRecordSplit.CR:
lReadByte += 1;
m_lConvertByte += 1;
break;
case MappingFixedRecordSplit.LF:
lReadByte += 1;
m_lConvertByte += 1;
break;
case MappingFixedRecordSplit.CRLF:
lReadByte += 2;
m_lConvertByte += 2;
break;
}
}
return lReadByte;
}
/// <summary>
/// Take in the item group to DataSet
/// </summary>
/// <param name="iID">ID</param>
/// <returns>Returns the length that has been read</returns>
private long FixedItemGroup2DataSet(int iID)
{
if (mResultFixedConvert != ResultFixedConvert.Success)
{
return 0;
}
// Create a counter information for creating an error message when a
n error occurs
m_iConvertItemGroupNo++;
// Increment item group counter
m_iConvertItemNo = 0;
// Initialization of item
DataStoreItem mLayout = _baton.InputDataStore.GetItem(iID);

int iLoopMax = 0;
ListData.Add(new KeyValuePair<int, string>(iID, mLayout.Properties..

if (Util.HasKey(mLayout.Properties., ""))
{
iLoopMax = Util.ToInt(mLayout.Properties..
}
long lReadByte = 0;
// If the item group, I repeat the number of times specified
for (int i = 0; i < iLoopMax; i++)
{
List<DataStoreItem> drs = _baton.InputDataStore.GetChildItems(iI
D);
foreach (DataStoreItem dr in drs)
{
int iTargetID = dr.Id;
switch (dr.ItemType)
{
case MappingLayoutType.ItemGroup:

// If the item grou

p
lReadByte += FixedItemGroup2DataSet(iTargetID);
break;
case MappingLayoutType.Item:
// In the case of i
tems
lReadByte += FixedItem2DataSet(iTargetID);
break;
}
}
}
return lReadByte;
}
/// <summary>
/// Fixed item to dataset
/// </summary>
/// <param name="iID">ID of the item</param>
/// <returns>Returns the read size</returns>
private long FixedItem2DataSet(int iID)
{
DataStoreItem store = _baton.InputDataStore.GetItemByType(MappingLay
outType.DataStore, 0); // get DataStore Fixed
DataStoreItem mItemLayout = _baton.InputDataStore.GetItem(iID);
long lReadByte = 0;
string strValue = "";
// Processing end if if already contains the error status
if (mResultFixedConvert != ResultFixedConvert.Success)
{
return lReadByte;
}
// Creating a counter information for creating an error message when
an error occurs
m_iConvertItemNo++;
// Increment of item counter
DataStoreItem parentItem = _baton.InputDataStore.GetItem(mItemLayout

.ParentId);
string strItemName = mItemLayout.LocalName; // Get the item name
// Extract only the specified size from the record array
int numberOfDigits = 0;
if (Util.HasKey(mItemLayout.Properties.Fixed, ""))
numberOfDigits = Util.ToInt(mItemLayout.Properties.Fixed.);
byte[] byBuf = new byte[numberOfDigits];
Buffer.BlockCopy(byFixedRecordBuf, iFixedRecordBufCounter, byBuf, 0,
numberOfDigits);
iFixedRecordBufCounter += numberOfDigits;
// Adding the read size
lReadByte += numberOfDigits;
// Read the contents the character conversion (If the return value i
s non-zero, are riding an error of character conversion module)
// Check data layout for convert
#region check data for Convert a string to the byte array

int ItemCount = Util.ToInt(mItemLayout.Properties.Fixed.);


DataEncoding de = (DataEncoding)Util.ToInt(mItemLayout.Properties.Fixe
d.);
MappingSISO mSISO = (MappingSISO)Util.ToInt(mItemLayout.Properties.Fix
ed.SISO);
MappingEBCDICType mEBCIDICType = (MappingEBCDICType)Util.ToInt(mItem
Layout.Properties.Fixed.EBCDIC);
MappingJEF_KEIS_Type JEF_KEIS_Type = (MappingJEF_KEIS_Type)Util.ToIn
t(mItemLayout.Properties.Fixed.JEF_KEIS);
MappingConvertError ConvertError = (MappingConvertError)Util.ToInt(m
ItemLayout.Properties.Fixed.);
string strErrorCode = mItemLayout.Properties.Fixed.;
Attributes mCharAttribute = (Attributes)Util.ToInt(mItemLayout.Prope
rties..);
Padding mPadding = (Padding)Util.ToInt(mItemLayout.Properties.Fixed.
Position mPosition = (Position)Util.ToInt(mItemLayout.Properties.Fixed
.);
bool bGaijiConvert = Util.ToBool(mItemLayout.Properties.Fixed.);
MappingZeroOut mZeroOut = (MappingZeroOut)Util.ToInt(store.Propertie
s.Fixed.);
MappingDecimalZeroFormat mDecimalZeroFormat = (MappingDecimalZeroFor
mat)Util.ToInt(store.Properties.Fixed.);
int iDecimalCount = Util.ToInt(mItemLayout.Properties.Fixed.);
#endregion
// Initialize encoding
initializeEdiEncoding(de, mSISO, true, mEBCIDICType, JEF_KEIS_Type,
ConvertError, strErrorCode, bGaijiConvert);
long lRet = -1;
// Convert byte array to string
lRet = ConvertByteArray2String(
byBuf,
out strValue,
ItemCount,
mCharAttribute,
mPadding,

mPosition,
mZeroOut,
mDecimalZeroFormat,
iDecimalCount);
// If conversion result is failed
if (mResultFixedConvert != ResultFixedConvert.Success)
{
_baton.Report.Add(string.Format("Record number [{0}] Item Group
[] item [{1} th: {2}] in failure.", m_iConvertRecordNo, m_iConvertItemNo, strIte
mName));
if (mResultFixedConvert == ResultFixedConvert.ErrStringConvert)
{
// If the character code conversion error
string strConvErrMsglRet = EdiEncoding.GetReurnCodeMsg(lRet)
;
_baton.Report.Add(string.Format("Error code [{0] character c
onversion result [{1}]", (int)mResultFixedConvert, strConvErrMsglRet));
}
else
{
_baton.Report.Add(string.Format("Error code [{0}]", (int)mRes
ultFixedConvert));
}
_baton.Report.Add(string.Format("Contents byte representation of
the object [{0}]", BitConverter.ToString(byBuf)));
return 0;
}
m_lConvertByte += numberOfDigits;
ListData.Add(new KeyValuePair<int, string>(iID, strValue));
return lReadByte;
}
#endregion
#region Get value from KeyValuePair
/// <summary>
/// return value from key in KeyValuePair htRecord
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private int ValueFromKey(int key)
{
int ret = 0;
foreach (KeyValuePair<int, int> kvp in htRecord)
{
if (kvp.Key == key)
{
ret = kvp.Value;
break;
}
}
return ret;
}
/// <summary>

/// return value from key in KeyValuePair ListData


/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private string ListDataValueFromKey(int key)
{
string ret = "";
foreach (KeyValuePair<int, string> kvp in ListData)
{
if (kvp.Key == key)
{
ret = kvp.Value;
break;
}
}
return ret;
}
private string ListDataValueFromKey(int key, List<KeyValuePair<int, stri
ng>> ListData)
{
string ret = "";
foreach (KeyValuePair<int, string> kvp in ListData)
{
if (kvp.Key == key)
{
ret = kvp.Value;
break;
}
}
return ret;
}
#endregion
}
public class FixedInputConverter : MultiThreadConverter
{
public FixedInputConverter(int id, object data, IDataStoreFactory source
Layout, IDataStoreFactory targetLayout,
IMappingLogic logics, AppParams parms, Writer report)
: base(id, data, sourceLayout, targetLayout, logics, parms, report)
{ }
public override void Convert()
{
int id = base.Id;
List<List<KeyValuePair<int, string>>> data = (List<List<KeyValuePair
<int, string>>>)base.Data;
IDataStoreFactory dsSource = base.InputDataStore;
List<DataStoreItem> dsItems = dsSource.GetDataStore().Items;
// Buffer to hold first tree nodes
List<XElement> threadBuffer = new List<XElement>();
List<DataStoreItem> layout = dsSource.GetDataStore().Items;
DataStoreItem mItem = dsSource.GetItem(data[0][1].Key);

XElement XnodeItemGroup = null;


int iItemGrID = -1;
if (mItem.ItemType == MappingLayoutType.ItemGroup)
{
iItemGrID = mItem.Id;
string itemGroupName = Util.CreateNodeName(dsSource.GetItem(iIte
mGrID).ItemType, iItemGrID);
XnodeItemGroup = new XElement(itemGroupName);
}
foreach (List<KeyValuePair<int, string>> record in data)
{
int iRecordID = 0;
List<DataStoreItem> listRecordsLayout = new List<DataStoreItem>(
); // List Records in Fixed layout file
listRecordsLayout = dsSource.GetRecords();

foreach (DataStoreItem item in listRecordsLayout)


{
if (Util.HasKey(item.Properties, "Fixed"))
{
if (item.Properties.Fixed. == record[0].V
iRecordID = item.Id;
} else
if (Util.HasKey(item.Properties, "Fixed"))
if (item.Properties.Fixed. == record[0].Value)
iRecordID = item.Id;
}
string RecordName = Util.CreateNodeName(dsSource.GetItem(iRecord
ID).ItemType, iRecordID);
XElement Xrecord = new XElement(RecordName);
// Get list Items
var ListItems = from p in layout
where p.ParentId == iRecordID
select p;
if (iItemGrID != -1)
{
List<DataStoreItem> rChilds = dsSource.GetChildItems(iItemGr
ID);
foreach (DataStoreItem item in ListItems)
{
rChilds.Add(item);
}
ListItems = rChilds;
}
foreach (DataStoreItem item in ListItems)
{
string ItemName = Util.CreateNodeName(item.ItemType, item.Id
);
if (item.ItemType == MappingLayoutType.ItemGroup)
{
//XElement IItem = new XElement(ItemName);
//XnodeItemGroup.Add(IItem);
}
else if (item.ItemType == MappingLayoutType.Item)
{
// Add value
XElement IItem = new XElement(ItemName, ListDataValueFro

mKey(item.Id, record));
if (item.ParentId == iItemGrID)
{
XnodeItemGroup.Add(IItem);
}
else
{
Xrecord.Add(IItem);
}
}
}
// Append new record node to buffer
if (XnodeItemGroup != null) Xrecord.Add(XnodeItemGroup);
if (Xrecord != null) threadBuffer.Add(Xrecord);
}
// Update buffer
base.Buffer = threadBuffer.Cast<object>().ToList();
}
/// <summary>
/// Get value from key in KeyValuePair ListData
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private string ListDataValueFromKey(int key, List<KeyValuePair<int, stri
ng>> ListData)
{
string ret = "";
foreach (KeyValuePair<int, string> kvp in ListData)
{
if (kvp.Key == key)
{
ret = kvp.Value;
break;
}
}
return ret;
}
}
}