I am extracting text from a PDF file and converting that text to HTML while extracting.
When doing this, an overlap of the text occurs, making it very difficult to read. I am using itextsharp to perform the extraction.
What in this code is causing that error?
public void Extract_inputpdf()
{
string pdf_of_inputFile = targetPathip;
StringBuilder sb_inputpdf = new StringBuilder();
PdfReader reader_inputPdf = new PdfReader(LblFleip.Text); //read PDF
divip.InnerHtml = "";
divop.InnerHtml = "";
sb_inputpdf.Length = 0;
text_output_File = string.Empty;
text_output_File_report = string.Empty;
text_input_File = string.Empty;
text_input_File_report = string.Empty;
input_pdf = string.Empty;
input_pdf_report = string.Empty;
output_pdf = string.Empty;
output_pdf_report = string.Empty;
rtbxinput_box_input = string.Empty;
rtbxinput_box_output = string.Empty;
Pagesize_input = 0;
FinalPagesize_input = 0;
Pagesize_output = 0;
FinalPagesize_output = 0;
for (i = 1;i <= reader_inputPdf.NumberOfPages;i++)
{
Pagesize_input = FinalPagesize_input;
height_input = reader_inputPdf.GetPageSizeWithRotation(i).Height;
pagenumber_input = i;
TextWithFont_inputPdf inputpdf = new TextWithFont_inputPdf();
text_input_File = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader_inputPdf, i, inputpdf);
sb_inputpdf.Append(text_input_File);
divip.InnerHtml = sb_inputpdf.ToString();
input_pdf = sb_inputpdf.ToString();
}
reader_inputPdf.Close();
}
//read input pdf ----------
public class TextWithFont_inputPdf : iTextSharp.text.pdf.parser.ITextExtractionStrategy
{
private StringBuilder result = new StringBuilder();
private Vector lastBaseLine;
private string lastFont;
private float lastFontSize;
public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)
{
string curFont = renderInfo.GetFont().PostscriptFontName;
string curfontweight = renderInfo.GetFont().PostscriptFontName;
float height_extract_input = Publishing.height_input;
int pagenumber_input = Publishing.i;//page number
string fontweight = string.Empty;
string fontstyle = string.Empty;
string presentfont = string.Empty;
string divide = curFont;
string[] fontnames = null;
//--------------------------------------------------------
Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
y_direction_input = 10 + Publishing.Pagesize_input + (height_extract_input - curBaseline[Vector.I2]);
Publishing.FinalPagesize_input = y_direction_input;
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
Single curFontSize = rect.Height;
//---------------------------------------
if ((this.lastBaseLine == null) || (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]) || (curFontSize != lastFontSize) || (curFont != lastFont))
{
if ((this.lastBaseLine != null))
{
this.result.AppendLine("</span>");
}
if ((this.lastBaseLine != null) && curBaseline[Vector.I2] != lastBaseLine[Vector.I2])
{
//this.result.AppendLine("<br />");
}
this.result.AppendFormat("<span style=\"font-family:{0};font-weight:{1};font-style:{2};margin-left:{3}pt;top:{4}pt; position:absolute;\">", curFont, fontweight, fontstyle, curBaseline[Vector.I1], y_direction_input);
}
this.result.Append(renderInfo.GetText());
this.lastBaseLine = curBaseline;
this.lastFontSize = curFontSize;
this.lastFont = curFont;
}
catch (Exception ex)
{
logWriter.Error("TextWithFont_inputPdf() : " + ex.Message);
}
}
public string GetResultantText()
{
if (result.Length > 0)
{
result.Append("</span>");
}
return result.ToString();
}
public void BeginTextBlock() { }
public void EndTextBlock() { }
public void RenderImage(ImageRenderInfo renderInfo) { }
}
Related
When I'm running my application and load a file(25MB) through it, everything runs just fine.
But when I try loading a file(160MB) I get a System.OutOfMemoryExeption.
Although I have been able to load the larger file at some point in time.
Is there anyway to fix this? If so, any help would be much appreciated!
My Code that loads the files:
private void openFile (string fileName)
{
List<Structs.strValidData> _header1 = new List<Structs.strValidData>();
List<Structs.strValidData> _header2 = new List<Structs.strValidData>();
List<Structs.strValidData> _header3 = new List<Structs.strValidData>();
List<Structs.strValidData> _header4 = new List<Structs.strValidData>();
var textBoxArray = new[]
{
textBoxResStart_Status1,
textBoxResStart_Status2,
textBoxResStart_Status3,
textBoxResStart_Status4,
textBoxResStart_Status5,
textBoxResStart_Status6,
textBoxResStart_Status7,
textBoxResStart_Status8,
};
var radioButtonArray = new[]
{
radioButtonResStart_SelectStr1,
radioButtonResStart_SelectStr2,
radioButtonResStart_SelectStr3,
radioButtonResStart_SelectStr4,
radioButtonResStart_SelectStr5,
radioButtonResStart_SelectStr6,
radioButtonResStart_SelectStr7,
radioButtonResStart_SelectStr8,
};
readCSV read;
read = new readCSV();
strInfo = default(Structs.strInfo);
strData = default(Structs.strData);
strSetup = default(Structs.strSetup);
strValidData = new List<Structs.strValidData>();
readID = default(Structs.ReadID);
try
{
strInfo = read.loadInfo(fileName);
strData = read.loadData(fileName);
strSetup = read.loadSetup(fileName);
readID = read.loadID(fileName);
strValidData = read.loadValidData(fileName);
var Str1 = read.loadStr1(fileName);
var Str235678 = read.loadStr235678(fileName);
var Str4 = read.loadStr4(fileName);
foreach (Structs.strValidData items in strValidData)
{
if (items.Str1_ValidData == true)
{
Str1_headers.Add(items);
}
if (items.Str2_ValidData == true ||
items.Str3_ValidData == true ||
items.Str5_ValidData == true ||
items.Str6_ValidData == true ||
items.Str7_ValidData == true ||
items.Str8_ValidData == true)
{
Str235678_headers.Add(items);
}
if (items.Str4_ValidData == true)
{
Str4_headers.Add(items);
}
}
Str1_data = combineData(Str1, Str1_headers);
Str4_data = combineData(Str4, Str4_headers);
var Str235678_CombinedData = combineData(Str235678, Str235678_headers);
foreach (Structs.strValidData items in Str235678_CombinedData)
{
if (items.Str2_ValidData == true)
{
Str2_data.Add(items);
}
if (items.Str3_ValidData == true)
{
Str3_data.Add(items);
}
if (items.Str5_ValidData == true)
{
Str5_data.Add(items);
}
if (items.Str6_ValidData == true)
{
Str6_data.Add(items);
}
if (items.Str7_ValidData == true)
{
Str7_data.Add(items);
}
if (items.Str8_ValidData == true)
{
Str8_data.Add(items);
}
}
strInfo = read.loadInfo(openDialog.FileName);
strData = read.loadData(openDialog.FileName);
strSetup = read.loadSetup(openDialog.FileName);
readID = read.loadID(openDialog.FileName);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
error.logSystemError(err);
}
}
Here are the ReadCSV() code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FileHelpers;
using FileHelpers.Events;
namespace Reading_Files
{
public class readCSV
{
public int strCnt = 0;
private readCSVprogressForm _waitForm;
public List<Structs.strDataImport> copyList(List<strData> copyFrom)
{
List<Structs.strDataImport> list = new List<Structs.strDataImport>();
list.AddRange(copyFrom.Select(s => copyListContents(s)));
return list;
}
public Structs.strDataImport copyListContents(strData copyFrom)
{
Structs.strDataImport data = new Structs.strDataImport();
data.sCD_TimeCP2711 = copyFrom.sCD_TimeCP2711;
data.sCD_TimeCX9020_1 = copyFrom.sCD_TimeCX9020_1;
data.sCD_TimeCX9020_2 = copyFrom.sCD_TimeCX9020_2;
data.rCD_CX9020_1_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_1_TimeDiff_DataLow);
data.rCD_CX9020_2_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_2_TimeDiff_DataLow);
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.bCD_1_Status = copyFrom.bCD_1_Status;
data.bCD_1_Overrange = copyFrom.bCD_1_Overrange;
data.iCD_1_Str_ID = copyFrom.iCD_1_Str_ID;
data.rCD_1_Value = copyFrom.rCD_1_Value;
data.bCD_2_Status = copyFrom.bCD_2_Status;
data.bCD_2_Overrange = copyFrom.bCD_2_Overrange;
data.iCD_2_Str_ID = copyFrom.iCD_2_Str_ID;
data.rCD_2_Value = copyFrom.rCD_2_Value;
data.bCD_3_Status = copyFrom.bCD_3_Status;
data.bCD_3_Overrange = copyFrom.bCD_3_Overrange;
data.iCD_3_Str_ID = copyFrom.iCD_3_Str_ID;
data.iCD_3_RawData = copyFrom.iCD_3_RawData;
data.rCD_3_Value = copyFrom.rCD_3_Value;
data.bCD_4_Status = copyFrom.bCD_4_Status;
data.bCD_4_Overrange = copyFrom.bCD_4_Overrange;
data.iCD_4_Str_ID = copyFrom.iCD_4_Str_ID;
data.iCD_4_RawData = copyFrom.iCD_4_RawData;
data.rCD_4_Value = copyFrom.rCD_4_Value;
data.bCD_5_Status = copyFrom.bCD_5_Status;
data.bCD_5_Overrange = copyFrom.bCD_5_Overrange;
data.iCD_5_Str_ID = copyFrom.iCD_5_Str_ID;
data.iCD_5_RawData = copyFrom.iCD_5_RawData;
data.rCD_5_Value = copyFrom.rCD_5_Value;
data.bCD_6_Status = copyFrom.bCD_6_Status;
data.bCD_6_Overrange = copyFrom.bCD_6_Overrange;
data.iCD_6_Str_ID = copyFrom.iCD_6_Str_ID;
data.iCD_6_RawData = copyFrom.iCD_6_RawData;
data.rCD_6_Value = copyFrom.rCD_6_Value;
data.bCD_7_Status = copyFrom.bCD_7_Status;
data.bCD_7_Overrange = copyFrom.bCD_7_Overrange;
data.iCD_7_Str_ID = copyFrom.iCD_7_Str_ID;
data.iCD_7_RawData = copyFrom.iCD_7_RawData;
data.rCD_7_Value = copyFrom.rCD_7_Value;
data.bCD_8_Status = copyFrom.bCD_8_Status;
data.bCD_8_Overrange = copyFrom.bCD_8_Overrange;
data.iCD_8_Str_ID = copyFrom.iCD_8_Str_ID;
data.iCD_8_RawData = copyFrom.iCD_8_RawData;
data.rCD_8_Value = copyFrom.rCD_8_Value;
data.bCD_9_Status = copyFrom.bCD_9_Status;
data.bCD_9_Overrange = copyFrom.bCD_9_Overrange;
data.iCD_9_Str_ID = copyFrom.iCD_9_Str_ID;
data.iCD_9_RawData = copyFrom.iCD_9_RawData;
data.rCD_9_Value = copyFrom.rCD_9_Value;
data.bCD_10_Status = copyFrom.bCD_10_Status;
data.bCD_10_Overrange = copyFrom.bCD_10_Overrange;
data.iCD_10_Str_ID = copyFrom.iCD_10_Str_ID;
data.iCD_10_RawData = copyFrom.iCD_10_RawData;
data.rCD_10_Value = copyFrom.rCD_10_Value;
data.bCD_11_Status = copyFrom.bCD_11_Status;
data.bCD_11_Overrange = copyFrom.bCD_11_Overrange;
data.iCD_11_Str_ID = copyFrom.iCD_11_Str_ID;
data.iCD_11_RawData = copyFrom.iCD_11_RawData;
data.rCD_11_Value = copyFrom.rCD_11_Value;
data.bCD_12_Status = copyFrom.bCD_12_Status;
data.bCD_12_Overrange = copyFrom.bCD_12_Overrange;
data.iCD_12_Str_ID = copyFrom.iCD_12_Str_ID;
data.iCD_12_RawData = copyFrom.iCD_12_RawData;
data.rCD_12_Value = copyFrom.rCD_12_Value;
data.bCD_13_Status = copyFrom.bCD_13_Status;
data.bCD_13_Overrange = copyFrom.bCD_13_Overrange;
data.iCD_13_Str_ID = copyFrom.iCD_13_Str_ID;
data.iCD_13_RawData = copyFrom.iCD_13_RawData;
data.rCD_13_Value = copyFrom.rCD_13_Value;
data.bCD_14_Status = copyFrom.bCD_14_Status;
data.bCD_14_Overrange = copyFrom.bCD_14_Overrange;
data.iCD_14_Str_ID = copyFrom.iCD_14_Str_ID;
data.iCD_14_RawData = copyFrom.iCD_14_RawData;
data.rCD_14_Value = copyFrom.rCD_14_Value;
data.bCD_15_Status = copyFrom.bCD_15_Status;
data.bCD_15_Overrange = copyFrom.bCD_15_Overrange;
data.iCD_15_Str_ID = copyFrom.iCD_15_Str_ID;
data.iCD_15_RawData = copyFrom.iCD_15_RawData;
data.rCD_15_Value = copyFrom.rCD_15_Value;
data.bCD_16_Status = copyFrom.bCD_16_Status;
data.bCD_16_Overrange = copyFrom.bCD_16_Overrange;
data.iCD_16_Str_ID = copyFrom.iCD_16_Str_ID;
data.iCD_16_RawData = copyFrom.iCD_16_RawData;
data.rCD_16_Value = copyFrom.rCD_16_Value;
data.bCD_17_Status = copyFrom.bCD_17_Status;
data.bCD_17_Overrange = copyFrom.bCD_17_Overrange;
data.iCD_17_Str_ID = copyFrom.iCD_17_Str_ID;
data.iCD_17_RawData = copyFrom.iCD_17_RawData;
data.rCD_17_Value = copyFrom.rCD_17_Value;
data.bCD_18_Status = copyFrom.bCD_18_Status;
data.bCD_18_Overrange = copyFrom.bCD_18_Overrange;
data.iCD_18_Str_ID = copyFrom.iCD_18_Str_ID;
data.iCD_18_RawData = copyFrom.iCD_18_RawData;
data.rCD_18_Value = copyFrom.rCD_18_Value;
data.bCD_19_Status = copyFrom.bCD_19_Status;
data.bCD_19_Overrange = copyFrom.bCD_19_Overrange;
data.iCD_19_Str_ID = copyFrom.iCD_19_Str_ID;
data.rCD_19_Value = copyFrom.rCD_19_Value;
data.bCD_20_Status = copyFrom.bCD_20_Status;
data.bCD_20_Overrange = copyFrom.bCD_20_Overrange;
data.iCD_20_Str_ID = copyFrom.iCD_20_Str_ID;
data.rCD_20_Value = copyFrom.rCD_20_Value;
return data;
}
public Structs.ReaStrID load_ID(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strIDSelector);
var data = engine.ReadFile(FileName);
Structs.ReaStrID structure = new Structs.ReaStrID();
foreach (strID filteredData in data)
{
structure.steID[0] = filteredData._1_Ste_ID;
structure.Status[0] = filteredData._1_Status;
structure.steID[1] = filteredData._2_Ste_ID;
structure.Status[1] = filteredData._2_Status;
structure.steID[2] = filteredData._3_Ste_ID;
structure.Status[2] = filteredData._3_Status;
structure.steID[3] = filteredData._4_Ste_ID;
structure.Status[3] = filteredData._4_Status;
structure.steID[4] = filteredData._5_Ste_ID;
structure.Status[4] = filteredData._5_Status;
}
return structure;
}
public Structs.strInfo loadInfo(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strInfoSelector);
var data = engine.ReadFile(FileName);
Structs.strInfo structure = new Structs.strInfo();
foreach (strInfo filteredData in data)
{
structure.Date = filteredData.Date;
structure.Description1 = filteredData.Description1;
structure.Description2 = filteredData.Description2;
structure.Description3 = filteredData.Description3;
}
return structure;
}
public Structs.strData loadData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strDataSelector);
var data = engine.ReadFile(FileName);
Structs.strData structure = new Structs.strData();
foreach (strData filteredData in data)
{
structure.iMDstr_var1_TypeID = filteredData.iMDstr_var1_TypeID;
structure.rMDstr_var1_Lenght = filteredData.rMDstr_var1_Lenght;
structure.iMDstr_var2_TypeID = filteredData.iMDstr_var2_TypeID;
structure.rMDstr_var2_Lenght = filteredData.rMDstr_var2_Lenght;
structure.iMDstr_var3_TypeID = filteredData.iMDstr_var3_TypeID;
structure.rMDstr_var3_Lenght = filteredData.rMDstr_var3_Lenght;
structure.iMDstr_var4_TypeID = filteredData.iMDstr_var4_TypeID;
structure.rMDstr_var4_Lenght = filteredData.rMDstr_var4_Lenght;
}
return structure;
}
public Structs.strSetup loadSetup(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strID),
typeof(strData),
typeof(strSetup),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strSetupSelector);
var data = engine.ReadFile(FileName);
Structs.strSetup structure = new Structs.strSetup();
foreach (strSetup filteredData in data)
{
structure.sSSstr_Sens = filteredData.sSSstr_Sens;
structure.bSSstr_S1_A = filteredData.bSSstr_S1_A;
structure.iSSstr_S1_B = filteredData.iSSstr_S1_B;
structure.sSSstr_S1_C = filteredData.sSSstr_S1_C;
structure.rSSstr_S1_D = filteredData.rSSstr_S1_D;
structure.bSSstr_S2_A = filteredData.bSSstr_S2_A;
structure.iSSstr_S2_B = filteredData.iSSstr_S2_B;
structure.sSSstr_S2_C = filteredData.sSSstr_S2_C;
structure.rSSstr_S2_D = filteredData.rSSstr_S2_D;
structure.bSSstr_S3_A = filteredData.bSSstr_S3_A;
structure.iSSstr_S3_B = filteredData.iSSstr_S3_B;
structure.sSSstr_S3_C = filteredData.sSSstr_S3_C;
structure.iSSstr_S3_D = filteredData.iSSstr_S3_D;
}
return structure;
}
public List<Structs.str1> load1(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strID),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str1Selector);
var data = engine.ReadFile(FileName);
List<Structs.str1> list = new List<Structs.str1>();
int i = 0;
foreach (str1 data1 in data)
{
Structs.str1 structure = new Structs.str1();
structure.rGL_1_L_Positive = data1.rGL_1_L_Positive;
structure.rGL_1_L_Negative = data1.rGL_1_L_Negative;
structure.rGL_1_R_Positive = data1.rGL_1_R_Positive;
structure.rGL_1_R_Negative = data1.rGL_1_R_Negative;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.str4> load4(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str4Selector);
var data = engine.ReadFile(FileName);
List<Structs.str4> list = new List<Structs.str4>();
int i = 0;
foreach (str4 data4 in data)
{
Structs.str4 structure = new Structs.str4();
structure.rGL_4_1 = data4.rGL_4_1;
structure.rGL_4_2 = data4.rGL_4_2;
structure.rGL_4_3 = data4.rGL_4_3;
structure.rGL_4_4 = data4.rGL_4_4;
structure.rGL_4_5 = data4.rGL_4_5;
structure.rGL_4_6 = data4.rGL_4_6;
structure.rGL_4_7 = data4.rGL_4_7;
structure.rGL_4_8 = data4.rGL_4_8;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.strValidData> loadValidData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData),
typeof(strValidData));
engine.RecordSelector = new RecordTypeSelector(strValidDataSelector);
var data = engine.ReadFile(FileName);
List<Structs.strValidData> list = new List<Structs.strValidData>();
int i = 0;
foreach (strValidData strValidData in data)
{
Structs.strValidData structure = new Structs.strValidData();
structure._name = String.Format("strItem {0}", i + 1);
structure._index = i;
structure.str1_ValidData = strValidData.str1_ValidData;
structure.str2_ValidData = strValidData.str2_ValidData;
structure.str3_ValidData = strValidData.str3_ValidData;
structure.str4_ValidData = strValidData.str4_ValidData;
structure.str5_ValidData = strValidData.str5_ValidData;
structure.str6_ValidData = strValidData.str6_ValidData;
structure.str7_ValidData = strValidData.str7_ValidData;
structure.str8_ValidData = strValidData.str8_ValidData;
structure.str9_ValidData = strValidData.str9_ValidData;
list.Add(structure);
i++;
}
return list;
}
public List<List<Structs.strDataImport>> loadstrDataAsync(string FileName)
{
var engine_Data = new FileHelperAsyncEngine<strData>();
engine_Data.BeforeReadRecord += BeforeEventAsync;
engine_Data.AfterReadRecord += AfterEventAsync;
engine_Data.Progress += ReadProgress;
List<strData> list = new List<strData>();
List<List<Structs.strDataImport>> list2D = new List<List<Structs.strDataImport>>();
using (engine_Data.BeginReadFile(FileName))
{
var prevRowNo = 0;
var j = 0;
strCnt = 0;
foreach (strData filteredData in engine_Data)
{
if (prevRowNo > filteredData.RowNo)
{
list2D.Add(copyList(list));
list.Clear();
}
prevRowNo = filteredData.RowNo;
list.Add(filteredData);
}
list2D.Add(copyList(list));
}
return list2D;
}
private Type strIDSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA .STATUS .STRID **"))
return typeof(strID);
else
{
return null;
}
}
private Type InfoSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_FILE **"))
return typeof(strInfo);
else
{
return null;
}
}
private Type strDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA **"))
return typeof(strData);
else
{
return null;
}
}
private Type strSetupSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_SETUP **"))
return typeof(strSetup);
else
{
return null;
}
}
private Type strValidDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_VALID_DATA **"))
return typeof(strValidData);
else
{
return null;
}
}
private Type StartNumSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_START_NUMBER **"))
return typeof(strStartNum);
else
{
return null;
}
}
private Type str1Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_1 **"))
return typeof(str1);
else
{
return null;
}
}
private Type str4Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_4 **"))
return typeof(str4);
else
{
return null;
}
}
private void BeforeEventAsync(EngineBase engine, BeforeReadEventArgs<strData> e)
{
if (e.RecordLine != "")
{
if (Char.IsDigit(e.RecordLine, 0))
{
}
else
{
e.SkipThisRecord = true;
}
}
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void AfterEventAsync(EngineBase engine, AfterReadEventArgs<strData> e)
{
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void ReadProgress(object sender, ProgressEventArgs e)
{
ShowWaitForm("Opening file." + "\n" + "\n" + "Please wait...", "Open File");
_waitForm.progressBar1.Value = Convert.ToInt16(e.Percent);
}
public void ShowWaitForm(string message, string caption)
{
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new readCSVprogressForm();
_waitForm.ShowMessage(message);
_waitForm.Text = caption;
_waitForm.TopMost = true;
_waitForm.Show();
_waitForm.Refresh();
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
}
Given the comments, it sounds like the problem is really that you're using structs extensively. These should almost certainly be classes for idiomatic C#. See the design guidelines for more details of how to pick between these.
At the moment, you're loading all the values in a big List<T>. Internally, that has an array - so it's going to be an array of your struct type. That means all the values are required to be in a single contiguous chunk of memory - and it sounds like that chunk can't be allocated.
If you change your data types to classes, then a contiguous chunk of memory will still be required - but only enough to store references to the objects you create. You'll end up using slightly more data overall (due to per-object overhead and the references to those objects) but you won't have nearly as strict a requirement on allocating a single big chunk of memory.
That's only one reason to use classes here - the reason of "this just isn't a normal use of structs" is a far bigger one, IMO.
As an aside, I'd also very strongly recommend that you start following .NET naming conventions, particularly around the use of capitalization and avoiding underscores to separate words in names. (There are other suggestions for improving the code in the question too, and I'd advise reading them all carefully.)
I have an automaton to integrate my files (.oxi = xml file ) in the DB, but i have a problem that the same file is integrated 2 times and more .
I did many precaution to prevent that using the move function from the IN path to the archive path after the integration but it still not working .
After that i used the copy to the archive path and delete the file from the IN path after the integration succed but it still not working.
Can any body explain to me what the problem exactly ?
public class Doc
{
public XmlDocument xDoc { get; set; }
public String Path { get; set; }
public String file_name { get; set; }
}
public class Job
{
public String Name { get; set; }
public String PathIn { get; set; }
public String PathArchive { get; set; }
public String PathError { get; set; }
public String StatutLotOut { get; set; }
}
// start the job called every period by the timer
public void start()
{
//General.addLog("hello, i am started");
UpdateText();
List<Job> jobs = get_jobs();
foreach (Job job in jobs)
{
List<Doc> docs = new List<Doc>();
//read all xml document inside the IN forlder path in
docs = gen.read_oxi(job);
foreach (Doc doc in docs)
{
try
{
TransferOpex.doc = doc;
TransferOpex.job = job;
xml_serialisation(doc.xDoc, job);
gen.moveDocToArchiverPath();
break;
}
catch (Exception ex)
{
General.addText("\n error : " + ex.ToString());
General.addLog(ex.ToString());
gen.moveDocToErrorPath();
}
}
}
}
public void moveDocToArchiverPath()
{
if (File.Exists(TransferOpex.doc.Path))
{
string Path2 = Path.Combine(TransferOpex.job.PathArchive, TransferOpex.doc.file_name + ".oxi");
if (File.Exists(Path2))
File.Delete(Path2);
File.Copy(TransferOpex.doc.Path, Path2,true);
addText("\n file " + TransferOpex.doc.Path + " copied to Archive path at" + DateTime.Now);
General.addLog("\n file " + TransferOpex.doc.Path + " copied to Archive path at" + DateTime.Now);
if (File.Exists(TransferOpex.doc.Path))
{
while (!IsFileReady(TransferOpex.doc.Path)) {
}
File.Delete(TransferOpex.doc.Path);
addText("\n file " + TransferOpex.doc.Path + " deleted from in path at" + DateTime.Now);
General.addLog("\n file " + TransferOpex.doc.Path + " deleted from in path at" + DateTime.Now);
}
}
}
public static bool IsFileReady(string filename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
I use timer to check every time if there are new files in the IN Forlder
SetTimer();
private void SetTimer()
{
TextAffichage += "\n The application started at " + DateTime.Now;
General.addText("\n Timer = " + gen.ReadSetting("Timer") + "ms");
General.addText("\n configPath = " + configPath);
General.addText(" \n connectionStrings = " + gen.ReadSetting("connectionStrings"));
General.addLog("Started");
UpdateText();
// Create a timer with a x second interval, you can find the value of x inside app.config.
aTimer = new System.Timers.Timer(int.Parse(gen.ReadSetting("Timer")));
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
start();
}
And this the function that make the integration in the DB
public void xml_serialisation(XmlDocument doc, Job job)
{
Lot lot = new Lot();
classes.Image image = new classes.Image();
XmlNodeList batchs = doc.GetElementsByTagName("Batch");
XmlNode batch = batchs[0];
String BatchIdentifier = batch.Attributes["BatchIdentifier"] != null ? batch.Attributes["BatchIdentifier"].Value : "Unknow value";
String NUM_LOT = BatchIdentifier;
String TransportId = batch.Attributes["TransportId"] != null ? batch.Attributes["TransportId"].Value : "Unknow value";
String NUM_SCANNER = TransportId;
String StartTime = doc.GetElementsByTagName("Batch")[0].Attributes["StartTime"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["StartTime"].Value : "Unknow value";
//String ID_lot = DateTime.Parse(StartTime).ToString("yyyyMMdd") + "" + NUM_LOT + "" + NUM_SCANNER;
String ID_lot = TransferOpex.doc.file_name;
String NUM_NB_IMAGE = doc.GetElementsByTagName("EndInfo")[0].Attributes["NumPages"] != null ? doc.GetElementsByTagName("EndInfo")[0].Attributes["NumPages"].Value : "Unknow value";
String EndTime = doc.GetElementsByTagName("EndInfo")[0].Attributes["EndTime"] != null ? doc.GetElementsByTagName("EndInfo")[0].Attributes["EndTime"].Value : "Unknow value";
String JobName = doc.GetElementsByTagName("Batch")[0].Attributes["JobName"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["JobName"].Value : "Unknow value";
String ImageFilePath = doc.GetElementsByTagName("Batch")[0].Attributes["ImageFilePath"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["ImageFilePath"].Value : "Unknow value";
//String OperatorName = doc.GetElementsByTagName("Batch")[0].Attributes["OperatorName"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["OperatorName"].Value : "Unknow value";
String OperatorName = gen.ReadSetting("OperatorName");
//instatiate Class lot
lot.TXT_TYPE_LOT = JobName;
lot.ID_LOT = long.Parse(ID_lot);
lot.NUM_NB_IMAGE = int.Parse(NUM_NB_IMAGE);
lot.DAT_DEBUT_NUM = DateTime.Parse(StartTime);
lot.DAT_FIN_NUM = DateTime.Parse(EndTime);
lot.ID_STATUT = int.Parse(job.StatutLotOut);// attention!!!!!!!!!!!, faut le recuperer de la configuration
lot.NUM_SCANNER = int.Parse(NUM_SCANNER);
lot.TXT_OPERATEUR = OperatorName;
XmlNodeList pages = doc.GetElementsByTagName("Page");
List<classes.Image> images = new List<classes.Image>();
List<Icr> icrs = new List<Icr>();
foreach (XmlNode page in pages)
{
String BatchSequence = page.Attributes["BatchSequence"] != null ? page.Attributes["BatchSequence"].Value : "Unknow value";
XmlNodeList imgs = null;
if (page.SelectNodes("Image") != null && page.SelectNodes("Image").Count > 0)
{
imgs = page.SelectNodes("Image");
}
String AuditTrail = "";
if (page.SelectNodes("AuditTrail") != null && page.SelectNodes("AuditTrail").Count >0)
{
AuditTrail = page.SelectNodes("AuditTrail")[0].Attributes["Text"] != null ? page.SelectNodes("AuditTrail")[0].Attributes["Text"].Value : "Unknow value";
}
String PageName = page.Attributes["PageName"] != null ? page.Attributes["PageName"].Value : "Unknow value";
// get node list from the config.xml file
XmlNodeList Recos = gen.getNodelList("Reco");
foreach (XmlNode Reco in Recos)
{
String Balise = Reco.Attributes["Balise"] != null ? Reco.Attributes["Balise"].Value : "";
String TagValue = Reco.Attributes["TagValue"] != null ? Reco.Attributes["TagValue"].Value : "";
String TypeIcr = Reco.Attributes["TypeIcr"] != null ? Reco.Attributes["TypeIcr"].Value : "";
XmlNodeList Balises = page.SelectNodes(Balise) != null ? page.SelectNodes(Balise) : null;
if (Balises != null)
{
foreach (XmlNode balise in Balises)
{
//instatiate Class Icr
String Index = balise.Attributes["Index"] != null ? balise.Attributes["Index"].Value : "";
Icr icr = new Icr();
// this instance will be saved
icr.save_it = true;
icr.ID_LOT = lot.ID_LOT;
icr.NUM_SEQUENCE = int.Parse(BatchSequence);
icr.NUM_INDEX = Index;
if (Balise == "Barcode")
{
icr.TXT_ICR = balise.Attributes["Value"].Value;
if (balise.Attributes["Type"] != null)
{
if (balise.Attributes["Type"].Value == TagValue)
{
icr.TXT_TYPE = TypeIcr;
}
else
{
icr.TXT_TYPE = "unknow value";
// prevent the instance to be saved in the DB
icr.save_it = false;
}
}
}
else if (Balise == "markDetect")
{
icr.TXT_ICR = balise.Attributes["Result"].Value;
icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value;
}
else if (Balise == "Micr")
{
icr.TXT_ICR = balise.Attributes["Value"].Value;
icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value;
}
else if (Balise == "OCR")
{
icr.TXT_ICR = balise.Attributes["Value"].Value;
icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value;
}
else
{
icr.save_it = false;
}
if (icr.TXT_ICR == "")
{
icr.save_it = false;
}
if (icr.save_it) icrs.Add(icr);
}
}
}
if(imgs !=null)
foreach (XmlNode img in imgs)
{
String Filename = img.Attributes["Filename"] != null ? img.Attributes["Filename"].Value : "Unknow value";
if (Filename == "" && gen.ReadSetting("acceptBlankImage") == "0")
{
General.addLog("can't add blank image( image without path ), in order to do that please change the value of acceptBlankImage to 1 ");
//create exceprion intentionally outside of the catch
int i = 0;
int j = 1 / i;
}
try
{
String Length = img.Attributes["Length"] != null ? img.Attributes["Length"].Value : "Unknow value";
String Height = img.Attributes["Height"] != null ? img.Attributes["Height"].Value : "Unknow value";
image = new classes.Image();
image.ID_LOT = lot.ID_LOT;
image.TXT_CHEMIN_IMAGE = ImageFilePath + "\\" + Filename;
String machine = gen.ReadSetting("machine");
//String index = "";
//if (machine == "IBML")
//{
// index = Filename[0] + "" + Filename[1];
//}
//else if (machine == "OPEX")
//{
// String file_name_without_extension = Path.GetFileNameWithoutExtension(Filename);
// int Lenght = file_name_without_extension.Length;
// int firstrightcharindex = Lenght - 1;
// index = file_name_without_extension[firstrightcharindex] + "";
//}
String expression = gen.ReadSetting("EXPRESSION_NUM_TYPE_PAGE");
String index = "";
if (expression[0] == 'g' || expression[0] == 'G')
{
int gauche = (int)char.GetNumericValue(expression[1]);//donne le number de caratère faut le recuperer à droite
for (int i = 0; i < gauche; i++)
{
index += Filename[i] + "";
}
}
else if (expression[0] == 'd' || expression[0] == 'D')
{
int droite = (int)char.GetNumericValue(expression[1]);//donne le number de caratère faut le recuperer à droite
String file_name_without_extension = Path.GetFileNameWithoutExtension(Filename);
int Lenght = file_name_without_extension.Length;
int firstrightcharindex = Lenght - 1;
for (int i = firstrightcharindex; i > firstrightcharindex - droite; i--)
{
index += file_name_without_extension[i] + "";
}
index = General.Reverse(index);
}
image.TXT_ENDOS = AuditTrail;
image.NUM_SEQUENCE = int.Parse(BatchSequence);
image.NUM_PAGE = int.Parse(BatchSequence);
image.NUM_TYPE_PAGE = int.Parse(getTypeImage(PageName, index)); //attention !!!!!!, faut le recuperer de la configuration
image.ID_STATUT = int.Parse(gen.ReadSetting("ID_STATUT")); //attention!!!!!!!, faut le recuperer de la configuration
image.Length = Length;
image.Height = Height;
images.Add(image);
}
catch (Exception ex)
{
}
}
}
DB.Database db = new DB.Database();
// save into data base
db.save_to_db(lot, images, icrs);
}
//get the job list from config.xml and serialize into object
public List<classes.Job> get_jobs()
{
XmlNodeList jobsNodelist = gen.getNodelList("Job");
List<Job> jobs = new List<Job>();
foreach (XmlNode j in jobsNodelist)
{
Job job = new Job();
job.Name = j.Attributes["Name"] != null ? j.Attributes["Name"].Value : "unknow value";
job.PathArchive = j.Attributes["PathArchive"] != null ? j.Attributes["PathArchive"].Value : "unknow value";
job.PathIn = j.Attributes["PathIn"] != null ? j.Attributes["PathIn"].Value : "unknow job";
job.StatutLotOut = j.Attributes["StatutLotOut"] != null ? j.Attributes["StatutLotOut"].Value : "unknow job";
job.PathError = j.Attributes["PathError"] != null ? j.Attributes["PathError"].Value : "unknow job";
jobs.Add(job);
}
return jobs;
}
This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...
I want to pass real time signals from emotive to octave.
I tried to write a c# wrapper for octave. Here is the code.
namespace LibSharpTave {
public class Octave {
Process OctaveProcess { get; set; }
private string OctaveEchoString { get; set; }
public Octave(string PathToOctaveBinaries) {
StartOctave(PathToOctaveBinaries, false);
}
public Octave(string PathToOctaveBinaries, bool CreateWindow) {
StartOctave(PathToOctaveBinaries, CreateWindow);
}
string ptob;
bool cw;
private void StartOctave(string PathToOctaveBinaries, bool CreateWindow) {
ptob = PathToOctaveBinaries;
cw = CreateWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
if (PathToOctaveBinaries[PathToOctaveBinaries.Length - 1] != '\\')
PathToOctaveBinaries = PathToOctaveBinaries + "\\";
pi.FileName = PathToOctaveBinaries + "octave.exe";
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !CreateWindow;
pi.Verb = "open";
//
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
OctaveProcess.Start();
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.BeginOutputReadLine();
OctaveEntryText = ExecuteCommand(null);
//OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(Oc
}
public double GetScalar(string scalar) {
string rasp = ExecuteCommand(scalar, 30000);
string val = rasp.Substring(rasp.LastIndexOf("\\") + 1).Trim();
return double.Parse(val);
}
public double[] GetVector(string vector) {
string rasp = ExecuteCommand(vector, 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
//catam urmatorul entry
List<double> data = new List<double>();
while (i != lines.Length) {
string line = lines[i];
if (line.Contains("through") || line.Contains("and")) {
i++;
line = lines[i];
string[] dataS = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
i++;
}
//caz special in care a pus toate rezultatele pe o singura linie
if (data.Count == 0) {
string[] dataS = lines[lines.Length - 1].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (dataS.Length != 0)
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
return data.ToArray();
}
public double[][] GetMatrix(string matrix) {
//string rasp = ExecuteCommand(matrix);
//aflam numarul de randuri
string rasp = ExecuteCommand(matrix + "(:,1)", 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
double[][] mat = new double[lines.Length - 1][];
for (int i = 0; i < mat.Length; i++) {
mat[i] = GetVector(matrix + "(" + (i + 1) + ",:)");
}
return mat;
}
StringBuilder SharedBuilder = new StringBuilder();
ManualResetEvent OctaveDoneEvent = new ManualResetEvent(false);
public string OctaveEntryText { get; internal set; }
public void WorkThread(object o) {
string command = (string)o;
SharedBuilder.Clear();
OctaveDoneEvent.Reset();
if (command != null) {
OctaveProcess.StandardInput.WriteLine(command);
}
//ca sa avem referinta pentru output
OctaveProcess.StandardInput.WriteLine("\"" + OctaveEchoString + "\"");
OctaveDoneEvent.WaitOne();
}
public string ExecuteCommand(string command, int timeout) {
if (OctaveProcess.HasExited) {
StartOctave(ptob, cw);
if (OctaveRestarted != null) OctaveRestarted(this, EventArgs.Empty);
}
exitError = false;
Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
tmp.Start(command);
if (!tmp.Join(timeout)) {
tmp.Abort();
throw new Exception("Octave timeout");
}
if (exitError) {
throw new Exception(errorMessage);
}
return SharedBuilder.ToString();
}
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
}
bool exitError = false;
string errorMessage = null;
void OctaveProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) {
if (e.Data == null) {
SharedBuilder.Clear();
//errorMessage = OctaveProcess.StandardError.ReadToEnd();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + errorMessage);
//exitError = true;
OctaveDoneEvent.Set();
return;
}
if (e.Data.Trim() == "ans = " + OctaveEchoString)
OctaveDoneEvent.Set();
else
SharedBuilder.Append(e.Data + "\r\n");
}
public event OctaveRestartedEventHandler OctaveRestarted;
public delegate void OctaveRestartedEventHandler(object sender, EventArgs e);
}
//custom class
// void OctaveProcess_OutputDataReceived (object sender, DataReceivedeEventArgs e)
/*{
if (e.data == null)
{
SharedBuilder.Clear();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + OctaveProcess.StandardError.ReadToEnd());
OctaveDoneEvent.Set();
return;
}
if (e.data.Trim == "ans =" + OctaveEchoString())
OctaveDoneEvent.set();
else
SharedBuilder.Append(e.Data + "\r\n");
}*/
}
And it is returning the error: "Not all code paths return a value".
How can I fix this error?
Your ExecuteCommand function should return a string, but doesn't. This is the ExecuteCommand overload that accepts one argument.
This function has string as return type but does not return anything when if (command != null) statement is false -
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
//**** The Error is here *****
//return a string here
}
Return a string at the mention section. I highlighted in the comment as - //**** The Error is here *****
Your
public string ExecuteCommand(string command) {
has no return statement even though you specified return type string.
Either return some string or make its return type void as in :
public void ExecuteCommand(string command) {
I have situation where I have a number of validators with the same error message on a page, when the page is validated these duplicates are shown in the validation summary.
I would like to remove these duplicates from the validation summary server side.
Here's some pseudo code of what I'd like to do.
validationSummery.ErrorMessages = validationSummery.ErrorMessages.DistinctBy(x=>x.ErrorText);
Having looked into the validation control it appears there is no access to the messages it displays.
I could iterate over all of the page validators which are invalid before the validation summary gets to them and set only one of each message type to valid but then I would not get the error message next to each control.
Does anyone know a way to do this?
It's not pretty but with the use of dotPeek to get the source for the ValidationSummary along with a bit of reflection I created a UniqueMessageValidationSummary control.
/// <summary>
/// Extended version of Validation Summary which overrides OnRender and re-implements get error
/// messages method to ensure the control only renders unique error messages.
///
/// Utilizes .NET code cleaned from .Peek and reflection to access subclass
/// </summary>
public class UniqueMessageValidationSummary : ValidationSummary
{
internal string[] GetErrorMessages(out bool inError)
{
var strArray = (string[])null;
inError = false;
var length = 0;
var validators = Page.GetValidators(ValidationGroup);
for (var index = 0; index < validators.Count; ++index)
{
var validator = validators[index];
if (!validator.IsValid)
{
inError = true;
if (validator.ErrorMessage.Length != 0)
++length;
}
}
if (length != 0)
{
strArray = new string[length];
var index1 = 0;
for (var index2 = 0; index2 < validators.Count; ++index2)
{
var validator = validators[index2];
if (!validator.IsValid && !string.IsNullOrEmpty(validator.ErrorMessage))
{
strArray[index1] = string.Copy(validator.ErrorMessage);
++index1;
}
}
}
var uniqueErrors = new List<string>();
if (strArray != null)
{
var objRegExp = new Regex("<(.|\n)+?>");
foreach (var error in strArray)
{
if (uniqueErrors.All(x => objRegExp.Replace(error, string.Empty) != objRegExp.Replace(x, String.Empty)))
{
uniqueErrors.Add(error);
}
}
}
return uniqueErrors.ToArray();
}
protected override void Render(HtmlTextWriter writer)
{
var renderUplevelCopy = true;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var baseType = GetType().BaseType;
if (baseType != null)
{
var field = baseType.GetField("renderUplevel", flags);
if (field != null)
renderUplevelCopy = (bool)field.GetValue(this);
}
string[] strArray;
bool flag1;
if (DesignMode)
{
flag1 = true;
renderUplevelCopy = false;
strArray = new[]
{
"ValSummary_error_message_1",
"ValSummary_error_message_2"
};
}
else
{
if (!Enabled)
return;
bool inError;
strArray = GetErrorMessages(out inError);
flag1 = ShowSummary && inError;
if (!flag1 && renderUplevelCopy)
Style["display"] = "none";
}
if (Page != null)
Page.VerifyRenderingInServerForm(this);
var flag2 = renderUplevelCopy || flag1;
if (flag2)
RenderBeginTag(writer);
if (flag1)
{
string text1;
string str1;
string str2;
string text2;
string text3;
switch (DisplayMode)
{
case ValidationSummaryDisplayMode.List:
text1 = "b";
str1 = string.Empty;
str2 = string.Empty;
text2 = "b";
text3 = string.Empty;
break;
case ValidationSummaryDisplayMode.SingleParagraph:
text1 = " ";
str1 = string.Empty;
str2 = string.Empty;
text2 = " ";
text3 = "b";
break;
default:
text1 = string.Empty;
str1 = "<ul>";
str2 = "<li>";
text2 = "</li>";
text3 = "</ul>";
break;
}
if (HeaderText.Length > 0)
{
writer.Write(HeaderText);
WriteBreakIfPresent(writer, text1);
}
if (strArray != null)
{
writer.Write(str1);
foreach (var t in strArray)
{
writer.Write(str2);
writer.Write(t);
WriteBreakIfPresent(writer, text2);
}
WriteBreakIfPresent(writer, text3);
}
}
if (!flag2)
return;
RenderEndTag(writer);
}
private static void WriteBreakIfPresent(HtmlTextWriter writer, string text)
{
if (text == "b")
{
writer.WriteBreak();
}
else
writer.Write(text);
}
}