/// <summary> /// Writes a record using the specified record format. /// </summary> /// <param name="recordKey">the key corresponding to the record format</param> /// <param name="fields">the list of field values to encode</param> /// <exception cref="IOException"> if there are issues writing the data</exception> /// <exception cref="EbcdicException"> if field values do not conform to the copybook</exception> public void WriteRecord(string recordKey, List <object> fields) { RecordFormat format = RecordFormatMap.GetFromId(recordKey); WriteRdw(fields, format); WriteFields(fields, format); }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected: //ORIGINAL LINE: private org.neo4j.io.pagecache.randomharness.Phase filesAreCorrectlyWrittenVerification(final org.neo4j.io.pagecache.randomharness.RecordFormat recordFormat, final int filePageCount) private Phase FilesAreCorrectlyWrittenVerification(RecordFormat recordFormat, int filePageCount) { return((cache, fs1, filesTouched) => { foreach (File file in filesTouched) { using (PagedFile pf = cache.map(file, cache.pageSize()), PageCursor cursor = pf.Io(0, PF_SHARED_READ_LOCK)) { for (int pageId = 0; pageId < filePageCount && cursor.Next(); pageId++) { try { recordFormat.AssertRecordsWrittenCorrectly(cursor); } catch (Exception th) { th.addSuppressed(new Exception("pageId = " + pageId)); throw th; } } } using (StoreChannel channel = fs1.open(file, OpenMode.READ)) { recordFormat.AssertRecordsWrittenCorrectly(file, channel); } } }); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void verifyWriteAndRead(System.Func<RecordFormat<R>> formatSupplier, System.Func<org.neo4j.kernel.impl.store.format.RecordGenerators_Generator<R>> generatorSupplier, System.Func<RecordKey<R>> keySupplier, boolean assertPostReadOffset) throws java.io.IOException private void VerifyWriteAndRead <R>(System.Func <RecordFormat <R> > formatSupplier, System.Func <RecordGenerators_Generator <R> > generatorSupplier, System.Func <RecordKey <R> > keySupplier, bool assertPostReadOffset) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { // GIVEN using (PagedFile storeFile = _pageCache.map(new File("store-" + Name.MethodName), _pageSize, CREATE)) { RecordFormat <R> format = formatSupplier(); RecordKey <R> key = keySupplier(); RecordGenerators_Generator <R> generator = generatorSupplier(); int recordSize = format.GetRecordSize(new IntStoreHeader(DATA_SIZE)); BatchingIdSequence idSequence = new BatchingIdSequence(_random.nextBoolean() ? IdSureToBeOnTheNextPage(_pageSize, recordSize) : 10); // WHEN long time = currentTimeMillis(); long endTime = time + TEST_TIME; long i = 0; for ( ; i < TEST_ITERATIONS && currentTimeMillis() < endTime; i++) { R written = generator.Get(recordSize, format, i % 5); R read = format.NewRecord(); try { WriteRecord(written, format, storeFile, recordSize, idSequence); ReadAndVerifyRecord(written, read, format, key, storeFile, recordSize, assertPostReadOffset); idSequence.Reset(); } catch (Exception t) { Exceptions.setMessage(t, t.Message + " : written:" + written + ", read:" + read + ", seed:" + _random.seed() + ", iteration:" + i); throw t; } } } }
static DriverConstants() { ProtocolVersion = 36; DriverName = "OrientDB-NET.binary"; DriverVersion = "0.2.2"; ClientID = "null"; RecordFormat = RecordFormat.ORecordDocument2csv; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReport3BytesMaxIdForRelationshipTypes() public virtual void ShouldReport3BytesMaxIdForRelationshipTypes() { // given RecordFormat <RelationshipTypeTokenRecord> format = HighLimit.RecordFormats.relationshipTypeToken(); // when long maxId = format.MaxId; // then assertEquals((1 << HighLimitFormatSettings.RelationshipTypeTokenMaximumIdBits) - 1, maxId); }
private void MakeSureMagicMinusOneIsSkipped(RecordFormat format) { DeleteIdGeneratorFile(); IdGeneratorImpl.createGenerator(_fs, IdGeneratorFile(), 0, false); IdGenerator idGenerator = new IdGeneratorImpl(_fs, IdGeneratorFile(), 1, format.MaxId, false, IdType.NODE, () => 0L); long id = ( long )Math.Pow(2, 32) - 3; idGenerator.HighId = id; assertEquals(id, idGenerator.NextId()); assertEquals(id + 1, idGenerator.NextId()); // Here we make sure that id+2 (integer -1) is skipped assertEquals(id + 3, idGenerator.NextId()); assertEquals(id + 4, idGenerator.NextId()); assertEquals(id + 5, idGenerator.NextId()); CloseIdGenerator(idGenerator); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void writeRecord(R record, RecordFormat<R> format, org.neo4j.io.pagecache.PagedFile storeFile, int recordSize, org.neo4j.kernel.impl.store.id.BatchingIdSequence idSequence) throws java.io.IOException private void WriteRecord <R>(R record, RecordFormat <R> format, PagedFile storeFile, int recordSize, BatchingIdSequence idSequence) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { using (PageCursor cursor = storeFile.Io(0, Org.Neo4j.Io.pagecache.PagedFile_Fields.PfSharedWriteLock)) { AssertedNext(cursor); if (record.inUse()) { format.Prepare(record, recordSize, idSequence); } int offset = Math.toIntExact(record.Id * recordSize); cursor.Offset = offset; format.Write(record, cursor, recordSize); AssertWithinBounds(record, cursor, "writing"); } }
public override int GetHashCode() { unchecked { var hashCode = TrackName != null?TrackName.GetHashCode() : 0; hashCode = (hashCode * 397) ^ Duration; hashCode = (hashCode * 397) ^ Bitrate; hashCode = (hashCode * 397) ^ (TrackUrl != null ? TrackUrl.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Group != null ? Group.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Year; hashCode = (hashCode * 397) ^ (RecordFormat != null ? RecordFormat.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Album != null ? Album.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Size; hashCode = (hashCode * 397) ^ (Genre != null ? Genre.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Rate; return(hashCode); } }
private void MakeSureIdCapacityCannotBeExceeded(RecordFormat format) { DeleteIdGeneratorFile(); IdGeneratorImpl.createGenerator(_fs, IdGeneratorFile(), 0, false); long maxValue = format.MaxId; IdGenerator idGenerator = new IdGeneratorImpl(_fs, IdGeneratorFile(), 1, maxValue - 1, false, IdType.NODE, () => 0L); long id = maxValue - 2; idGenerator.HighId = id; assertEquals(id, idGenerator.NextId()); assertEquals(id + 1, idGenerator.NextId()); try { idGenerator.NextId(); fail("Id capacity shouldn't be able to be exceeded for " + format); } catch (StoreFailureException) { // Good } CloseIdGenerator(idGenerator); }
public IEnumerable <FilteredKeyword> ReadTerms(string filePath, RecordFormat recordFormat) { if (File.Exists(filePath)) { using (var sr = File.OpenText(filePath)) { switch (recordFormat) { case RecordFormat.TermOnly: return(ReadTermsOnly(sr)); case RecordFormat.CategorizedTerm: return(ReadCategorizedTerms(sr)); case RecordFormat.Tsv: return(ReadTsvTerms(sr)); } } } return(new List <FilteredKeyword>()); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void readAndVerifyRecord(R written, R read, RecordFormat<R> format, RecordKey<R> key, org.neo4j.io.pagecache.PagedFile storeFile, int recordSize, boolean assertPostReadOffset) throws java.io.IOException private void ReadAndVerifyRecord <R>(R written, R read, RecordFormat <R> format, RecordKey <R> key, PagedFile storeFile, int recordSize, bool assertPostReadOffset) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { using (PageCursor cursor = storeFile.Io(0, Org.Neo4j.Io.pagecache.PagedFile_Fields.PF_SHARED_READ_LOCK)) { AssertedNext(cursor); read.Id = written.Id; /* * Retry loop is needed here because format does not handle retries on the primary cursor. * Same retry is done on the store level in {@link org.neo4j.kernel.impl.store.CommonAbstractStore} */ int offset = Math.toIntExact(written.Id * recordSize); do { cursor.Offset = offset; format.Read(read, cursor, NORMAL, recordSize); } while (cursor.ShouldRetry()); AssertWithinBounds(written, cursor, "reading"); if (assertPostReadOffset) { assertEquals("Cursor is positioned on first byte of next record after a read", offset + recordSize, cursor.Offset); } cursor.CheckAndClearCursorException(); // THEN if (written.inUse()) { assertEquals(written.inUse(), read.inUse()); assertEquals(written.Id, read.Id); assertEquals(written.SecondaryUnitId, read.SecondaryUnitId); key.AssertRecordsEquals(written, read); } else { assertEquals(written.inUse(), read.inUse()); } } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHandleRelationshipTypesBeyond2Bytes() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHandleRelationshipTypesBeyond2Bytes() { // given RecordFormat <RelationshipTypeTokenRecord> format = HighLimit.RecordFormats.relationshipTypeToken(); int typeId = 1 << ((sizeof(short) * 8) + (sizeof(sbyte) * 8)) - 1; RelationshipTypeTokenRecord record = new RelationshipTypeTokenRecord(typeId); int recordSize = format.GetRecordSize(NO_STORE_HEADER); record.Initialize(true, 10); IdSequence doubleUnits = mock(typeof(IdSequence)); PageCursor cursor = new StubPageCursor(0, ( int )kibiBytes(8)); // when format.Prepare(record, recordSize, doubleUnits); format.Write(record, cursor, recordSize); verifyNoMoreInteractions(doubleUnits); // then RelationshipTypeTokenRecord read = new RelationshipTypeTokenRecord(typeId); format.Read(record, cursor, NORMAL, recordSize); assertEquals(record, read); }
/// <summary> /// Initializes a new instance of the <see cref="ParameterSendRecordFormat"/> class. /// </summary> /// <param name="recordFormat">Record format.</param> public ParameterSendRecordFormat(RecordFormat recordFormat) { this.Type = ParameterType.SendRecordFormat; this.RecordFormat = recordFormat; }
internal PrepareTrackingRecordFormat(PrepareTrackingRecordFormats outerInstance, RecordFormat <RECORD> actual, ISet <RECORD> prepare) { this._outerInstance = outerInstance; this.Actual = actual; this.PrepareConflict = prepare; }
internal TheStore(File file, File idFile, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, RecordFormat <TheRecord> recordFormat, params OpenOption[] openOptions) : base(file, idFile, configuration, idType, idGeneratorFactory, pageCache, logProvider, "TheType", recordFormat, NoStoreHeaderFormat.NoStoreHeaderFormatConflict, "v1", openOptions) { }
public Record GetItemById(string id, RecordFormat format) { return(_mapper.Map <RecordWithInverses>(_store.GetRecord(_store.CodeEntity(id)), options => options.Items["Format"] = format)); }
public TokenStore(File file, File idFile, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, DynamicStringStore nameStore, string typeDescriptor, RecordFormat <RECORD> recordFormat, string storeVersion, params OpenOption[] openOptions) : base(file, idFile, configuration, idType, idGeneratorFactory, pageCache, logProvider, typeDescriptor, recordFormat, NO_STORE_HEADER_FORMAT, storeVersion, openOptions) { this._nameStore = nameStore; }
internal DynamicStoreHeaderFormat(int dataSizeFromConfiguration, RecordFormat <DynamicRecord> recordFormat) : base(dataSizeFromConfiguration + recordFormat.RecordHeaderSize) { }
static void Main(string[] args) { var parametersValidator = new ParametersValidator(); var parametersAreValid = parametersValidator.Validate(args); if (parametersAreValid) { string nameOfFile; string numberOfLines; string numberOfUniqueIp; var parametersDictionary = CommandLineParser.Parse(args); if (parametersDictionary.TryGetValue("nameoffile", out nameOfFile) && parametersDictionary.TryGetValue("numberoflines", out numberOfLines) && parametersDictionary.TryGetValue("numberofuniqueip", out numberOfUniqueIp)) { var uniqueIpCount = Convert.ToInt32(numberOfUniqueIp); var linesLength = Convert.ToInt32(numberOfLines); var configFileReader = new Settings.ConfigFileReader(@"D:\Univercity\Univercity\3курс-лабы\config.yaml"); string[] methods = { "POST", "LINK", "DELETE", "PUT", "PATCH", "GET", "OPTIONS", "HEAD", "TRACE", "UNLINK", "CONNECT" }; string[] extensions = { "txt", "pdf", "doc", "exe", "jmp", "cpp", "obj", "iso" }; string[] protocols = { "http", "https" }; string[] serverResponseCodes = { "200", "401", "204", "404", "501" }; const int minIntervalInMilliseconds = 100; const int maxIntervalInMilliseconds = 100000; const int minNumberOfFolders = 3; const int maxNumberOfFolders = 7; const int minNumberOfCharacters = 3; const int maxNumberOfCharacters = 7; const int minSizeOfResponse = 100; const int maxSizeOfResponse = 10000; var recordFormat = new RecordFormat { IpIsPresent = true, QueryTimeIsPresent = true, QueryMethodIsPresent = true, FileNameIsPresent = true, ExtensionIsPresent = true, ProtocolIsPresent = true, ServerResponseCodeIsPresent = true, SizeOfTheResponseIsPresent = true }; var generator = new Generator { Extensions = extensions, Protocols = protocols, Methods = methods, Settings = configFileReader.Settings, ServerResponseCodes = serverResponseCodes, MinIntervalInMilliseconds = minIntervalInMilliseconds, MaxIntervalInMilliseconds = maxIntervalInMilliseconds, MinNumberOfCharacters = minNumberOfCharacters, MaxNumberOfCharacters = maxNumberOfCharacters, MinNumberOfFolders = minNumberOfFolders, MaxNumberOfFolders = maxNumberOfFolders, MinSizeOfResponse = minSizeOfResponse, MaxSizeOfResponse = maxSizeOfResponse, NumberOfUniqueIp = uniqueIpCount }; var allRecords = generator.GenerateRecords(linesLength); var rows = ApacheLogFormat.RecordsToString(allRecords, recordFormat); SaveToFile.SaveRowsToFile(nameOfFile, rows); Console.WriteLine("Save succesed!"); } else { Console.WriteLine("Входные параметры не соответствуют шаблону."); } } else { Console.WriteLine(parametersValidator.ValidationInformation); } Console.ReadKey(); }
public AbstractDynamicStore(File file, File idFile, Config conf, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, string typeDescriptor, int dataSizeFromConfiguration, RecordFormat <DynamicRecord> recordFormat, string storeVersion, params OpenOption[] openOptions) : base(file, idFile, conf, idType, idGeneratorFactory, pageCache, logProvider, typeDescriptor, recordFormat, new DynamicStoreHeaderFormat(dataSizeFromConfiguration, recordFormat), storeVersion, openOptions) { }
public DynamicStringStore(File file, File idFile, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, int dataSizeFromConfiguration, RecordFormat <DynamicRecord> recordFormat, string storeVersion, params OpenOption[] openOptions) : base(file, idFile, configuration, idType, idGeneratorFactory, pageCache, logProvider, TYPE_DESCRIPTOR, dataSizeFromConfiguration, recordFormat, storeVersion, openOptions) { }
public ConvertingProcess(RecordFormat from, RecordFormat to) { fromFormat = from; toFormat = to; }
public Record GetItemById(string id, [FromBody] RecordFormat format) { return(_service.GetItemById(id, format)); }
public RelationshipGroupRecordFormatTest(RecordFormats formats) { this._format = formats.RelationshipGroup(); this._recordSize = _format.getRecordSize(NO_STORE_HEADER); }
private static RecordFormat <R> WithForcedSecondaryUnit <R>(RecordFormat <R> format) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { return(new ForcedSecondaryUnitRecordFormat <R>(format)); }
public ForcedSecondaryUnitRecordFormat(RecordFormat <RECORD> actual) { this._actual = actual; }
/// <summary> /// Generate /// </summary> /// <param name="fileFormatSpecificationFilename"></param> /// <returns></returns> public static string Generate(string fileFormatSpecificationFilename) { var recordFormatList = new List <RecordFormat>(); string[] linesArrayNotTrimmed = File.ReadAllLines(fileFormatSpecificationFilename); string section = string.Empty; bool parseRecordFormat = false; string tableHeader = string.Empty; string className = string.Empty; string finalClassName = string.Empty; int lineNumber = -1; foreach (string columnFormatLine in linesArrayNotTrimmed) { lineNumber++; string lineTrimmed = columnFormatLine.Trim(); string[] split = columnFormatLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length <= 0) { continue; } if (split[split.Length - 1] == "Section") { section = columnFormatLine; } if (lineTrimmed == "Record Format") { parseRecordFormat = false; } else if (lineTrimmed == "Details") { parseRecordFormat = false; } else if (lineTrimmed == "Example") { parseRecordFormat = false; } else if (lineTrimmed == "Verification/Validation/Value Authority Control") { parseRecordFormat = false; } else if (lineTrimmed == "Relationships to Other Record Types") { parseRecordFormat = false; } if (columnFormatLine.Replace(" ", string.Empty) == "COLUMNS" + "DataType" + "FIELD" + "DEFINITION") { tableHeader = linesArrayNotTrimmed[lineNumber]; parseRecordFormat = true; if (className != string.Empty && finalClassName != string.Empty) { // Change className to finalClassName. foreach (RecordFormat recordFormat2 in recordFormatList) { if (className != null && recordFormat2.ClassName == className && className.Length > 0) { recordFormat2.ClassName = finalClassName; } if (className != null && recordFormat2.FieldValue == className && className.Length > 0) { recordFormat2.FieldValue = finalClassName; } } className = string.Empty; finalClassName = string.Empty; } } if (parseRecordFormat) { // Find if the first index of a non-space is a definition. int nonspace; for (nonspace = 0; nonspace < linesArrayNotTrimmed[lineNumber].Length; nonspace++) { if (linesArrayNotTrimmed[lineNumber][nonspace] != ' ') { break; } } if (nonspace == tableHeader.IndexOf("DEFINITION")) { RecordFormat definitionRecord = recordFormatList[recordFormatList.Count - 1]; definitionRecord.Definition = definitionRecord.Definition.Trim() + " " + columnFormatLine.Trim(); } var recordFormat = new RecordFormat(); int fieldFirstColumn = -1; int fieldLastColumn = -1; fieldFirstColumn = tableHeader.IndexOf("COLUMNS") + 1; fieldLastColumn = fieldFirstColumn + 2; string FirstColumnString = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; fieldFirstColumn = fieldLastColumn + 1; fieldLastColumn = fieldFirstColumn; string columnSplitter = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; fieldFirstColumn = fieldLastColumn + 1; fieldLastColumn = fieldFirstColumn + 2; string LastColumnString = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; bool columnsFound = false; int x; if (int.TryParse(FirstColumnString, out x)) { recordFormat.FirstColumn = x; int t; if (!int.TryParse(columnSplitter, out t)) { columnsFound = true; } } int y; if (!int.TryParse(LastColumnString, out y)) { recordFormat.LastColumn = recordFormat.FirstColumn; } else { recordFormat.LastColumn = y; } if (columnsFound) { // first column 1..3 // second column 5..7 // data type 15..28 // field name 29..47 // definition 48..end int DataTypeStart = tableHeader.IndexOf("DATA") + 1; fieldFirstColumn = tableHeader.IndexOf("DATA") + 1; fieldLastColumn = tableHeader.IndexOf("FIELD"); recordFormat.DataType = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; fieldFirstColumn = tableHeader.IndexOf("FIELD") + 1; fieldLastColumn = AreQuotesOpenAt(columnFormatLine, tableHeader.IndexOf("DEFINITION") - 1) ? columnFormatLine.IndexOf('"', fieldFirstColumn) : tableHeader.IndexOf("DEFINITION"); recordFormat.FieldValue = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; string FieldValueNotChanged = recordFormat.FieldValue; CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; string testname = recordFormat.FieldValue.Trim(); if (testname.Length > 0 && testname[0] == '"') { bool q = false; for (int i = 0; i < testname.Length; i++) { if (testname[i] == '"') { q = !q; finalClassName += "_"; } else { finalClassName += (string.Empty + testname[i]).Replace(" ", string.Empty).Replace("[", "_").Replace("]", "_").Replace("{", "_").Replace("}", "_").Replace(".", "_").Replace("__", "_").Replace("__", "_"); } } finalClassName = finalClassName.Trim(new[] { '_', ' ', '.', ',' }); } recordFormat.FieldValue = recordFormat.FieldValue.Replace("\"", string.Empty); recordFormat.FieldValue = recordFormat.FieldValue.Replace(" ", "_"); recordFormat.FieldValue = recordFormat.FieldValue.Replace("__", "_"); recordFormat.FieldValue = recordFormat.FieldValue.Replace("__", "_"); recordFormat.FieldValue = recordFormat.FieldValue.Trim(new[] { '_' }); int t; if (int.TryParse(recordFormat.FieldValue.Substring(0, 1), out t)) { recordFormat.FieldValue = "_" + recordFormat.FieldValue; } fieldFirstColumn = tableHeader.IndexOf("DEFINITION") + 1; fieldLastColumn = columnFormatLine.Length; recordFormat.Definition = (fieldFirstColumn > 0 && fieldLastColumn > 0 && columnFormatLine.Length >= fieldFirstColumn) ? columnFormatLine.Substring(fieldFirstColumn - 1, (columnFormatLine.Length >= fieldLastColumn ? ((fieldLastColumn - fieldFirstColumn) + 1) : columnFormatLine.Length - (fieldFirstColumn - 1))).Trim() : string.Empty; recordFormat.Definition = recordFormat.Definition.Replace("\"", string.Empty); if (recordFormat.DataType == "Record name") { className = recordFormat.FieldValue; int a = 1; bool found = true; string proposedName = string.Empty; while (found) { found = false; proposedName = className + (a > 1 ? string.Empty + a : string.Empty); foreach (RecordFormat recordFormat2 in recordFormatList) { if (recordFormat2.ClassName == proposedName) { a++; found = true; break; } } } className = proposedName; } recordFormat.ClassName = className; recordFormatList.Add(recordFormat); } } } // Make list of classes. var classList = new List <string>(); foreach (RecordFormat recordFormat in recordFormatList) { if (!classList.Contains(recordFormat.ClassName)) { classList.Add(recordFormat.ClassName); } } // Add additionaldata column. foreach (string name in classList) { int highestLastColumn = 1; foreach (RecordFormat recordFormat in recordFormatList) { if (recordFormat.ClassName == name) { if (recordFormat.LastColumn > highestLastColumn) { highestLastColumn = recordFormat.LastColumn; } } } var additionalDataRecordFormat = new RecordFormat(); additionalDataRecordFormat.ClassName = name; additionalDataRecordFormat.FieldValue = "additionalData"; additionalDataRecordFormat.FirstColumn = highestLastColumn + 1; additionalDataRecordFormat.LastColumn = -1; additionalDataRecordFormat.Definition = "Any data found which is additional to the fields listed in the specification"; recordFormatList.Add(additionalDataRecordFormat); } foreach (RecordFormat recordFormat in recordFormatList) { if (recordFormat.ClassName.Length > 1 && (string.Empty + recordFormat.ClassName[1]).IndexOfAny(new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) < 0) { recordFormat.ClassName = recordFormat.ClassName.Trim(new[] { '_' }); } if (recordFormat.FieldValue.Length > 1 && (string.Empty + recordFormat.FieldValue[1]).IndexOfAny(new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) < 0) { recordFormat.FieldValue = recordFormat.FieldValue.Trim(new[] { '_' }); } } // Ensure all field names are unique. foreach (string name in classList) { var FieldValueList = new List <string>(); var fieldsToRename = new List <string>(); foreach (RecordFormat recordFormat in recordFormatList) { if (recordFormat.ClassName.ToLowerInvariant() == name.ToLowerInvariant()) { if (!FieldValueList.Contains(recordFormat.FieldValue)) { FieldValueList.Add(recordFormat.FieldValue); } else { // Add it to be renamed. if (!fieldsToRename.Contains(recordFormat.FieldValue)) { fieldsToRename.Add(recordFormat.FieldValue); } } } } foreach (string FieldValue in fieldsToRename) { int i = 0; foreach (RecordFormat recordFormat in recordFormatList) { if (recordFormat.ClassName == name && recordFormat.FieldValue == FieldValue) { i++; if (i > 1) { recordFormat.FieldValue = recordFormat.FieldValue + i; } } } } } string mainClassCode = string.Empty; string cases = string.Empty; // Iterate through list adding each field's code. foreach (string name in classList) { int repeat = 1; if (name.Substring(name.Length - 1, 1) == "n") { repeat = 3; } for (int n = 1; n <= repeat; n++) { string childClassCode = string.Empty; string constructor = string.Empty; string tostring = string.Empty; string nameWithN = (name.Substring(name.Length - 1, 1) == "n") ? name.Substring(0, name.Length - 1) + n : name; tostring += "public override string ToString()" + Environment.NewLine; tostring += "{" + Environment.NewLine; tostring += "string columnDelimiter = \"\\t\";" + Environment.NewLine; tostring += "string result = \"\";" + Environment.NewLine; childClassCode += "public class " + nameWithN + "_Record : ProteinDataBankFileRecord" + Environment.NewLine; childClassCode += "{" + Environment.NewLine; constructor += "public " + nameWithN + "_Record( string columnFormatLine) : base( columnFormatLine)" + Environment.NewLine; constructor += "{" + Environment.NewLine; // Iterate through format records finding classname, adding format to class. foreach (RecordFormat recordFormat in recordFormatList) { if (recordFormat.ClassName == nameWithN || recordFormat.ClassName == name) { var recordFormatCopy = new RecordFormat(); recordFormatCopy.ClassName = recordFormat.ClassName; recordFormatCopy.FieldValue = recordFormat.FieldValue; recordFormatCopy.Definition = recordFormat.Definition; recordFormatCopy.DataType = recordFormat.DataType; recordFormatCopy.FirstColumn = recordFormat.FirstColumn; recordFormatCopy.LastColumn = recordFormat.LastColumn; recordFormatCopy.FieldValue = recordFormatCopy.FieldValue.Replace("[N]", "_" + n + "_").Replace("[n]", "_" + n + "_"); recordFormatCopy.FieldValue = recordFormatCopy.FieldValue.Replace("[", "_").Replace("]", "_"); recordFormatCopy.FieldValue = recordFormatCopy.FieldValue.Replace(".", "_"); if (recordFormat.ClassName.ToLowerInvariant() == recordFormat.FieldValue.ToLowerInvariant()) { recordFormatCopy.ClassName = recordFormatCopy.FieldValue; } if (name != nameWithN) { recordFormatCopy.ClassName = nameWithN; } if (recordFormat.ClassName.Substring(recordFormat.ClassName.Length - 1) == "n" && recordFormat.ClassName == recordFormat.FieldValue) { recordFormatCopy.FieldValue = recordFormatCopy.ClassName; } childClassCode += recordFormatCopy.ToString(1); constructor += recordFormatCopy.ToString(2); tostring += "result += " + recordFormatCopy.FieldValue + ".FieldValue + columnDelimiter;" + Environment.NewLine; if (recordFormatCopy.ClassName == recordFormatCopy.FieldValue || recordFormatCopy.ClassName.Substring(0, recordFormatCopy.ClassName.Length - 1) == recordFormatCopy.FieldValue.Substring(0, recordFormatCopy.FieldValue.Length - 1)) { if (recordFormatCopy.FieldValue.Substring(0, recordFormatCopy.FieldValue.Length - 1) == recordFormatCopy.FieldValue.Substring(0, recordFormatCopy.FieldValue.Length - 1).ToUpperInvariant()) { cases += "case \"" + recordFormatCopy.ClassName + "\":" + Environment.NewLine; cases += "result = new " + recordFormatCopy.ClassName + "_Record( columnFormatLine);" + Environment.NewLine; cases += "break;" + Environment.NewLine; } } } } tostring += "return result;" + Environment.NewLine; tostring += "}" + Environment.NewLine; constructor += "}" + Environment.NewLine; childClassCode += constructor + Environment.NewLine; childClassCode += tostring + Environment.NewLine; childClassCode += "}" + Environment.NewLine; mainClassCode += childClassCode + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine; } } mainClassCode = ProteinDataBankFileConstructors + ToStringMethod + ProteinDataBaseFileLineRecordMethod.Replace("%case statements%", cases) + PDBRecordTypeMethod + LoadFileMethod + UnloadFileMethod + CountMethod + NextRecordMethod + ProteinDataBankFileRecordFieldClass + ProteinDataBankFileRecordClass + mainClassCode; mainClassCode = MainNameSpaceAndClass.Replace("%data%", mainClassCode); while (mainClassCode.IndexOf("__") > -1) { mainClassCode = mainClassCode.Replace("__", "_"); } return(mainClassCode); }