2020-01-22 17:33:34 +00:00

518 lines
17 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
using VEPROMS.CSLA.Library;
using log4net;
using Volian.Controls.Library;
using C1.Win.C1FlexGrid;
using System.Data.SqlClient;
namespace ConvertAlarms
{
public partial class frmConvertAlarms : Form
{
//private void SaveProcedure(string text, string procNumber, string procTitle, int serialNo)
private static DocVersionInfo DVI;
private void SaveProcedure(string text, string procNumber, string procTitle, string fileName)
{
MatchCollection mc = Regex.Matches(text, "pNote");
if (mc.Count > 1) Console.WriteLine("-------> {0} Notes", mc.Count);
// Add Procedure Number and Title
ItemInfo prev = null;
//if (serialNo == 999999)
prev = DVI.MyItem == null ? null : DVI.MyItem.LastSibling; //FindLocation(DVI.MyItem,procNumber);
//else
//{
// prev = FindPrevious(dicSerialNo, serialNo);
//}
using (Procedure prc = Procedure.MakeProcedure(DVI, prev, procNumber, procTitle, 0))
{
MyLookUp = DVI.DocVersionAssociations[0].MyROFst.GetROFSTLookup(DVI);
if (MyLookUp.GetROIDByAccPagID("ALR-" + procNumber, "SP", "IG") == null)
{
prc.MyContent.Config = MakeConfig("<config><PSI ALMSERIALNUMBER=\"{0}\" ALM=\"{1}\" ALMID=\"{2}\" ALMSOURCE=\"{3}\" ALMSETPOINT=\"{4}\" KEPCOPROCNUM=\"{5}\" KEPCOPROCTITLE1=\"{6}\" /></config>",
prcSerialNoValue, prcTitleValue, prcNumberValue, prcSourceValue, prcSetpointValue, FullName.Substring(0, 13), FullName.Substring(14));
Annotation.MakeAnnotation(prc, AnnotationType.GetByNameOrCreate("Conversion Error"), null, "Missing Referenced Object " + procNumber , null);
}
else
prc.MyContent.Config = MakeConfig("<config><PSI KEPCOPROCNUM=\"{0}\" KEPCOPROCTITLE1=\"{1}\" /></config>",
FullName.Substring(0, 13), FullName.Substring(14));
prc.MyContent.Config = prc.MyContent.Config.Replace("<config><",string.Format("<config><Procedure Rev=\"{0}\"/><",RevisionNumber));
Annotation.MakeAnnotation(prc, AnnotationType.GetByNameOrCreate("Conversion Info"), null, GetAnnotationText(fileName), null);
ProcedureInfo prci = ProcedureInfo.Get(prc.ItemID);
// dicSerialNo.Add(serialNo, prci);
// Console.WriteLine("{0},{1}", serialNo, prci.ShortPath);
// Add Section
using (Section sec = Section.MakeSection(prci, null, null, "Procedure Content", 10006))
{
sec.SectionConfig.Section_ColumnMode = SectionConfig.SectionColumnMode.One;
sec.SectionConfig.Section_Pagination = SectionConfig.SectionPagination.Separate;
sec.Save();
SectionInfo seci = SectionInfo.Get(sec.ItemID);
// TODO: Add High Level Steps
// TODO: Add Substeps
MemoryStream ms = GetMemoryStream(text);
Queue<string> qread = new Queue<string>();
using (StreamReader sr = new StreamReader(ms))
fillQueue(qread, sr);
Dictionary<int, ItemInfo> lookup = new Dictionary<int, ItemInfo>();
lookup.Add(0, prci);
lookup.Add(1, seci);
int level = 2;
int type = 20001;
int lastLevel = 2;
int lastType = 0;
int lastIndent = 0;
int extra = 0;
string lastTab = "";
int? DeQueueType = null;
E_FromType myFromType = E_FromType.Step;
Queue<string> enQueue = null;
Queue<string> deQueue = null;
int deQueueLevel = 0;
int deQueueLevelLast = 0;
bool wasFromQueue;
bool firstQueue = false;
ItemInfo deQueueItem = null;
bool saveDeQueueInfo = false;
bool isTable = false;
bool lastWasTable = false;
string tableText = null;
string tab = "";
bool strangeBullet = false;
while (qread.Count > 0 || deQueue != null)
{
string lineText;
tableText = null;
if (deQueue != null)
{
wasFromQueue = true;
extra = 1;
lineText = deQueue.Dequeue().Trim();
if (deQueue.Count == 0)
deQueue = null;
if (Regex.IsMatch(lineText, "(NOTE|CAUTION|WARNING)"))
{
Console.WriteLine("Level {0} Type = {1}", deQueueLevel, DeQueueType);
switch (lineText)
{
case "<NOTE>":
DeQueueType = 20007;
break;
case "<CAUTION>":
DeQueueType = 20006;
break;
case "<WARNING>":
DeQueueType = 20020;
break;
}
firstQueue = true;
lineText = "\t" + deQueue.Dequeue();
while (deQueue.Count > 0 && deQueue.Peek().ToString().Trim().StartsWith("\u2022") == false && !Regex.IsMatch(deQueue.Peek(), "<(NOTE|CAUTION|WARNING)>"))
lineText += " " + deQueue.Dequeue();
myFromType = E_FromType.Note;
}
if (deQueue.Count == 0)
{
deQueue = null;
}
}
else
{
wasFromQueue = false;
DeQueueType = null;
extra = 0;
//if (NextLine != null)
//{
// lineText = NextLine;
// NextLine = null;
//}
//else
//{
lineText = qread.Dequeue().TrimEnd(" ".ToCharArray());
while (lineText.Trim() == "<pNOTE>" || lineText.Trim() == "<pCAUTION>" || lineText.Trim() == "<pWARNING>")
{
if (enQueue == null) enQueue = new Queue<string>();
lineText = qread.Dequeue().Trim();
//Console.WriteLine("======> {0},Count Before = {1} ", lineText.Trim(), enQueue.Count());
while (lineText != "</pNOTE>" && lineText != "</pCAUTION>" && lineText != "</pWARNING>")
{
enQueue.Enqueue(lineText.Trim());
lineText = qread.Dequeue().Trim();
}
lineText = qread.Dequeue().Trim();
//Console.WriteLine("======> {0},Count After = {1} ", lineText.Trim(), enQueue.Count());
}
if (lineText == "&gt;") lineText = lineText.Replace("&gt;", "");
else lineText = lineText.Replace("&lt;", "<").Replace("&gt;", ">");
//}
HasSpecialCharacters(lineText);
if (lineText.StartsWith("<table>"))
{
while (!lineText.Contains("</table>"))
{
lineText += " " + qread.Dequeue();
lineText = Regex.Replace(lineText, "</table>.*", "</table>");
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(lineText);
LoadTable2(xd.DocumentElement, null, 0);
isTable = true;
if (!lastWasTable) level = lastLevel + 1;
else level = lastLevel;
type = 20008;
tableText = GetTableText();
//StringBuilder sbxml= new StringBuilder();
//using(StringWriter sw = new StringWriter(sbxml))
// _MyFlexGrid.WriteXml(sw);
//using(StringReader sr= new StringReader(sbxml.ToString()))
// _MyFlexGrid.ReadXml(sr);
//Application.DoEvents();
}
else lineText = Regex.Replace(lineText, "<[^<>]+>", "");
}
if (lineText.Replace("\t", "").Replace(" ", "") != "")
{
lastLine = lineText;
Match m = Regex.Match(lineText, @"^(\t*)([1-9][0-9]*\.0|[1-9][0-9]*\.[1-9][0-9]*|[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*|[A-Z]\.|\u2022|)([\t ]+)([^\u2022]*)$", RegexOptions.Multiline);
if (m.Groups[4].Value != "")
{
tab = m.Groups[2].Value;
int indent = m.Groups[1].Value.Length;
if (isTable)
{
// do nothing
if (lastWasTable)
level = lastLevel;
else
level = 1 + lastLevel;
type = 20008;
myFromType = E_FromType.Table;
}
else if (indent == 0 && tab.EndsWith(".0")) // High Level Step
{
level = 2;
type = 20002;
}
else if (Regex.IsMatch(tab, "[1-9][0-9]*\\.[1-9][0-9]*\\.[1-9][0-9]*")) // Sub-Substep
{
level = 4;
type = 20001;
}
else if (Regex.IsMatch(tab, "[1-9][0-9]*\\.[1-9][0-9]*")) // Substep
{
level = 3;
type = 20001;
}
else if (Regex.IsMatch(tab, "[A-Z]\\.")) // Sub-Substep
{
level = 5;
type = 20001;
}
else if (tab == "") // Paragraph
{
level = lastLevel + 1;
type = 20024;
}
else if (tab == "\u2022")//bullet
{
if (firstQueue)
level = lastLevel + 1;
else if (lastTab == "\u2022")
level = lastLevel;
else
if (lastType == 20007 && lastTab == "")
level = lastLevel + 1;
else
{
level = indent + 3;
strangeBullet = true;
}
type = 20004;
if (Regex.IsMatch(m.Groups[4].Value, "^[0-9]"))
type = 20011;
}
else if (tab == "\u25CB")//bullet
{
level = indent + 4;
type = 20004;
if (Regex.IsMatch(m.Groups[4].Value, "^[0-9]"))
type = 20011;
}
//while (level < lastLevel)
// lookup.Remove(lastLevel--);
if (firstQueue && deQueueLevelLast > 0) level = deQueueLevelLast+1;
while (level < lookup.Count - 1)
lookup.Remove(lookup.Count - 1);
lastTab = tab;
lastLevel = level;
//lastIndent = indent;
lastWasTable = isTable;
deQueueLevelLast = deQueueLevel;
}
if (deQueue == null && enQueue != null)
{
deQueue = enQueue;
saveDeQueueInfo = true;
enQueue = null;
}
int newType = DeQueueType ?? (isTable ? 20008 : type);
lastType = newType;
if (enQueue == null)
{
if (lookup.Count < level)
{
using (Step stp = (lookup[lookup.Count - 1] as StepInfo).Get())
{
Annotation.MakeAnnotation(stp, AnnotationType.GetByNameOrCreate("Conversion Error"), null, GetAnnotationText2(lineText), null);
}
}
else if (lookup.Count == level)
{
using (Step stp = Step.MakeStep(lookup[level - 1], null, null, tableText ?? m.Groups[4].Value, newType, myFromType))
{
if (strangeBullet)
Annotation.MakeAnnotation(stp, AnnotationType.GetByNameOrCreate("Conversion Error"), null, "Strange Bullet", null);
ItemInfo myItem = StepInfo.Get(stp.ItemID);
if (isTable)
{
Grid.MakeGrid(stp.MyContent, _MyFlexGrid.GetXMLData(), "");
String footnote = GetFootNote(ms, qread);
if (footnote.Length > 0)
Step.MakeStep(myItem, null, null, footnote, 20024, E_FromType.Step);
}
isTable = false;
//Console.WriteLine("+++B tab = {0}, Lookup.Count = {1}, Level = {2}",tab, lookup.Count, level);
lookup.Add(level, myItem);
//Console.WriteLine("+++A tab = {0}, Lookup.Count = {1}, Level = {2}",tab, lookup.Count, level);
if (saveDeQueueInfo)
{
deQueueLevel = level;
deQueueItem = lookup[level];
saveDeQueueInfo = false;
}
if (firstQueue) firstQueue = false;
}
}
else
{
int previousType = ((int)lookup[level].MyContent.Type);
if (firstQueue && DeQueueType != null)
{
previousType = (int) DeQueueType;
level = deQueueLevel + 1;
}
using (Step stp = Step.MakeStep(lookup[level - 1], lookup[level], null, tableText ?? m.Groups[4].Value, previousType, myFromType))
{
Annotation.MakeAnnotation(stp, AnnotationType.GetByNameOrCreate("Conversion Error"), null, string.Format("Type Change {0} to {1}", newType, ((int)lookup[level].MyContent.Type)), null);
if (strangeBullet)
Annotation.MakeAnnotation(stp, AnnotationType.GetByNameOrCreate("Conversion Error"), null, "Strange Bullet", null);
strangeBullet = false;
ItemInfo myItem = StepInfo.Get(stp.ItemID);
if (isTable)
{
Grid.MakeGrid(stp.MyContent, _MyFlexGrid.GetXMLData(), "");
String footnote = GetFootNote(ms, qread);
if (footnote.Length > 0)
Step.MakeStep(myItem, null, null, footnote, 20024, E_FromType.Step);
}
isTable = false;
//Console.WriteLine(">>> tab = {0}, Lookup.Count = {1}, Level = {2}", tab, lookup.Count, level);
lookup[level] = myItem;
if (saveDeQueueInfo)
{
deQueueLevel = level;
deQueueItem = lookup[level];
saveDeQueueInfo = false;
}
if (firstQueue) firstQueue = false;
}
}
myFromType = E_FromType.Step;
if (deQueue == null && deQueueItem != null)
{
level = deQueueLevel;
while (level < lookup.Count)
lookup.Remove(lookup.Count - 1);
lookup[level] = deQueueItem;
deQueueItem = null;
DeQueueType = null;
}
}
//else
//{
// enQueue.Enqueue(lineText);
//}
DeQueueType = null;
}
}
}
}
if (runOne) MessageBox.Show("Done", "Converted");
}
private ItemInfo FindLocation(ItemInfo myItem, string procNumber)
{
while (myItem != null)
{
if (myItem.DisplayNumber.CompareTo(procNumber) >= 0)
return myItem.MyPrevious;
myItem = myItem.NextItem;
}
return myItem;
}
private string MakeConfig(string fmt, params string [] args)
{
string [] atts = new string[args.Length];
args.CopyTo(atts,0);
for(int i=0; i<atts.Length; i++)
atts[i] = atts[i].Replace("&","&amp;").Replace("<","&lt;").Replace(">","&gt;");
return string.Format(fmt, atts);
}
private void fillQueue(Queue<string> qread, StreamReader sr)
{
while(sr.Peek() > 0)
qread.Enqueue(sr.ReadLine());
}
//private string _NextLine;
//public string NextLine
//{
// get { return _NextLine; }
// set { _NextLine = value; }
//}
private string GetFootNote(MemoryStream ms, Queue<string> qRead)
{
string sep = "";
StringBuilder sb = new StringBuilder();
int lineCount = 0;
string lookingFor = null;
while(qRead.Count > 0)
{
// Read a line at a time
string str = qRead.Peek();
if(lineCount == 0 && str.StartsWith("<p>"))
{
lookingFor = "</p>";
str = str.Replace("<p>", "");
}
lineCount++;
str = Regex.Replace(str, "<[^<>]+>", "").Trim(" \t".ToCharArray()).Replace("&gt;", "");
str = str.Replace('\x25CB', 'o').Replace("\u2022", "\\u9679?");
//str = str.Replace('\x25CB', 'o').Replace("\u2022", "\\u7?");
// If Text begins with number then
if (lookingFor != null)
{
if (str.Contains(lookingFor))
{
sb.Append(sep + str.Replace(lookingFor, ""));
return sb.ToString();
}
}
else if (Regex.IsMatch(str, "[0-9].*") || str.StartsWith("<table>"))
return sb.ToString();
//append string
if (sb.ToString() != "" && str != "")
sep = "\r\n";
sb.Append(sep + str);
qRead.Dequeue();// Remove current line from queue
}
return sb.ToString();
}
private void ProcessChars(string str)
{
foreach (char c in str)
{
if (c < 0x20 || c > 0x7F)
Console.WriteLine("{0:X4}", (int)c);
}
}
public void ResetSpecial()
{
FoundSpecial = new List<char>();
}
List<char> FoundSpecial = new List<char>();
private void HasSpecialCharacters(string lineText)
{
StringBuilder sb = new StringBuilder();
foreach (char c in lineText)
{
if ((c < 0x20 || c > 0x7F) && !FoundSpecial.Contains(c))
{
Console.WriteLine("*** Special Character {0:X4}", (int)c);
FoundSpecial.Add(c);
}
}
}
private static string GetAnnotationText(string fileName)
{
return string.Format("FileName:{0}\r\nShortName:{1}\r\nFullName:{2}\r\nSystem:{3}\r\nPNSNo:{4}\r\nRelatedFunction:{5}" ,
fileName,ShortName,FullName,ApSystem,PNSNo ,RelatedFunction);
}
private static string GetAnnotationText2(string lineText)
{
//return string.Format("LineText:{0}\r\nShortName:{1}\r\nFullName:{2}\r\nSystem:{3}\r\nPNSNo:{4}\r\nRelatedFunction:{5}",
// lineText, ShortName, FullName, apSystem, PNSNo, RelatedFunction);
return string.Format("LineText:{0}",
lineText);
}
}
public class StepLookup : SortedDictionary<string, StepInfo>
{
public StepInfo this[int i]
{
get
{
if (this.ContainsKey(i.ToString())) return base[i.ToString()];
return null;
}
set
{
if (i > this.Count)
throw new Exception("Gap in Stack");
if (value == null)
throw new Exception("Null StepInfo");
//if (value.MyHLS.Ordinal==5 && (value.IsNote || value.IsCaution ))
// Volian.Base.Library.vlnStackTrace.ShowStackLocal(2,5,"=====> Adding Caution or Note on Step 5 {0}",value);
if (this.ContainsKey(i.ToString()))
{
base[i.ToString()] = value;
while (this.ContainsKey((i + 1).ToString()))
base.Remove((base.Count - 1).ToString());
}
else base.Add(i.ToString(), value);
//ListMySteps("Set ", this);
}
}
public void AddOne(StepInfo previousStep)
{
this[this.Count] = previousStep;
}
private static void ListMySteps(string str, StepLookup mySteps)
{
int i = 0;
foreach (string key in mySteps.Keys)
{
if (key != i.ToString())
Console.WriteLine("{0} {1} {2} {3}", str, i, key, mySteps[key].DisplayText);
i++;
}
}
}
}