Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Show BOLD text in ListBox

$
0
0

I want that row with the word 'Total' in BOLD, how do I do that?
see http://imagedrop.co/img-52c6703a72af5

also, I want the Average value of both of the Utilisation. How to get the average of Utilisation? I try with Utilisation1.Average() and Utilisation2.Average(), it complains of

System.FormatException was unhandled
  HResult=-2146233033
  Message=Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
  Source=mscorlib
  StackTrace:
  at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
  at System.String.Format(IFormatProvider provider, String format, Object[] args)
  at System.IO.TextWriter.WriteLine(String format, Object[] arg)
  at TestSystemUtilisation.MainWindow.<>c__DisplayClass5.<bw_DoWork>b__0() in C:\DriveD\TESTS4WORK\TestSystemUtilisation\MainWindow.xaml.cs:line 226
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.DispatcherOperation.InvokeImpl()
  at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Windows.Threading.DispatcherOperation.Invoke()
  at System.Windows.Threading.Dispatcher.ProcessQueue()
  at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
  at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
  at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
  at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.Run()
  at System.Windows.Application.RunDispatcher(Object ignore)
  at System.Windows.Application.RunInternal(Window window)
  at System.Windows.Application.Run(Window window)
  at System.Windows.Application.Run()
  at TestSystemUtilisation.App.Main() in C:\DriveD\TESTS4WORK\TestSystemUtilisation\obj\x86\Debug\App.g.cs:line 0
  at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
  at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

code is attached below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Globalization;
using System.IO;
using System.ComponentModel;
using System.Windows.Threading;

namespace TestSystemUtilisation
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string path1 = @"C:\DriveD\TESTS4WORK\TestSystemUtilisation\CostCenter\";
        string path = @"C:\DriveD\TESTS4WORK\TestSystemUtilisation\";
        string outputfilename = "Utilisation.txt";
        string[] CostCenterName = {"Analog", "Digital", "EMS", "INT1", "INT2", "INT3", "Photo", "SMT", "US-PF", "US-PXS"};
        string[] CostCenterNumber = {"130300", "130400", "110100", "130500", "130600", "130650", "120200", "190235", "120300", "120301"};

        private BackgroundWorker worker = new BackgroundWorker();
    
        public MainWindow()
        {
            InitializeComponent();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(bw_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);           
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] formats = { "dd/MM/yyyy" };
            var defaultDT_Start = DateTime.ParseExact("01/12/2013", formats, new CultureInfo("en-US"), DateTimeStyles.None);
            DateTimePicker_Start.Value = defaultDT_Start;
            var defaultDT_End = DateTime.ParseExact("01/12/2013", formats, new CultureInfo("en-US"), DateTimeStyles.None);
            DateTimePicker_End.Value = defaultDT_End;
            Update_ListBoxTestSystemsDefault();
            string[] hr = { "Whole Day", "Day Shift w/o OT", "Night Shift w/o OT", "Day Shift with OT", "Night Shift with OT","Day Shift w/o OT + Night Shift w/o OT", "Day Shift w/o OT + Night Shift with OT","Night Shift w/o OT + Day Shift with OT", "Day Shift with OT + Night Shift with OT"};
            comboBox_Base.ItemsSource = hr.ToList();
            comboBox_CostCenter.ItemsSource = CostCenterName.ToList();
        }
        private void Update_ListBoxTestSystemsDefault()
        {
            listBox_TestSystems.Items.Clear();
            string outputfilename = "Analog.txt";
            FileInfo file = new FileInfo(string.Concat(path1, outputfilename));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_TestSystems.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void comboBox_CostCenter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex = comboBox_CostCenter.SelectedIndex;
            listBox_TestSystems.Items.Clear();
            label_CostCenter.Content = CostCenterNumber[selectedIndex];
            FileInfo file = new FileInfo(string.Concat(path1, CostCenterName[selectedIndex],".txt"));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_TestSystems.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void comboBox_Base_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex = comboBox_Base.SelectedIndex;
            string[] hr = { "24", "8.8", "8.5", "11.55", "11.5", "17.3", "20.3", "20.05", "23.05" };
            string[] duration = { "00:00 AM - 11:59 PM", "07:30 AM - 05:00 PM", "11:00 PM - 07:45 AM", "07:30 AM - 08:00 PM", "08:00 PM - 07:45 AM","07:30 AM - 05:00 PM + 11:00 PM - 07:45 AM", "07:30 AM - 05:00 PM + 08:00 PM - 07:45 AM", "11:00 PM - 07:45 AM + 07:30 AM - 08:00 PM","07:30 AM - 08:00 PM + 08:00 PM - 07:45 AM" };

            if (comboBox_Base.SelectedIndex == selectedIndex)
                label_Base.Content = hr[selectedIndex];
                label_Duration.Content = duration[selectedIndex];
        }

        private void Update_ListBoxUtilisation()
        {  
            listBox_Utilisation.Items.Clear();
         
            FileInfo file = new FileInfo(string.Concat(path, outputfilename));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_Utilisation.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void Query_Click(object sender, RoutedEventArgs e)
        {
            textBox_Status.Text = "";
            textBox_Status.Text = "In progress ...";
            listBox_Utilisation.Items.Clear();

            if (worker.IsBusy != true)
            {
                worker.RunWorkerAsync();
            }            
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter adapter = new TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter();
            TS_UtilisationDataSet.PPL_TESTSYSTEMS_UTILISATIONDataTable table = adapter.GetData();

            StreamWriter sw = new StreamWriter(string.Concat(path, outputfilename));
            string header1 = "   Date     SystemType  Testtime    Waittime    Systemtime     Utilisation (%)          Utilisation (%)";
            string header2 = "                                                             (Test, System time)   (Test, Wait, System time)";
            string header3 = "==========  ==========  ========    ========    ==========   ===================   =========================";
            sw.WriteLine(header1);
            sw.WriteLine(header2);
            sw.WriteLine(header3);

            var SelectedTestSystems = new List<string>();
            var Testtime = new List<Int32>();
            var Waittime = new List<Int32>();
            var Systemtime = new List<Int32>();
            var Utilisation1 = new List<double>();
            var Utilisation2 = new List<double>();
            var Date = new List<DateTime>();

            Int32 Testtime_hr, Testtime_min;
            Int32 Waittime_hr, Waittime_min;
            Int32 Systemtime_hr, Systemtime_min; 
            worker.ReportProgress(10);
            System.Threading.Thread.Sleep(1000);

            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                string[] formats = { "dd/MM/yyyy" };
                var Start = DateTime.ParseExact(DateTimePicker_Start.Text.ToString(), formats, new CultureInfo("en-US"), DateTimeStyles.None);
                var End = DateTime.ParseExact(DateTimePicker_End.Text.ToString(), formats, new CultureInfo("en-US"), DateTimeStyles.None);
                foreach (var arr in listBox_TestSystems.SelectedItems)
                {
                    SelectedTestSystems.Add(arr.ToString());
                }
                TimeSpan ts = End - Start;
                int DifferenceInDays = ts.Days;
                double DifferenceInHours = ts.Hours + ts.Minutes / 60.0;

                for (int i = 0; i < SelectedTestSystems.Count(); i++)
                {
                    Testtime.Clear();
                    Waittime.Clear();
                    Systemtime.Clear();
                    Utilisation1.Clear();
                    Utilisation2.Clear();

                    for (int d = 0; d <= DifferenceInDays; d++)
                    {
                        DateTime START = Start.AddDays(d).AddHours(0);
                        DateTime END = START.AddHours(24);

                        IEnumerable<DataRow> query =
                        from row in table.AsEnumerable()
                        where (row.Field<string>("SYSTEMTYPE") == SelectedTestSystems[i]) && (row.Field<DateTime?>("TS_START") > START) && (row.Field<DateTime?>("TS_END") < END)
                        select row;

                        int count = query.Count();
                        var TimeTest = query.Select(row => row.Field<Decimal?>("TIME_TEST")).Sum();
                        var TimeWait = query.Select(row => row.Field<Decimal?>("TIME_WAIT")).Sum();
                        var TimeSystem = query.Select(row => row.Field<Decimal?>("TIME_SYSTEM")).Sum();

                        decimal? hr_per_day = Convert.ToDecimal(label_Base.Content.ToString());

                        decimal? Utilisation_1 = (TimeTest + TimeSystem) * 100 / (hr_per_day * 3600);
                        decimal? Utilisation_2 = (TimeTest + TimeSystem + TimeWait) * 100 / (hr_per_day * 3600);

                        Testtime.Add(Convert.ToInt32(TimeTest));
                        Waittime.Add(Convert.ToInt32(TimeWait));
                        Systemtime.Add(Convert.ToInt32(TimeSystem));

                        Utilisation1.Add(Convert.ToDouble(Utilisation_1));
                        Utilisation2.Add(Convert.ToDouble(Utilisation_2));

                        Date.Add(START);

                        Testtime_hr = Testtime[d] / 3600;
                        Testtime_min = Testtime[d] / 60 - Testtime_hr * 60;
                        Waittime_hr = Waittime[d] / 3600;
                        Waittime_min = Waittime[d] / 60 - Waittime_hr * 60;
                        Systemtime_hr = Systemtime[d] / 3600;
                        Systemtime_min = Systemtime[d] / 60 - Systemtime_hr * 60;

                        sw.WriteLine("{0,8}{1,9}{2,12}{3,11}{4,13}{5,18}{6,26}", Date[d].ToString().Replace("12:00:00 AM",""), SelectedTestSystems[i],
                                        string.Concat(Testtime_hr, "h ", Testtime_min, "min"),
                                        string.Concat(Waittime_hr, "h ", Waittime_min, "min"),
                                        string.Concat(Systemtime_hr, "h ", Systemtime_min, "min"),
                                        string.Format("{0:N2}", Utilisation1[d]), string.Format("{0:N2}", Utilisation2[d]));

                    }
                    
                    Testtime_hr = Testtime.Sum() / 3600;
                    Testtime_min = Testtime.Sum() / 60 - Testtime_hr * 60;
                    Waittime_hr = Waittime.Sum() / 3600;
                    Waittime_min = Waittime.Sum() / 60 - Waittime_hr * 60;
                    Systemtime_hr = Systemtime.Sum() / 3600;
                    Systemtime_min = Systemtime.Sum() / 60 - Systemtime_hr * 60;

                    sw.WriteLine("{0,8}{1,9}{2,12}{3,11}{4,13}", "Total      ", SelectedTestSystems[i],
                                    string.Concat(Testtime_hr, "h ", Testtime_min, "min"),
                                    string.Concat(Waittime_hr, "h ", Waittime_min, "min"),
                                    string.Concat(Systemtime_hr, "h ", Systemtime_min, "min"));
                              //      string.Format("{0:N2}", Utilisation1, string.Format("{0:N2}", Utilisation2)));
                    sw.WriteLine();
                }

                sw.Close();
                Update_ListBoxUtilisation();
            }));
        }
   
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                textBox_Status.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                textBox_Status.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                textBox_Status.Text = "Completed.";
            }
        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBox_Status.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>