Proper use of get_range to make a chart - c#

I am using the following code to attempt to make a charge and it is throwing a com exception. I am attempting to make a chart. Is there something obvious my code is doing wrong? The error is thrown on the get_range line.
static void makechart(int counter, int startcount, Worksheet sourcesheet)
{
Range chartrange;
string rangestr = "G" + startcount.ToString() + ":G" + counter.ToString() + ",I" + startcount.ToString() + ":I" + counter.ToString();
ChartObjects xlcharts = (ChartObjects)sourcesheet.ChartObjects(Type.Missing);
ChartObject myChart = (ChartObject)xlcharts.Add(10, 80, 300, 250);
Chart chartPage = myChart.Chart;
chartrange = objsheet.get_Range(rangestr,Type.Missing);
//chartrange = sourcesheet.get_Range("G1", "B" + counter + 1);
chartPage.SetSourceData(chartrange, Type.Missing);
chartPage.ChartType = XlChartType.xlBarClustered;
}

This should work:
Replace:
string rangestr = "G" + startcount.ToString() + ":G" + counter.ToString() + ",I" + startcount.ToString() + ":I" + counter.ToString();
with:
string range1 = "G" + startcount.ToString() + ":G" + counter.ToString();
string range2 = "I" + startcount.ToString() + ":I" + counter.ToString();
and
chartrange = objsheet.get_Range(rangestr,Type.Missing);
with:
chartrange = objsheet.get_Range(range1,range2);

Related

Way too slow C# Console application. Any way to speed it up?

I am currently developing a little program that goes through an excel file and escalate things by e-mail, and shows the progress of the materials in a "progress bar" inside the excel.
The program runs just fine, does all the things it intended to do but its way too slow.
For about 11 rows it takes like 3 minutes.
The file will have more and more (couple hunderd) lines eventually and it will take forever to update.
Do you guys know any way to speed this up?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Prod_Tracking
{
class Program
{
static void Main(string[] args)
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
string rootPath = Directory.GetCurrentDirectory();
string path = rootPath + "\\ProdTracking.xlsx";
string email1 = "email#email.com";
string email2 = "email#email.com";
string body;
string subject;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet tracking = excel.Sheets["Tracking"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet coois = excel.Sheets["COOIS"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet line = excel.Sheets["Line"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet stat = excel.Sheets["Stat"] as Microsoft.Office.Interop.Excel.Worksheet;
Excel.Range trackingRange = tracking.UsedRange;
int mainRows = trackingRange.Rows.Count; //row number of main sheet
coois.Select(true);
Excel.Range cooisRange = coois.UsedRange;
int cooisRows =cooisRange.Rows.Count; //row number of coois sheet
line.Select(true);
Excel.Range lineRange = line.UsedRange;
int lineRows = lineRange.Rows.Count; //row number of line sheet
line.Select(true);
Excel.Range statRange = stat.UsedRange;
int statRows = statRange.Rows.Count; //row number of stat sheet
DateTime thisDay = DateTime.Today;
int days = 0;
int daysofescalation = 0;
for (int i = 3; i <= mainRows; i++)
{
double percent = (i - 2) * 100 / (mainRows - 1); //progress percentage
Console.Clear();
Console.Write("Update in progress! Please wait..." + '\n' + percent + "%" );
for(int j = 2; j <= cooisRows; j++)
{
//get data from COOIS
if (coois.Cells[j,1].Value == tracking.Cells[i, 1].Value)
{
tracking.Cells[i, 2].Value = coois.Cells[j, 2].Value;
tracking.Cells[i, 5].Value = coois.Cells[j, 11].Value;
tracking.Cells[i, 7].Value = coois.Cells[j, 8].Value;
tracking.Cells[i, 8].Value = coois.Cells[j, 9].Value;
if ((thisDay - Convert.ToDateTime(tracking.Cells[i, 5].Value)).TotalDays > 0)
{
tracking.Cells[i, 38].Value = (thisDay - Convert.ToDateTime(tracking.Cells[i, 5].Value)).TotalDays; //calculate passed time in days format
days = Convert.ToInt32(tracking.Cells[i, 38].Value);
}
else
{
tracking.Cells[i, 38].Value = "Prod not yet started";
}
//A/B/C
if (Convert.ToString(tracking.Cells[i,2].Value).Length > 12)
{
tracking.Cells[i, 3].Value = "A";
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(21);
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Range["AF" + i + ":" + "AK" + i].Interior.ColorIndex = 1; //insert black part
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days > 21)
{
tracking.Range["J" + i + ":" + "AE" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
if(Convert.ToString(tracking.Cells[i, 2].Value).Length == 12)
{
tracking.Cells[i, 3].Value = "B";
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(13);
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Range["W" + i + ":" + "AK" + i].Interior.ColorIndex = 1; //insert black part
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days >= 13)
{
tracking.Range["J" + i + ":" + "V" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
if (Convert.ToString(tracking.Cells[i, 2].Value)[0] == '5')
{
tracking.Cells[i, 3].Value = "C";
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(28);
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days > 28)
{
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
//get current production status
for (int l = 2; l <= statRows; l++)
{
if(tracking.Cells[i,1].Value == stat.Cells[l,1].Value && stat.Cells[l, 7].Value != null)
{
tracking.Cells[i, 9].value = Convert.ToString(stat.Cells[l, 4].Value);
l = statRows + 1;
}
}
//Get lines (way too slow, need to be optimised, maybe import it to a list?)
for (int k = 2; k <= lineRows; k++)
{
if (tracking.Cells[i, 2].Value == line.Cells[k, 1].Value)
{
tracking.Cells[i, 4].Value = line.Cells[k, 2].Value;
k = lineRows + 1;
}
}
if (tracking.Cells[i, 4].Value == null)
{
tracking.Cells[i, 4].Value = "NA";
}
//overdue status "YES" or "NO"
if(tracking.Cells[i, 10].Interior.ColorIndex == 3)
{
tracking.Cells[i, 39].Value = "Yes";
}
else
{
tracking.Cells[i, 39].Value = "No";
}
//escalation level one, making the body into a string, sending email and writing in the date of the escalation
if(tracking.Cells[i, 39].Value == "Yes" && tracking.Cells[i, 40].Value == null && tracking.Cells[i, 42].Value != "x")
{
body = "Dear Recipient," + "\n\nThe production order: " + Convert.ToString(tracking.Cells[i, 1].Value) + " for the material " + Convert.ToString(tracking.Cells[i, 2].Value) + " is overdue." + "\nOrdered quantity: " + Convert.ToString(tracking.Cells[i, 7].Value) + "\nConfirmed quantity: " + Convert.ToString(tracking.Cells[i, 8].Value) + "\nPlease take some actions." + "\n\n\n\nThis is an automatically generated message by the production tracking tool";
subject = Convert.ToString(tracking.Cells[i, 1].Value) + " production order is overdue - Escalalation I.";
Program.SendEMail(email1, subject, body);
tracking.Cells[i, 40].Value = thisDay;
}
//escalation level2
if (tracking.Cells[i, 40].Value != null)
{
daysofescalation = Convert.ToInt32((thisDay - Convert.ToDateTime(tracking.Cells[i, 40].Value)).TotalDays);
if(daysofescalation > 8 && tracking.Cells[i, 42].Value != "x" && tracking.Cells[i, 41].Value != null)
{
body = "Dear Recipient," + "\n\nThe production order: " + Convert.ToString(tracking.Cells[i, 1].Value) + " for the material " + Convert.ToString(tracking.Cells[i, 2].Value) + " is overdue." + "\nOrdered quantity: " + Convert.ToString(tracking.Cells[i, 7].Value) + "\nConfirmed quantity: " + Convert.ToString(tracking.Cells[i, 8].Value) + "\nPlease take some actions." + "\n\n\n\nThis is an automatically generated message by the production tracking tool";
subject = Convert.ToString(tracking.Cells[i, 1].Value) + " production order is overdue - Escalalation II.";
Program.SendEMail(email2, subject, body);
tracking.Cells[i, 41].Value = thisDay;
}
}
j = cooisRows + 1;
}
}
}
wb.Close(true);
excel.Quit();
Console.Clear();
Console.WriteLine("Update in progress!Please wait..." + '\n' + "100" + " % " + "\nExcel updated!");
Console.ReadLine();
}
static void SendEMail(string email, string subject, string body)
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = subject;
mailItem.To = email;
mailItem.Body = body;
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
((Outlook._MailItem)mailItem).Send();
}
}
}
Thank you so much for the help in advance,
-B

C# My form objects don't work properly after application running a while

I have 2 pictureboxes and a couple of labels and buttons in my form. The application reads variables from a PLC to draw a graph on pictureboxes and checks if any alarm has been occured by reading variables from PLC. I have 3 timers working at 0.5, 1 and 30 seconds interval for each one. After a while, pictureboxes go invalid. I mean red rectangle on white background by invalid. Buttons don't work. I run application from exe built by debug mode. No errors or exceptions have been occured. Should i refresh my form by my code? Should i enable double buffering property? Or what else should i do? Thanks for your time.
Best regards,
Bee-
Note: Before some changes the app worked around a week. And it was all ok. Changes are: 2 timers added(0.5 and 1 sec interval) and added a picturebox.
Edit: When i go debug mode, i figured out that picturebox.Invalidate() commands doesn't refresh picturebox. After invalidate command, debugger didn't hit paint event method. And also buttons creates form object but can't show it. I think there is something wrong with graphics/rendering. I'm just a beginner and thanks for your help. Codes below:
Reading values to create graph and invalidate pictureboxes:
private void timerCommunication_Tick(object sender, EventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
string info = adsClient.ReadDeviceInfo().ToString();
float ActData = (float)adsClient.ReadAny(16416, 200, typeof(float));
textBox1.Text = Convert.ToString(ActData);
string[] vs = new string[9];
string[] vs1 = new string[6];
if (DateTime.Now.Hour < 10)
vs[0] = "0" + DateTime.Now.Hour.ToString() + ":";
else
vs[0] = DateTime.Now.Hour.ToString() + ":";
if (DateTime.Now.Minute < 10)
vs[0] += "0" + DateTime.Now.Minute.ToString();
else
vs[0] += DateTime.Now.Minute.ToString();
vs[1] = Convert.ToString(ActData);
vs1[0] = vs[0];
ActData = (float)adsClient.ReadAny(16416, 216, typeof(float));
vs1[1] = Convert.ToString(ActData);
float PrmUpperLimit = Global_Variables.PrmSetValue + Global_Variables.PrmAlarm + Global_Variables.PrmWarning + Global_Variables.PrmMaxMin;
float PrmLowerLimit = Global_Variables.PrmSetValue - Global_Variables.PrmAlarm - Global_Variables.PrmWarning - Global_Variables.PrmMaxMin;
float PrmSet = Global_Variables.PrmSetValue;
float PrmUpperWarning = Global_Variables.PrmSetValue + Global_Variables.PrmWarning;
float PrmLowerWarning = Global_Variables.PrmSetValue - Global_Variables.PrmWarning;
float PrmUpperAlarm = PrmUpperWarning + Global_Variables.PrmAlarm;
float PrmLowerAlarm = PrmLowerWarning - Global_Variables.PrmAlarm;
float OvlUpperLimit = Global_Variables.OvlSetValue + Global_Variables.OvlAlarm + Global_Variables.OvlWarning + Global_Variables.OvlMaxMin;
float OvlSet = Global_Variables.OvlSetValue;
float OvlUpperWarning = Global_Variables.OvlSetValue + Global_Variables.OvlWarning;
float OvlUpperAlarm = OvlUpperWarning + Global_Variables.OvlAlarm;
vs[2] = Convert.ToString(PrmUpperLimit);
vs1[2] = Convert.ToString(OvlUpperLimit);
vs[3] = Convert.ToString(PrmUpperAlarm);
vs1[3] = Convert.ToString(OvlUpperAlarm);
vs[4] = Convert.ToString(PrmUpperWarning);
vs1[4] = Convert.ToString(OvlUpperWarning);
vs[5] = Convert.ToString(PrmSet);
vs1[5] = Convert.ToString(OvlSet);
vs[6] = Convert.ToString(PrmLowerWarning);
vs[7] = Convert.ToString(PrmLowerAlarm);
vs[8] = Convert.ToString(PrmLowerLimit);
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Archive\\" + Dir);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs1);
picboxPerimeter.Invalidate();
picboxOvality.Invalidate();
}
Picturebox Paint Event:
private void picboxPerimeter_Paint(object sender, PaintEventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
string[] X = new string[2];
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
string path = Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt";
try
{
int index;
string[] ReadLog = System.IO.File.ReadAllLines(path);
float LargestSet = LargestLimit(ReadLog, 5, 0, out index);
float LargestTrend = LargestLimit(ReadLog, 2, 0, out index);
string[] FillLbL = ReadLog[index].Split('|');
string[] myL = ReadLog[index].Split('|');
FillLabelsPrm(FillLbL);
Trend.SetTrendLimits(LargestTrend, float.Parse(myL[8]));
listPerimeter.Clear();
X[0] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\:mm");
X[1] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\:mm");
Trend.Time = X;
string[] unravel = ReadLog[0].Split('|');
Trend.p1 = unravel;
for (int i = 2; i <= ReadLog.Length - 1; i += 2)
{
unravel = ReadLog[i].Split('|');
bool Check = Trend.DrawWholePicture(unravel, sender, e, listPerimeter);
}
}
catch
{
;
}
Point L_ptc = new Point();
L_ptc = picboxPerimeter.PointToClient(new Point(0, 0));
L_ptc = new Point(-L_ptc.X, -L_ptc.Y + picboxPerimeter.Size.Height);
Pen p = new Pen(Color.Black, 1.5f);
Label[] labels = new Label[17];
for (int i = 0; i <= 16; i++)
{
e.Graphics.DrawLine(p, i * picboxPerimeter.Width / 16, 0, i * picboxPerimeter.Width / 16, picboxPerimeter.Height);
labels[i] = new Label();
this.Controls.Add(labels[i]);
labels[i].Location = new Point(L_ptc.X - 15 + i * picboxPerimeter.Width / 16, L_ptc.Y - 15);
labels[i].BackColor = Color.Transparent;
labels[i].Size = new Size(35, 15);
labels[i].BringToFront();
try
{
double archive_sh = Convert.ToDouble(X[0].Substring(0, 2)) * 60 + Convert.ToDouble(X[0].Substring(3));
double archive_sh1 = Convert.ToDouble(X[1].Substring(0, 2)) * 60 + Convert.ToDouble(X[1].Substring(3));
if (archive_sh1 < archive_sh)
archive_sh1 += 24 * 60;
double a = archive_sh1 - archive_sh;
a /= 16.00;
double b = archive_sh;
TimeSpan span = TimeSpan.FromMinutes(b + i * a);
labels[i].Text = span.ToString(#"hh\:mm");
}
catch
{
;
}
}
}
}
The other picturebox' event is the same, the difference is: this one draw graph according to odd numbered lines of txt file and the other draws according to even numbered lines. Adding other timers' tick event methods below, don't know if necessary though.
Timer1; 1 sec interval, checks alarm values from PLC:
private void timer1_Tick(object sender, EventArgs e)
{
lblNotification.Text = "";
if (adsClient.IsConnected == false)
adsClient.Connect(801);
if((bool)adsClient.ReadAny(16417, 1, typeof(bool)))
{
adsClient.WriteAny(16417, 1, false);
}
if ((bool)adsClient.ReadAny(16417, 2, typeof(bool)))
{
adsClient.WriteAny(16417, 2, false);
}
bool alarm = (bool)adsClient.ReadAny(16416, 1, typeof(bool));
bool alarm1 = (bool)adsClient.ReadAny(16416, 2, typeof(bool));
bool[] myBool = (bool[])adsClient.ReadAny(16416, 400, typeof(bool[]), new int[] { 14 });
//string alarmDir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string alarmDir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Alarm\\" + alarmDir);
//string alarmPath = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string alarmPath = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
int alarmCount = 0;
for (int i=0; i <= myBool.Length - 1; i++)
{
alarmMessage[i] = AlarmLog.GetMessage(i);
if (!alarmisActive[i] && myBool[i])
{
alarmisActive[i] = true;
alarmActiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[i])
{
lblNotification.Text = alarmMessage[i];
alarmisWritten[i] = true;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if(alarmisActive[i] && !myBool[i])
{
if (alarmisWritten[i])
{
alarmisActive[i] = false;
alarmDeactiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmisWritten[i] = false;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
}
bool etherCatAlarm = (bool)adsClient.ReadAny(16417, 7, typeof(bool));
alarmMessage[14] = AlarmLog.GetMessage(14);
if (!alarmisActive[14] && etherCatAlarm)
{
alarmisActive[14] = true;
alarmActiveTime[14]= DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[14])
{
alarmisWritten[14] = true;
alarmFileData = alarmMessage[14]+ "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if (alarmisActive[14] && !etherCatAlarm)
{
if (alarmisWritten[14])
{
alarmisActive[14] = false;
alarmDeactiveTime[14] = DateTime.Now.ToString("HH:mm");
alarmisWritten[14] = false;
alarmFileData = alarmMessage[14] + "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
if(alarmCount > 1)
{
lblNotification.Text = "Multiple alarms are active, check \"Active Alarm\" page...";
}
else if (alarmCount == 1)
{
for (int i = 0; i <= 13; i++)
{
lblNotification.Text = alarmMessage[i];
}
}
}
Timer2; 0.5 sec interval, reads values to show in labels:
private void timer2_Tick(object sender, EventArgs e)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
float[] Actual = (float[])adsClient.ReadAny(16416, 200, typeof(float[]), new int[] { 8 });
lblPerimeterValue.Text = Actual[0].ToString();
lblPerimeterX.Text = Actual[1].ToString();
lblPerimeterY.Text = Actual[2].ToString();
lblOvalityValue.Text = Actual[4].ToString();
lblOvalityX.Text = Actual[5].ToString();
lblOvalityY.Text = Actual[6].ToString();
}

c# how to color each lines in richtextbox

I need to color each line depends on the last char in each string form list. This is my code and it's always make the last line green. What's wrong with it?
List<string> plik = File.ReadAllLines(path).ToList();
string pom;
int size = plik.Count;
richTextBox1.Clear();
for (int i = 0; i < size; i++)
{
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
pom =plik[i];
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
// richTextBox1.Select(0, pom.Length);
if (pom.Substring(pom.Length - 1) == "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) == "n" ? Color.Red :Color.Red;
}
if(pom.Substring(pom.Length - 1) != "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) != "n"?Color.Green:Color.Green;
}
}
just replace
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
by
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
Append the text instead of modifying it in whole. Using += will replace the entire string and hence you'll lose the set color each time. Use AppendText instead.
Also you can remove the unnecessary ifs in your code. This should work:
for (int i = 0; i < size; i++)
{
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
richTextBox1.SelectionBackColor = plik[i][plik[i].Length - 1] == 'n' ? Color.Red : Color.Green;
}

Excel.Range Copy() works very slowly

I'm building a report in which try to copy the previous row cell styles in the following
for (int i = 0; i < DataSource.Length; i++)
{
int rowNumber = i + s;
Excel.Range RngToCopy = ObjWorkSheet.get_Range("A" + rowNumber.ToString(), "K" + rowNumber.ToString());
Excel.Range r = ObjWorkSheet.get_Range("A" + (rowNumber + 1).ToString(), "K" + (rowNumber + 1).ToString());
RngToCopy.Copy(Type.Missing);
r.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
r.PasteSpecial(Excel.XlPasteType.xlPasteFormats,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
ObjWorkSheet.Cells[rowNumber, 1] = i + 1;
ObjWorkSheet.Cells[rowNumber, 2] = DataSource[i].TerminalName;
ObjWorkSheet.Cells[rowNumber, 3] = DataSource[i].Type;
ObjWorkSheet.Cells[rowNumber, 4] = DataSource[i].Requisite;
}
everything works but very long
How can I speed this up?
I think you manually copy you will be improved.
Object[] origData = origRange.Value2;
destRange.Value2 = origData;
That should be WAY faster.

WrapText for column in Excel programmatically

I'm trying to set WrapText property to true with C#.
Range rng = sheet.get_Range("A:A", System.Type.Missing);
rng.EntireColumn.ColumnWidth = 50;
rng.EntireColumn.AutoFit();
rng.EntireRow.AutoFit();
rng.WrapText = true;
but it doesn't work without any exceptions. What's wrong? Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;
//Initial Declarations//
Excel.Workbook destinationXlWorkBook;
Excel.Worksheet destinationXlWorkSheet;
Excel.Application destinationXlApp;
object misValue = System.Reflection.Missing.Value;
//Launch Excel App//
destinationXlApp = new Excel.Application();
//Load WorkBook in the opened Excel App//
destinationXlWorkBook = destinationXlApp.Workbooks.Add(misValue);
//Load worksheet-1 in the workbook//
destinationXlWorkSheet =
(Excel.Worksheet)destinationXlWorkBook.Worksheets.get_Item(1);
//Set Text-Wrap for all rows true//
destinationXlWorkSheet.Rows.WrapText = true;
//Or, set it for specific rows//
destinationXlWorkSheet.Rows[3].WrapText = true;
destinationXlWorkSheet.Rows[5].WrapText = true;
//Edit individual cells//
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
//Save and close the Excel//
destinationXlWorkBook.SaveAs("C:\\Users\\UtkarshSinha\\Documents\\SAP\\text.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//Start quitting and closing Excel//
destinationXlWorkBook.Close(true, misValue, misValue);
destinationXlApp.Quit();
Marshal.ReleaseComObject(destinationXlWorkSheet);
Marshal.ReleaseComObject(destinationXlWorkBook);
Marshal.ReleaseComObject(destinationXlApp);
I am duping A LOT of code here, for my entire solution, TextWrap being one of it. I figure it might come in handy to someone someday.
MAIN PROGRAM:
public int counter;
public void ExportPartsToExcelButton(object sender, RoutedEventArgs e)
{
Type officeType = Type.GetTypeFromProgID("Excel.Application");
if (officeType != null)
{
if (CurrentID != 0)
{
counter = 1;
GeneratePartsXLSX();
}
else
{
MessageBoxEx.Show(this, "No address selected!", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
else
{
MessageBoxEx.Show(this, "Install Microsoft Excel!", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
public void GeneratePartsXLSX()
{
Mouse.OverrideCursor = Cursors.Wait;
string filename = GlobalStrings.building_house_address;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
filename = filename.Replace("/", "+");
if (!File.Exists(path + filename + ".xlsx"))
{
DataGridParts.ExportPartsToExcel(path + filename + ".xlsx"); //You have to include the ".xlsx" extension, otherwise the Office interop detects a possible dot (.) in the file name as an extension. Example: road.block instead of road.block.xlsx
MessageBoxEx.Show(this, "Saved to Desktop");
}
else
{
if (!File.Exists(path + "\\" + filename + " (" + (counter) + ")" + ".xlsx"))
{
DataGridParts.ExportPartsToExcel(path + filename + " (" + (counter) + ")" + ".xlsx");
MessageBoxEx.Show(this, "Saved to Desktop");
}
else
{
counter++;
GeneratePartsXLSX();
}
}
Mouse.OverrideCursor = null;
}
CLASS:
using Microsoft.Office.Interop.Excel;
using System;
using System.Runtime.InteropServices;
namespace SAVETOEXCELPROGRAM
{
public static class ExportToExcel
{
public static void ExportPartsToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
{
int ColumnsCount;
int RowShift = 7;
ColumnsCount = DataTable.Columns.Count;
// load excel, and create a new workbook
Application Excel = new Application();
Excel.Workbooks.Add();
// single worksheet
_Worksheet Worksheet = Excel.ActiveSheet;
Excel.Sheets[1].Name = "WHATEVER";
Worksheet.Columns.NumberFormat = "#"; //Force the "Text" format, so that 1/2 won't get converted to 1st of February for example
Worksheet.Columns.HorizontalAlignment = XlHAlign.xlHAlignLeft; //Text aligment
Worksheet.Columns.VerticalAlignment = XlHAlign.xlHAlignCenter; //Text aligment
object[,] Title = new object[5, 1]; //Array range starts at [1,1], the content index starts at [0,0]
if (GlobalStrings.building_alterantive_addresses.Length == 0)
{
if (GlobalStrings.building_postcode.Length != 0)
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
}
else
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", " + GlobalStrings.building_plot_number;
}
}
else
{
if (GlobalStrings.building_postcode.Length != 0)
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
Title[4, 0] = "LOOK ALSO: " + GlobalStrings.building_alterantive_addresses;
}
else
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
Title[4, 0] = "LOOK ALSO: " + GlobalStrings.building_alterantive_addresses;
}
}
Range TitleRange = Worksheet.get_Range((Range)(Worksheet.Cells[5, 1]), (Range)(Worksheet.Cells[1, 1]));
TitleRange.Value = Title;
TitleRange.Font.Bold = true;
TitleRange.Font.Size = 10;
object[] Header = new object[14]; //Number of Headers
Header[0] = "PART";
Header[1] = "SHARE";
Header[2] = "CRP";
Header[3] = "+/-";
Header[4] = "OWNER";
Header[5] = "ADDRESS";
Header[6] = "POSTCODE";
Header[7] = "AREA";
Header[8] = "COUNTRY";
Header[9] = "SOCIAL";
Header[10] = "TYPE";
Header[11] = "DESCRIPTION";
Header[12] = "COMMENT";
Header[13] = "CODE";
int MaxCol = Header.Length;
Range HeaderRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift, 2]), (Range)(Worksheet.Cells[RowShift, MaxCol + 1])); //MaxCol+1, because we have to shift the Array position by 1, as the first column is set to "ColumnWidth = 0.1"
HeaderRange.Value = Header;
HeaderRange.Font.Bold = true;
HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
HeaderRange.Borders.LineStyle = XlLineStyle.xlContinuous;
// DataCells
int RowsCount = DataTable.Rows.Count;
object[,] Cells = new object[RowsCount, ColumnsCount]; //Array range starts at [1,1], the content index starts at [0,0]
for (int j = 0; j < RowsCount; j++)
{
for (int i = 3; i <= ColumnsCount - 2; i++) //With this you control the data range, starts with 0, you can exclude data with an " if (i != 0 && i != 1 && ... && i= 5)
{
Cells[j, i - 3] = DataTable.Rows[j][i]; //with i you control the horizontal placement of the data in the worksheet
}
}
Range CellRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift + 1, 2]), (Range)(Worksheet.Cells[RowShift + RowsCount, MaxCol + 1])); //MaxCol+1, because we have to shift the Array position by 1, as the first column is set to "ColumnWidth = 0.1"
CellRange.Value = Cells;
CellRange.Borders.LineStyle = XlLineStyle.xlContinuous;
Worksheet.Columns[1].ColumnWidth = 0.1; //If this was set on AutoFit the Column 1 would get extended to the Title Width, because they share the column.
Worksheet.Columns[2].ColumnWidth = 3;
Worksheet.Columns[3].ColumnWidth = 4;
Worksheet.Columns[4].ColumnWidth = 3;
Worksheet.Columns[5].ColumnWidth = 2;
Worksheet.Columns[6].ColumnWidth = 13;
Worksheet.Columns[7].ColumnWidth = 15;
Worksheet.Columns[8].ColumnWidth = 4;
Worksheet.Columns[9].ColumnWidth = 8;
Worksheet.Columns[10].ColumnWidth = 6;
Worksheet.Columns[11].ColumnWidth = 10;
Worksheet.Columns[12].ColumnWidth = 18;
Worksheet.Columns[13].ColumnWidth = 16;
Worksheet.Columns[14].ColumnWidth = 18;
Worksheet.Columns[MaxCol + 1].ColumnWidth = 15; //Set the Width of the last Column
for (int b = 2; b <= MaxCol; b++) //If we wanted to include the "Header[14]", we would have to set MaxCol+1, because the Array (not the DataTable) is shifted by +1. These are Excel Worksheet settings!
{
Worksheet.Columns[b].WrapText = true;
//Worksheet.Columns[b].AutoFit();
}
for (int b = 2; b <= MaxCol + 1; b++)
{
Worksheet.Columns[b].Font.Size = 7;
}
Worksheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
Worksheet.PageSetup.TopMargin = 0.5;
Worksheet.PageSetup.BottomMargin = 0.5;
Worksheet.PageSetup.RightMargin = 0.5;
Worksheet.PageSetup.LeftMargin = 0.5;
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
Worksheet.SaveAs(ExcelFilePath);
Excel.Quit();
Marshal.FinalReleaseComObject(Worksheet);
Marshal.FinalReleaseComObject(TitleRange);
Marshal.FinalReleaseComObject(HeaderRange);
Marshal.FinalReleaseComObject(CellRange);
Marshal.FinalReleaseComObject(Excel);
}
else
// no filepath is given
{
Excel.Visible = true;
}
}
}
}
workSheet.Cells["A1:T1"].Style.WrapText = true;

Categories

Resources