WPF Memory Leak Causes

I've been having problems with memory leaks in my WPF app for weeks now and can' find the cause.

Using ANTS or .NET memory proiler, the leak always seems to be in the Private bytes, so I guess this is related to unmanaged resources.

I'm new to all .NET, especially WPF, so this has been a massive learning curve. I've attached a sample of my code below to show how I'm declaring all of my usable items for use within the voids. I've also included a sample public void to show I'm using the variables.

Is this the correct way of handling global strings, Doubles etc..?

I'd appreciate some advice and guidance here, as I really can't figure out where my leak is coming from.

Basically MainWindow1.xaml has a Frame, that navigates to Mainpage.Xaml when loaded. The OnLoaded Event of the MainPage fires an event handler for timer_tick, which increment an int called count. Every 10secs the timer_tick runs, changes images, text and charts on the page.

If you want to see the full code with Xaml, I can post it here as well.

public partial class MainPage : Page
    {
            InitializeComponent();
            Chart1.AnimationEnabled = false;
            Chart1.AnimatedUpdate = false;

            Chart2.AnimationEnabled = false;
            Chart2.AnimatedUpdate = false;
            DataSeries dataSeries = new DataSeries();
            DataSeries dataSeries2 = new DataSeries();
            DataSeries dataSeries3 = new DataSeries();
            DataSeries dataSeries4 = new DataSeries();
           
            // Attach a Loaded event to chart in order to attach a timer's Tick event
            //Chart1.Loaded += new RoutedEventHandler(chart_Loaded);
            
            txtCO2.UndoLimit = 0;
            txtCost.UndoLimit = 0;
            txtElecPower.UndoLimit = 0;
            txtStatus.UndoLimit = 0;
            

            
            dataSeries.RenderAs = RenderAs.Column;
            dataSeries2.RenderAs = RenderAs.Column;
            Chart1.Series.Add(dataSeries);
            Chart2.Series.Add(dataSeries2);

        System.Windows.Threading.DispatcherTimer timer = new    // Create a new instance of timer object
        System.Windows.Threading.DispatcherTimer();

        private static List<DateTime> dt;
        //OdbcCommand DbCommand;
        private static GetDailyData day = new GetDailyData();
        private static DataTable ElecDayData = null;
        private static DataTable ElecPrevDayData = null;
        private static DataTable GasDayData = null;
        private static DataTable GasPrevDayData = null;
        private static GetMonthlyData month = new GetMonthlyData();
        private static GetLiveData LiveDataRefs = new GetLiveData();
        private static GetTempData TempDAC = new GetTempData();
        private static DataTable TempDT = null;
        private static DataTable OAT_DT = null;
        private static int GasMeter = 0;
        private static int ElecMeter = 0;
        private static string CO2Multiplier = string.Empty;
        private static string CarbonMultiplier = string.Empty;
        private static string sDate = DateTime.Now.ToShortDateString();
        private static string sDate2 = DateTime.Now.AddDays(-1).ToShortDateString();
        private static Double ElecPower;
        private static Double GasPower;
        private static double ScreenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
        private static double ScreenHeight = System.Windows.SystemParameters.PrimaryScreenWidth;
        private static Int32 NoBuildings = 0; //Used to store Number of Buildings Counted from the Table
        private static int GasAvailable = new int();
        private static int ElecAvailable = new int();
        private static string EleckWObjRef = Settings.Default.ElectricityPowerAV;
        private static string GaskWObjRef = Settings.Default.GasPowerAV;
        private static Double ProCyclistOutput = Convert.ToDouble(Settings.Default.ProCyclistsWattsOutput);
        private static Double LaptopPower = 40;
        private static Double kgCoal = 0.4018;
        private static string ElecCostPerkWh = Settings.Default.ElecCostPerkWh;
        private static string GasCostPerkWh = Settings.Default.GasCostPerkWh;
        private static Double ElecCO2 = Convert.ToDouble(Settings.Default.ElecCO2Multiplier);
        private static Double GasCO2 = Convert.ToDouble(Settings.Default.GasCO2Multiplier);
        private static Double YesterdayGasUsage = new Double();
        private static Double HomeCO2perYear = Convert.ToDouble(Settings.Default.HomeCO2UsagePerYear);
        private static Title GasMonth = new Title();
        private static Title GasPrevMonth = new Title();
        private static Title Chart2Day = new Title();
        private static Title Chart2PrevDay = new Title();
        private static Title ElecMonth = new Title();
        private static Title ElecPrevMonth = new Title();
        private static Title Chart1Day = new Title();
        private static Title Chart1PrevDay = new Title();
        //OdbcConnection DbConnection = new OdbcConnection("DSN=Delta Network");

        private Axis axis = new Axis();
        private Axis Chart1AxisY = new Axis();
        private Axis Chart2AxisY = new Axis();
        private static Uri src1 = new Uri(@"/EnergySuiteViewer;component/Car.jpg", UriKind.Relative);
        private static BitmapImage img1 = new BitmapImage(src1);
        private static Uri src2 = new Uri(@"/EnergySuiteViewer;component/green_home.jpg", UriKind.Relative);
        private static BitmapImage img2 = new BitmapImage(src2);
        
        private static Uri src3 = new Uri(@"/EnergySuiteViewer;component/Lightbulb1.jpg", UriKind.Relative);
        private static BitmapImage img3 = new BitmapImage(src3);
        private static Uri src4 = new Uri(@"/EnergySuiteViewer;component/Flame.jpg", UriKind.Relative);
        private static BitmapImage img4 = new BitmapImage(src4);
        private static Uri src5 = new Uri(@"/EnergySuiteViewer;component/CO2_1.jpg", UriKind.Relative);
        private static BitmapImage img5 = new BitmapImage(src5);
        private static Uri src6 = new Uri(@"/EnergySuiteViewer;component/Coal.jpg", UriKind.Relative);
        private static BitmapImage img6 = new BitmapImage(src6);
        private static Uri src7 = new Uri(@"/EnergySuiteViewer;component/Laptop.jpg", UriKind.Relative);
        private static BitmapImage img7 = new BitmapImage(src7);
        private static Uri src8 = new Uri(@"/EnergySuiteViewer;component/Pound.jpg", UriKind.Relative);
        private static BitmapImage img8 = new BitmapImage(src8);
        private static Double Cars;
        private static Double YesterdayGasCO2;
        private static Double TodayCO2;
        private static Double kgPerGallon = 10.9;
        private static Double MPG = 40;
        private static int count = 0;
        private static Int32 CurrentBuilding = 0; //Used to Iterate through each building
        private static DataTable Refs = null;
        //Create Generic Values for Sending  Data to User Controls
        //These Values are assigned Dynamically from DataTables and sent over to each User Control as Required
        private static String Value1 = string.Empty;
        private static String Value2 = string.Empty;
        private static String Value3 = string.Empty;
        private static String Value4 = string.Empty;
        private static String Value5 = string.Empty;
        private static String Value6 = string.Empty;
        private static String Value7 = string.Empty;
        private static String Value8 = string.Empty;
        private static String Value9 = string.Empty;
        private static String Value10 = string.Empty;
        private static String Value11 = string.Empty;
        private static String Value12 = string.Empty;
        private string[] ElecPowerArray;
        private string[] GasPowerArray;
        private string[] OATArray;
        private string[] Space_TempArray;
        private string[] ElecPowerRefArray;
        private string[] GasPowerRefArray;
        private string[] OATRefArray;
        private string[] Space_TempRefArray;
        private string[] BuildingNoArray;
        private string[] SpaceTempTLInst;
        private string[] OATTLInst;
        private string[] BuildingNameArray;
        private string[] ElecTLRefArray;
        private string[] GasTLRefArray;
public void ODBCData(int Count)
        {
            
            Image transImg1 = new Image();
            Image transImg2 = new Image();
            Image transImg3 = new Image();
            Image transImg4 = new Image();
            Cars = 0;
            YesterdayGasCO2 = 0;
            //if (DeltaDSN == 1)
            //{
                StatuxBox.Visibility = Visibility.Visible;
                myGauge1.Visibility = Visibility.Visible;
                GasGauge.Visibility = Visibility.Visible;
                
                    
                try
                {

                    if (Count == 1)
                    {
                        ElecPower = Convert.ToDouble(ElecPowerArray[CurrentBuilding]);
                        Cars = Math.Round(((TodayCO2 / kgPerGallon) * MPG) / 100, 0);
                        myGauge1.CurrentValue = Math.Round(ElecPower, 0);
                        txtStatus.Text = "Today, this Building has emitted the same CO2 as " + Cars.ToString() + " family Cars covering 100miles";
                        StatuxBox.Header = "Current Status - Electricity";
                        txtCost.Text = (Math.Round(ElecPower * Convert.ToDouble(ElecCostPerkWh), 2)).ToString() + " £/h";
                        txtCO2.Text = (Math.Round(ElecPower * ElecCO2, 0)).ToString() + " kgCO2/h";
                        txtElecPower.Text = Math.Round(ElecPower, 1).ToString() + " kW";
                        transImg1.Source = img1;
                        transImg2.Source = img3;
                        transImg4.Source = img5;

                    }
                    if ((Count == 3)&&(GasAvailable==1))
                    {
                        GasPower = Convert.ToDouble(GasPowerArray[CurrentBuilding]);
                        GasGauge.CurrentValue = Math.Round(GasPower, 0);
                        GasCO2 = Math.Round((YesterdayGasUsage * GasCO2) * HomeCO2perYear, 4);
                        txtStatus.Text = "Yesterday, this Building emitted the equivalent CO2 of  " + YesterdayGasCO2.ToString() + " Households Annual Emissions";
                        StatuxBox.Header = "Current Status - Gas";
                        txtCost.Text = (Math.Round(GasPower * Convert.ToDouble(GasCostPerkWh), 2)).ToString() + " £/h";
                        txtCO2.Text = (Math.Round(GasPower * GasCO2, 0)).ToString() + " kgCO2/h";
                        txtElecPower.Text = Math.Round(GasPower, 1).ToString() + " kW";
                        transImg1.Source = img2;
                        transImg2.Source = img4;
                        transImg4.Source = img5;

                    }
                    if (Count == 5)
                    {
                        ElecPower = Convert.ToDouble(ElecPowerArray[CurrentBuilding]);
                        Cars = Math.Round(((ElecPower * 1000) / LaptopPower), 0);
                        myGauge1.CurrentValue = Math.Round(ElecPower, 0);
                        txtStatus.Text = "Today this Building has used the Equivalent Power of " + Cars.ToString() + " 40-Watt Laptop(s) per hour";
                        StatuxBox.Header = "Current Status - Electricity";
                        txtCost.Text = (Math.Round((ElecPower * Convert.ToDouble(ElecCostPerkWh)) * 12, 2)).ToString() + " £/Day";
                        txtCO2.Text = (Math.Round((ElecPower * ElecCO2) * kgCoal, 0)).ToString() + " kg Coal/h";
                        txtElecPower.Text = Math.Round(ElecPower, 1).ToString() + " kW";
                        transImg1.Source = img7;
                        transImg2.Source = img3;
                        transImg4.Source = img6;

                    }
                    transImg3.Source = img8;

                }
                catch (Exception ex)
                {
                    string msg = "ODBC Data Collection Error: ";
                    msg += ex.InnerException.ToString(); ;
                    throw new Exception(msg);
                }
                finally
                {
                    TransitionBox.Content = transImg1;
                    TransitionBox2.Content = transImg2;
                    TransitionBox3.Content = transImg3;
                    TransitionBox4.Content = transImg4;

                }
            //}
            //else
            //{
            //    StatuxBox.Visibility = Visibility.Hidden;
            //    myGauge1.Visibility = Visibility.Hidden;
            //    GasGauge.Visibility = Visibility.Hidden;
            //}

        }
private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            StatuxBox.Visibility = Visibility.Hidden;
            myGauge1.Visibility = Visibility.Hidden;
            GasGauge.Visibility = Visibility.Hidden;
            //DeltaDSNChecker();
            //if (DeltaDSN == 1) DbConnection.Open();

            count = 0;
            GasAvailable = 1;
            ElecAvailable = 1;
            //ElecDataSeries();
            //Call Electricity DataSeries on Load so the Current Status is populated

            timer.Start();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 0, 10, 0);

            GetODBCObjRefs();//Pulls in all Object Refs from Table, only once on startup
            GetODBCObjData();//Pull in Data from Table
            ODBCData(1);//Return ODBC Data on Load
        }
        private void DeltaDSNChecker()
        {
            StringBuilder DSNs = new StringBuilder();
            // fill data source names
            DevToolShed.OdbcDataSourceManager dsnManager = new DevToolShed.OdbcDataSourceManager();
            System.Collections.SortedList dsnList = dsnManager.GetAllDataSourceNames();
            for (int i = 0; i < dsnList.Count; i++)
            {
                string sName = (string)dsnList.GetKey(i);
                DevToolShed.DataSourceType type = (DevToolShed.DataSourceType)dsnList.GetByIndex(i);
                DSNs.Append(sName + " - (" + type.ToString() + " DSN)");
            }
            string[] DSNArray = DSNs.ToString().Split(')');
            DeltaDSN = 0;
            foreach (string s in DSNArray)
            {
                if (s.Contains("Delta Network"))
                {
                    DeltaDSN = 1;
                }
            }
        }

        public void Daily_XAxis_Values()
        {
            Chart1.AxesX.Clear();
            Chart2.AxesX.Clear();
            // Create a new Axis

            //Axis axis2 = new Axis();
            dt = new List<DateTime>();
            try
            {
                dt.Clear();
                DateTime starttime = Convert.ToDateTime("00:00");
                dt.Add(starttime);
                DateTime test = starttime;


                // Set axis properties
                axis.IntervalType = IntervalTypes.Auto;
                axis.Interval = 4;
                axis.Title = "Time";
                // Add axis to AxesX collection
                Chart1.AxesX.Add(axis);
                Chart2.AxesX.Add(axis);
                for (int i = 0; i < 96; i++)
                {
                    test = test.AddMinutes(15);

                    dt.Add(test);
                }
            }
            catch { }
            finally
            {

            }
        }
        public void Monthly_XAxis_Values()
        {


            // Set axis properties

            axis.IntervalType = IntervalTypes.Auto;
            axis.Interval = 1;
            axis.Title = "Date";
            // Add axis to AxesX collection
            Chart1.AxesX.Clear();
            Chart2.AxesX.Clear();
            Chart1.AxesX.Add(axis);
            Chart2.AxesX.Add(axis);

        }
        public static void MinimizeMemory()
        {
              
            GC.Collect(GC.MaxGeneration);
            GC.WaitForPendingFinalizers();
            SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF);

            IntPtr heap = GetProcessHeap();

            if (HeapLock(heap))
            {
                try
                {
                    if (HeapCompact(heap, 0) == 0)
                    {
                        // error condition ignored 
                    }
                }
                finally
                {
                    HeapUnlock(heap);
                }
            }
        }
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetProcessWorkingSetSize(IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr GetProcessHeap();
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool HeapLock(IntPtr heap);
        [DllImport("kernel32.dll")]
        internal static extern uint HeapCompact(IntPtr heap, uint flags);
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool HeapUnlock(IntPtr heap);

        /// <summary>
        /// Function to create a chart
        /// </summary>
        /// 
        public void DailyElecDataSeries()
        {
            using (LINQEnergySuiteDataContext db = new LINQEnergySuiteDataContext())
            {
                var Carbon = from s in db.MeterLists
                             where s.MeterInstance == ElecMeter
                             select new
                             {
                                 s.CarbonMultiplier,
                                 s.CO2Multiplier
                             };

                foreach (var d in Carbon)
                {
                    CO2Multiplier = d.CO2Multiplier.ToString();
                    CarbonMultiplier = d.CarbonMultiplier.ToString();
                }
            }
            sDate = DateTime.Now.ToShortDateString();
            sDate2 = DateTime.Now.AddDays(-1).ToShortDateString();


            
            try
            {
                ElecDayData = day.DailyData(ElecMeter, sDate);
                ElecPrevDayData = day.DailyData(ElecMeter, sDate2);

                if (ElecDayData.Compute("sum(DataDiff)", "") != DBNull.Value)
                {
                    Value1 = Decimal.Round((Convert.ToInt32((ElecDayData.Compute("sum(DataDiff)", "")))), 2).ToString() + " kWh";
                    Value2 = (Decimal.Round((Convert.ToInt32((ElecDayData.Compute("sum(DataDiff)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value3 = (Decimal.Round((Convert.ToInt32((ElecDayData.Compute("sum(DataDiff)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";
                    TodayCO2 = Convert.ToDouble(Decimal.Round((Convert.ToInt32((ElecDayData.Compute("sum(DataDiff)*" + CO2Multiplier + "", "")))), 2).ToString());
                }

                if (ElecPrevDayData.Compute("sum(DataDiff)", "") != DBNull.Value)
                {
                    Value4 = Decimal.Round((Convert.ToInt32((ElecPrevDayData.Compute("sum(DataDiff)", "")))), 2).ToString() + " kWh";
                    Value5 = (Decimal.Round((Convert.ToInt32((ElecPrevDayData.Compute("sum(DataDiff)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value6= (Decimal.Round((Convert.ToInt32((ElecPrevDayData.Compute("sum(DataDiff)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }
                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((ElecDayData.Compute("sum(DataDiff)", "") != DBNull.Value) && (ElecPrevDayData.Compute("sum(DataDiff)", "") != DBNull.Value))
                {

                    Chart1AxisY.AxisMaximum = (Math.Max(Convert.ToDecimal(ElecDayData.Compute("max(DataDiff)", "").ToString()), Convert.ToDecimal(ElecPrevDayData.Compute("max(DataDiff)", "").ToString())) + 1).ToString();
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart1AxisY.Title = "kWh";
                    Chart1.AxesY.Clear();
                    Chart1.AxesY.Add(Chart1AxisY);
                }

                //Create Chart Titles
                Chart1Day.Text = "Electricity Usage Today";
                // ElecDay.FontSize = ChartpointSize;

                Chart1PrevDay.Text = "Electricity Usage Yesterday";
                //ElecPrevDay.FontSize = ChartpointSize;




                // Create a new instance of DataSeries

                //DataSeries dataSeries2 = new DataSeries();

                // Set DataSeries property

                Chart1.Series[0].LegendText = "kWh Usage";
                Chart1.ColorSet = "VisiOrange";

                for (int i = 0; i < 96; i++)
                {

                    DataPoint dataPoint = new DataPoint();
                    dataPoint.AxisXLabel = dt[i].ToShortTimeString();


                    // Add dataPoint to DataPoints collection
                    Chart1.Series[0].DataPoints.Add(dataPoint);
                    //dataSeries2.DataPoints.Add(dataPoint);




                }

                if (count == 0)
                {

                    Chart1.Titles.Clear();
                    Chart1.Titles.Add(Chart1Day);

                    for (int i = 0; i < ElecDayData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart1.Series[0].DataPoints[i].YValue = Convert.ToDouble(ElecDayData.Rows[i]["DataDiff"].ToString()); // Changing the dataPoint YValue at runtime

                    }
                    for (int i = ElecDayData.Rows.Count; i < 96; i++)
                    {
                        Chart1.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                    }

                }
                else
                {
                    Chart1.Titles.Clear();
                    Chart1.Titles.Add(Chart1PrevDay);

                    for (int i = 0; i < ElecPrevDayData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart1.Series[0].DataPoints[i].YValue = Convert.ToDouble(ElecPrevDayData.Rows[i]["DataDiff"].ToString()); // Changing the dataPoint YValue at runtime

                    }
                    for (int i = ElecPrevDayData.Rows.Count; i < 96; i++)
                    {
                        Chart1.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                    }

                }



            }
            catch (Exception ex)
            {
                string msg = "Daily Electricity Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString();
                throw new Exception(msg);

            }
            finally
            {
                ElecDayData.Clear();
                if (null != ElecDayData)
                {
                    ElecDayData.Dispose();
                }
                ElecPrevDayData.Clear();
                if (null != ElecPrevDayData)
                {
                    ElecPrevDayData.Dispose();
                }

            }

        }
        public void MonthlyElecDataSeries()
        {

            using (LINQEnergySuiteDataContext db = new LINQEnergySuiteDataContext())
            {
                var Carbon = from s in db.MeterLists
                             where s.MeterInstance == ElecMeter
                             select new
                             {
                                 s.CarbonMultiplier,
                                 s.CO2Multiplier
                             };
                foreach (var d in Carbon)
                {
                    CO2Multiplier = d.CO2Multiplier.ToString();
                    CarbonMultiplier = d.CarbonMultiplier.ToString();
                }
            }

            sDate = DateTime.Now.ToShortDateString();
            sDate2 = DateTime.Now.AddMonths(-1).ToShortDateString();

            DataTable MonthData = null;
            DataTable PrevMonthData = null;
            try
            {
                MonthData = month.MonthlyData(ElecMeter, sDate);
                PrevMonthData = month.MonthlyData(ElecMeter, sDate2);
                if (MonthData.Compute("sum(day_data)", "") != DBNull.Value)
                {
                    Value1 = Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)", "")))), 2).ToString() + " kWh";
                    Value2 = (Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value3 = (Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }

                if (PrevMonthData.Compute("sum(day_data)", "") != DBNull.Value)
                {
                    Value4 = Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)", "")))), 2).ToString() + " kWh";
                    Value5 = (Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value6 = (Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }
                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((MonthData.Compute("sum(day_data)", "") != DBNull.Value) && (PrevMonthData.Compute("sum(day_data)", "") != DBNull.Value))
                {

                    Chart1AxisY.AxisMaximum = (Math.Max(Convert.ToDecimal(MonthData.Compute("max(day_data)", "").ToString()), Convert.ToDecimal(PrevMonthData.Compute("max(day_data)", "").ToString())) + 1).ToString();
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart1AxisY.Title = "kWh";
                    Chart1.AxesY.Clear();
                    Chart1.AxesY.Add(Chart1AxisY);
                }

                //Create Chart Titles

                ElecMonth.Text = "Electricity Current Month Usage"; //**NOT URRENTLY USED**
                // ElecDay.FontSize = ChartpointSize;

                ElecPrevMonth.Text = "Electricity Usage " + Convert.ToDateTime(sDate2).ToString("MMM yyyy");
                //ElecPrevDay.FontSize = ChartpointSize;




                // Create a new instance of DataSeries

                //DataSeries dataSeries2 = new DataSeries();

                // Set DataSeries property
                Chart1.Series[0].LegendText = "kWh Usage";
                Chart1.ColorSet = "VisiBlue";
                //


                if (count == 4)
                {
                    for (int i = 0; i < PrevMonthData.Rows.Count; i++)
                    {

                        DataPoint dataPoint = new DataPoint();
                        dataPoint.AxisXLabel = Convert.ToDateTime(PrevMonthData.Rows[i]["Date"].ToString()).ToString("ddd, d");

                        // Add dataPoint to DataPoints collection
                        Chart1.Series[0].DataPoints.Add(dataPoint);
                        //dataSeries2.DataPoints.Add(dataPoint);

                    }

                    Chart1.Titles.Clear();
                    Chart1.Titles.Add(ElecPrevMonth);

                    for (int i = 0; i < PrevMonthData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart1.Series[0].DataPoints[i].YValue = Convert.ToDouble(PrevMonthData.Rows[i]["day_data"].ToString()); // Changing the dataPoint YValue at runtime

                    }


                }




            }
            catch (Exception ex)
            {
                string msg = "Monthly Electricity Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString();
                throw new Exception(msg);

            }
            finally
            {
                MonthData.Clear();
                if (null != MonthData)
                {
                    MonthData.Dispose();
                }
                PrevMonthData.Clear();
                if (null != PrevMonthData)
                {
                    PrevMonthData.Dispose();
                }
            }

        }
        public void DailyTempDataSeries()
        {
            sDate = DateTime.Now.ToShortDateString();

            Value1 = Space_TempArray[CurrentBuilding];
            Value2 = "Room Temperature";
            Value3 = OATArray[CurrentBuilding];
            Value4 = "Outside Air Temp";
            //The Rest Are not Currently Used
            Value5 = string.Empty;
            Value6 = string.Empty;
            Value7 = string.Empty;
            Value8 = string.Empty;
            Value9 = string.Empty;
            Value10 = string.Empty;
            Value11 = string.Empty;
            Value12 = string.Empty;

            try
            {
                TempDT = TempDAC.TempData(Convert.ToInt32(SpaceTempTLInst[CurrentBuilding]), sDate);
                
                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((TempDT.Compute("sum(Data)", "") != DBNull.Value) )
                {

                    Chart1AxisY.AxisMaximum = Convert.ToDecimal(TempDT.Compute("max(Data)", "").ToString())+1;
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart1AxisY.Title = "°C";
                    Chart1.AxesY.Clear();
                    Chart1.AxesY.Add(Chart1AxisY);
                }

                //Create Chart Titles
                Chart1Day.Text = "Room Temperature Last 24 Hours";
                
                // Set DataSeries property

                Chart1.Series[0].LegendText = "Temperature";
                Chart1.ColorSet = "VisiOrange";

                for (int i = 0; i < 96; i++)
                {

                    DataPoint dataPoint = new DataPoint();
                    dataPoint.AxisXLabel = dt[i].ToShortTimeString();

                    // Add dataPoint to DataPoints collection
                    Chart1.Series[0].DataPoints.Add(dataPoint);
                    //dataSeries2.DataPoints.Add(dataPoint);

                }

                

                    Chart1.Titles.Clear();
                    Chart1.Titles.Add(Chart1Day);

                    for (int i = 0; i < TempDT.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart1.Series[0].DataPoints[i].YValue = Convert.ToDouble(TempDT.Rows[i]["Data"].ToString()); // Changing the dataPoint YValue at runtime

                    }
                    for (int i = TempDT.Rows.Count; i < 96; i++)
                    {
                        Chart1.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                    }

                
                



            }
            catch (Exception ex)
            {
                string msg = "Daily Temperature Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString();
                throw new Exception(msg);

            }
            finally
            {
                TempDT.Clear();
                if (null != TempDT)
                {
                    TempDT.Dispose();
                }
            }
        }
        public void DailyOATDataSeries()
        {
            sDate = DateTime.Now.ToShortDateString();


            try
            {
                OAT_DT = TempDAC.TempData(Convert.ToInt32(OATTLInst[CurrentBuilding]), sDate);

                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((OAT_DT.Compute("sum(Data)", "") != DBNull.Value))
                {

                    Chart2AxisY.AxisMaximum = Convert.ToDecimal(OAT_DT.Compute("max(Data)", "").ToString()) + 1;
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart2AxisY.Title = "°C";
                    Chart2.AxesY.Clear();
                    Chart2.AxesY.Add(Chart2AxisY);
                }

                //Create Chart Titles
                Chart2Day.Text = "Outdoor Temperature Last 24 Hours";

                // Set DataSeries property

                Chart2.Series[0].LegendText = "Temperature";
                Chart2.ColorSet = "VisiOrange";

                for (int i = 0; i < 96; i++)
                {

                    DataPoint dataPoint = new DataPoint();
                    dataPoint.AxisXLabel = dt[i].ToShortTimeString();

                    // Add dataPoint to DataPoints collection
                    Chart2.Series[0].DataPoints.Add(dataPoint);
                    //dataSeries2.DataPoints.Add(dataPoint);

                }



                Chart2.Titles.Clear();
                Chart2.Titles.Add(Chart2Day);

                for (int i = 0; i < OAT_DT.Rows.Count; i++)
                {
                    // Update YValue property of the DataPoint
                    Chart2.Series[0].DataPoints[i].YValue = Convert.ToDouble(OAT_DT.Rows[i]["Data"].ToString()); // Changing the dataPoint YValue at runtime

                }
                for (int i = OAT_DT.Rows.Count; i < 96; i++)
                {
                    Chart2.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                }






            }
            catch (Exception ex)
            {
                string msg = "Outside Temperature Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString();
                throw new Exception(msg);

            }
            finally
            {
                OAT_DT.Clear();
                if (null != OAT_DT)
                {
                    OAT_DT.Dispose();
                }
            }
        }
        public void DailyGasDataSeries()
        {

            using (LINQEnergySuiteDataContext db = new LINQEnergySuiteDataContext())
            {
                var Carbon = from s in db.MeterLists
                             where s.MeterInstance == GasMeter
                             select new
                             {
                                 s.CarbonMultiplier,
                                 s.CO2Multiplier

                             };

                foreach (var d in Carbon)
                {
                    CO2Multiplier = d.CO2Multiplier.ToString();
                    CarbonMultiplier = d.CarbonMultiplier.ToString();
                }
            }
            sDate = DateTime.Now.ToShortDateString();
            sDate2 = DateTime.Now.AddDays(-1).ToShortDateString();

            
            try
            {
                GasDayData = day.DailyData(GasMeter, sDate);
                GasPrevDayData = day.DailyData(GasMeter, sDate2);
                if (GasDayData.Compute("sum(DataDiff)", "") != DBNull.Value)
                {
                    Value7 = Decimal.Round((Convert.ToInt32((GasDayData.Compute("sum(DataDiff)", "")))), 2).ToString() + " kWh";
                    Value8 = (Decimal.Round((Convert.ToInt32((GasDayData.Compute("sum(DataDiff)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value9 = (Decimal.Round((Convert.ToInt32((GasDayData.Compute("sum(DataDiff)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }

                if (GasPrevDayData.Compute("sum(DataDiff)", "") != DBNull.Value)
                {
                    Value10 = Decimal.Round((Convert.ToInt32((GasPrevDayData.Compute("sum(DataDiff)", "")))), 2).ToString() + " kWh";
                    Value11 = (Decimal.Round((Convert.ToInt32((GasPrevDayData.Compute("sum(DataDiff)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value12 = (Decimal.Round((Convert.ToInt32((GasPrevDayData.Compute("sum(DataDiff)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";
                    YesterdayGasUsage = Convert.ToDouble(GasPrevDayData.Compute("sum(DataDiff)", ""));

                }
                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((GasDayData.Compute("sum(DataDiff)", "") != DBNull.Value) && (GasPrevDayData.Compute("sum(DataDiff)", "") != DBNull.Value))
                {

                    Chart2AxisY.AxisMaximum = (Math.Max(Convert.ToDecimal(GasDayData.Compute("max(DataDiff)", "").ToString()), Convert.ToDecimal(GasPrevDayData.Compute("max(DataDiff)", "").ToString())) + 1).ToString();
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart2AxisY.Title = "kWh";
                    Chart2.AxesY.Clear();
                    Chart2.AxesY.Add(Chart2AxisY);
                }

                //Create Chart Titles

                Chart2Day.Text = "Gas Usage Today";
                //GasDay.FontSize = ChartpointSize;

                Chart2PrevDay.Text = "Gas Usage Yesterday";
                //GasPrevDay.FontSize = ChartpointSize;



                // Set DataSeries property
                Chart2.Series[0].LegendText = "kWh Usage";
                Chart2.ColorSet = "VisiOrange";
                Chart2.AnimationEnabled = true;
                // Create a DataPoint


                for (int i = 0; i < 96; i++)
                {
                    DataPoint dataPoint = new DataPoint();
                    dataPoint.AxisXLabel = dt[i].ToShortTimeString();


                    // Add dataPoint to DataPoints collection
                    Chart2.Series[0].DataPoints.Add(dataPoint);
                    //dataSeries2.DataPoints.Add(dataPoint);

                }
                if (count == 0)
                {
                    Chart2.Titles.Clear();
                    Chart2.Titles.Add(Chart2Day);

                    for (int i = 0; i < GasDayData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart2.Series[0].DataPoints[i].YValue = Convert.ToDouble(GasDayData.Rows[i]["DataDiff"].ToString()); // Changing the dataPoint YValue at runtime

                    }
                    for (int i = GasDayData.Rows.Count; i < 96; i++)
                    {
                        Chart2.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                    }

                }
                else
                {
                    Chart2.Titles.Clear();
                    Chart2.Titles.Add(Chart2PrevDay);

                    for (int i = 0; i < GasPrevDayData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart2.Series[0].DataPoints[i].YValue = Convert.ToDouble(GasPrevDayData.Rows[i]["DataDiff"].ToString()); // Changing the dataPoint YValue at runtime

                    }
                    for (int i = GasPrevDayData.Rows.Count; i < 96; i++)
                    {
                        Chart2.Series[0].DataPoints[i].YValue = 0; // For the curent Day where not every XValue will have Day, return 0
                    }



                }

            }
            catch (Exception ex)
            {
                string msg = "Daily Gas Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString(); ;
                throw new Exception(msg);

            }
            finally
            {
                GasDayData.Clear();
                if (null != GasDayData)
                {
                    GasDayData.Dispose();
                }
                GasPrevDayData.Clear();
                if (null != GasPrevDayData)
                {
                    GasPrevDayData.Dispose();
                }
            }

        }
        public void MonthlyGasDataSeries()
        {
            using (LINQEnergySuiteDataContext db = new LINQEnergySuiteDataContext())
            {
                var Carbon = from s in db.MeterLists
                             where s.MeterInstance == GasMeter
                             select new
                             {
                                 s.CarbonMultiplier,
                                 s.CO2Multiplier
                             };
                foreach (var d in Carbon)
                {
                    CO2Multiplier = d.CO2Multiplier.ToString();
                    CarbonMultiplier = d.CarbonMultiplier.ToString();
                }
            }

            sDate = DateTime.Now.ToShortDateString();
            sDate2 = DateTime.Now.AddMonths(-1).ToShortDateString();

            DataTable MonthData = null;
            DataTable PrevMonthData = null;
            try
            {
                MonthData = month.MonthlyData(GasMeter, sDate);
                PrevMonthData = month.MonthlyData(GasMeter, sDate2);
                if (MonthData.Compute("sum(day_data)", "") != DBNull.Value)
                {
                    Value7 = Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)", "")))), 2).ToString() + " kWh";
                    Value8 = (Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value9 = (Decimal.Round((Convert.ToInt32((MonthData.Compute("sum(day_data)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }

                if (PrevMonthData.Compute("sum(day_data)", "") != DBNull.Value)
                {
                    Value10 = Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)", "")))), 2).ToString() + " kWh";
                    Value11 = (Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)*" + CO2Multiplier + "", "")))), 2).ToString()) + " kg";
                    Value12 = (Decimal.Round((Convert.ToInt32((PrevMonthData.Compute("sum(day_data)*" + CarbonMultiplier + "", "")))), 2).ToString()) + " kg";

                }
                //Set the maximum Y Axis at a constant using the maximum value from each DataTable
                //Only update Axis if the DataTable return Valid Data
                if ((MonthData.Compute("sum(day_data)", "") != DBNull.Value) && (PrevMonthData.Compute("sum(day_data)", "") != DBNull.Value))
                {

                    Chart2AxisY.AxisMaximum = (Math.Max(Convert.ToDecimal(MonthData.Compute("max(day_data)", "").ToString()), Convert.ToDecimal(PrevMonthData.Compute("max(day_data)", "").ToString())) + 1).ToString();
                    //Also add in the Axis Title at this point,X Axis Title is added in another Method
                    Chart2AxisY.Title = "kWh";
                    Chart2.AxesY.Clear();
                    Chart2.AxesY.Add(Chart2AxisY);
                }

                //Create Chart Titles

                GasMonth.Text = "Gas Current Month Usage"; //**NOT CURRENTLY USED**
                // ElecDay.FontSize = ChartpointSize;

                GasPrevMonth.Text = "Gas Usage " + Convert.ToDateTime(sDate2).ToString("MMM yyyy");
                //ElecPrevDay.FontSize = ChartpointSize;




                // Create a new instance of DataSeries

                //DataSeries dataSeries2 = new DataSeries();

                // Set DataSeries property
                Chart2.Series[0].LegendText = "kWh Usage";
                Chart2.ColorSet = "VisiBlue";
                //


                if (count == 4)
                {
                    for (int i = 0; i < PrevMonthData.Rows.Count; i++)
                    {

                        DataPoint dataPoint = new DataPoint();
                        dataPoint.AxisXLabel = Convert.ToDateTime(PrevMonthData.Rows[i]["Date"].ToString()).ToString("ddd, d");

                        // Add dataPoint to DataPoints collection
                        Chart2.Series[0].DataPoints.Add(dataPoint);
                        //dataSeries2.DataPoints.Add(dataPoint);

                    }

                    Chart2.Titles.Clear();
                    Chart2.Titles.Add(GasPrevMonth);

                    for (int i = 0; i < PrevMonthData.Rows.Count; i++)
                    {
                        // Update YValue property of the DataPoint
                        Chart2.Series[0].DataPoints[i].YValue = Convert.ToDouble(PrevMonthData.Rows[i]["day_data"].ToString()); // Changing the dataPoint YValue at runtime

                    }


                }




            }
            catch (Exception ex)
            {
                string msg = "Monthly Gas Chart Series Rendering Error: ";
                msg += ex.InnerException.ToString();
                throw new Exception(msg);

            }
            finally
            {
                MonthData.Clear();
                if (null != MonthData)
                {
                    MonthData.Dispose();
                }
                PrevMonthData.Clear();
                if (null != PrevMonthData)
                {
                    PrevMonthData.Dispose();
                }
            }

        }
        public void GetODBCObjRefs()
        {
            Refs = LiveDataRefs.LiveData();
            NoBuildings = Refs.Rows.Count;
            ElecPowerArray = new string[NoBuildings];
            GasPowerArray = new string[NoBuildings];
            OATArray = new string[NoBuildings];
            Space_TempArray = new string[NoBuildings];
            ElecPowerRefArray = new string[NoBuildings];
            GasPowerRefArray = new string[NoBuildings];
            OATRefArray = new string[NoBuildings];
            Space_TempRefArray = new string[NoBuildings];
            BuildingNoArray = new string[NoBuildings];
            SpaceTempTLInst = new string[NoBuildings];
            OATTLInst = new string[NoBuildings];
            BuildingNameArray = new string[NoBuildings];
            ElecTLRefArray = new string[NoBuildings];
            GasTLRefArray = new string[NoBuildings];
            for (int i = 0; i < NoBuildings; i++)
            {
                this.ElecPowerRefArray[i] = Refs.Rows[i]["ElecPowerAV"].ToString();
                this.GasPowerRefArray[i] = Refs.Rows[i]["GasPowerAV"].ToString();
                this.OATRefArray[i] = Refs.Rows[i]["OAT"].ToString();
                this.Space_TempRefArray[i] = Refs.Rows[i]["SpaceTemp"].ToString();
                this.BuildingNoArray[i] = Refs.Rows[i]["BuildingNo"].ToString();
                this.SpaceTempTLInst[i] = Refs.Rows[i]["SpaceTemp_TL"].ToString();
                this.OATTLInst[i] = Refs.Rows[i]["OAT_TL"].ToString();
                this.BuildingNameArray[i] = Refs.Rows[i]["BuildingName"].ToString();
                this.ElecTLRefArray[i] = Refs.Rows[i]["ElecEnergyTL"].ToString();
                this.GasTLRefArray[i] = Refs.Rows[i]["GasEnergyTL"].ToString();
            }
            
        }
        public void GetODBCObjData()
        {
            using (LINQEnergySuiteDataContext db = new LINQEnergySuiteDataContext())
            {
                for (int i = 0; i < NoBuildings; i++)
                {
                        //Retrieve Electricity Data
                        var Elecdata = from s in db.ODBCDumps
                                       where s.ID == Convert.ToInt32(BuildingNoArray[i]) && s.ObjRef == ElecPowerRefArray[i]
                                       select s;
                        foreach (var ed in Elecdata)
                        {
                            ElecPowerArray[i] = ed.Value;
                        }
                        //Retrieve Gas Data
                        var Gasdata = from s in db.ODBCDumps
                                      where s.ID == Convert.ToInt32(BuildingNoArray[i]) && s.ObjRef == GasPowerRefArray[i]
                                      select s;
                        foreach (var gd in Gasdata)
                        {
                            GasPowerArray[i] = gd.Value;
                        }
                                                //Retrieve OAT Data
                        var OATdata = from s in db.ODBCDumps
                                      where s.ID == Convert.ToInt32(BuildingNoArray[i]) && s.ObjRef == OATRefArray[i]
                                      select s;
                        foreach (var OAT in OATdata)
                        {
                            OATArray[i] = OAT.Value;
                        }

                        //Retrieve Space Temp Data
                        var STdata = from s in db.ODBCDumps
                                     where s.ID == Convert.ToInt32(BuildingNoArray[i]) && s.ObjRef == Space_TempRefArray[i]
                                     select s;
                        foreach (var st in OATdata)
                        {
                            Space_TempArray[i] = st.Value;
                        }



                    
                }
            }
        }
        public void AssignChartTLRefs()
        {
            //Elec and Gas Meter Instances must be Entered as TLInstance ONLY. Not with DEVInstance
            ElecMeter = Convert.ToInt32(ElecTLRefArray[CurrentBuilding]);
            GasMeter = Convert.ToInt32(GasTLRefArray[CurrentBuilding]);
            
        }

        public void ODBCData(int Count)
        {
            
            Image transImg1 = new Image();
            Image transImg2 = new Image();
            Image transImg3 = new Image();
            Image transImg4 = new Image();
            Cars = 0;
            YesterdayGasCO2 = 0;
            //if (DeltaDSN == 1)
            //{
                StatuxBox.Visibility = Visibility.Visible;
                myGauge1.Visibility = Visibility.Visible;
                GasGauge.Visibility = Visibility.Visible;
                
                    
                try
                {

                    if (Count == 1)
                    {
                        ElecPower = Convert.ToDouble(ElecPowerArray[CurrentBuilding]);
                        Cars = Math.Round(((TodayCO2 / kgPerGallon) * MPG) / 100, 0);
                        myGauge1.CurrentValue = Math.Round(ElecPower, 0);
                        txtStatus.Text = "Today, this Building has emitted the same CO2 as " + Cars.ToString() + " family Cars covering 100miles";
                        StatuxBox.Header = "Current Status - Electricity";
                        txtCost.Text = (Math.Round(ElecPower * Convert.ToDouble(ElecCostPerkWh), 2)).ToString() + " £/h";
                        txtCO2.Text = (Math.Round(ElecPower * ElecCO2, 0)).ToString() + " kgCO2/h";
                        txtElecPower.Text = Math.Round(ElecPower, 1).ToString() + " kW";
                        transImg1.Source = img1;
                        transImg2.Source = img3;
                        transImg4.Source = img5;

                    }
                    if ((Count == 3)&&(GasAvailable==1))
                    {
                        GasPower = Convert.ToDouble(GasPowerArray[CurrentBuilding]);
                        GasGauge.CurrentValue = Math.Round(GasPower, 0);
                        GasCO2 = Math.Round((YesterdayGasUsage * GasCO2) * HomeCO2perYear, 4);
                        txtStatus.Text = "Yesterday, this Building emitted the equivalent CO2 of  " + YesterdayGasCO2.ToString() + " Households Annual Emissions";
                        StatuxBox.Header = "Current Status - Gas";
                        txtCost.Text = (Math.Round(GasPower * Convert.ToDouble(GasCostPerkWh), 2)).ToString() + " £/h";
                        txtCO2.Text = (Math.Round(GasPower * GasCO2, 0)).ToString() + " kgCO2/h";
                        txtElecPower.Text = Math.Round(GasPower, 1).ToString() + " kW";
                        transImg1.Source = img2;
                        transImg2.Source = img4;
                        transImg4.Source = img5;

                    }
                    if (Count == 5)
                    {
                        ElecPower = Convert.ToDouble(ElecPowerArray[CurrentBuilding]);
                        Cars = Math.Round(((ElecPower * 1000) / LaptopPower), 0);
                        myGauge1.CurrentValue = Math.Round(ElecPower, 0);
                        txtStatus.Text = "Today this Building has used the Equivalent Power of " + Cars.ToString() + " 40-Watt Laptop(s) per hour";
                        StatuxBox.Header = "Current Status - Electricity";
                        txtCost.Text = (Math.Round((ElecPower * Convert.ToDouble(ElecCostPerkWh)) * 12, 2)).ToString() + " £/Day";
                        txtCO2.Text = (Math.Round((ElecPower * ElecCO2) * kgCoal, 0)).ToString() + " kg Coal/h";
                        txtElecPower.Text = Math.Round(ElecPower, 1).ToString() + " kW";
                        transImg1.Source = img7;
                        transImg2.Source = img3;
                        transImg4.Source = img6;

                    }
                    transImg3.Source = img8;

                }
                catch (Exception ex)
                {
                    string msg = "ODBC Data Collection Error: ";
                    msg += ex.InnerException.ToString(); ;
                    throw new Exception(msg);
                }
                finally
                {
                    TransitionBox.Content = transImg1;
                    TransitionBox2.Content = transImg2;
                    TransitionBox3.Content = transImg3;
                    TransitionBox4.Content = transImg4;

                }
            //}
            //else
            //{
            //    StatuxBox.Visibility = Visibility.Hidden;
            //    myGauge1.Visibility = Visibility.Hidden;
            //    GasGauge.Visibility = Visibility.Hidden;
            //}

        }



        /// <summary>
        /// Event handler for loaded event of chart
        /// </summary>
        /// <param name="sender">Chart</param>
        /// <param name="e">RoutedEventArgs</param>
        void chart_Loaded(object sender, RoutedEventArgs e)
        {
            

            
        }

        /// <summary>
        /// Event handler for Tick event of Timer
        /// </summary>
        /// <param name="sender"> System.Windows.Threading.DispatcherTimer</param>
        /// <param name="e">EventArgs</param>
        void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                //Elec and Gas Meter Instances must be Entered as TLInstance ONLY. Not with DEVInstance
                AssignChartTLRefs();
                if (count % 2 == 0) //Count is even
                {
                    Chart1.Series[0].DataPoints.Clear();
                    Chart2.Series[0].DataPoints.Clear();

                }
                if (count % 2 != 0) //count is an odd number
                {
                    GetODBCObjData();
                    ODBCData(count);
                }

                if (count <= 3)
                {
                    HeaderTitle.Content = BuildingNameArray[CurrentBuilding] + " - Energy Consumption";
                    Daily_XAxis_Values();
                }
                else
                {
                    Monthly_XAxis_Values();
                    
                }

                if (((count == 0) || (count == 2)) && (ElecAvailable == 1))
                {
                    
                    DailyElecDataSeries();
                    
                }
                if (((count == 0) || (count == 2)) && (GasAvailable == 1))
                {
                    DailyGasDataSeries();
                    System.Threading.Thread.Sleep(2000);
                    ReplaceControl_day();
                }
                if (((count == 4)) && (ElecAvailable == 1))
                {
                    MonthlyElecDataSeries();
                    
                }
                if (((count == 4)) && (GasAvailable == 1))
                {
                    MonthlyGasDataSeries();
                    System.Threading.Thread.Sleep(2000);
                    ReplaceControl_month();
                }
                if (count == 6)
                {
                    HeaderTitle.Content = BuildingNameArray[CurrentBuilding] + " - Temperatures";
                    DailyTempDataSeries();
                    DailyOATDataSeries();
                    System.Threading.Thread.Sleep(2000);
                    ReplaceControl_temps();
                }
                if (count == 7)
                {
                    HeaderTitle.Content = BuildingNameArray[CurrentBuilding] + " - Water Usage";
                    
                    System.Threading.Thread.Sleep(2000);
                    ReplaceControl_water();
                }
                
                count = count + 1;
                if (count > 7) //Start the sequence from the Start
                {
                    count = 0;
                    CurrentBuilding = CurrentBuilding + 1;
                    if (CurrentBuilding > (NoBuildings-1)) 
                    {
                        //CurrentBuilding Actually Starts at 0, not 1 for cross-referencing the Arrays
                        CurrentBuilding = 0;
                    }
                }
            }
            catch { }
            finally
            {
                
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                //MinimizeMemory();

            }

        }
        
        DayEnergyControl obj;
        MonthEnergyControl obj2;
        EnvironControl obj3;
        WaterControl obj4;
        void ReplaceControl_day()
        {
            //Send the Values over to the UserControl.
            //Generic Values Used to cut down on Strings and to make future changes Easier (less naming)
            obj = new DayEnergyControl(Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8, Value9, Value10, Value11, Value12);
            statusTransition.Content = obj;

        }
        void ReplaceControl_month()
        {
            //mainwind = this.Content;
            obj2 = new MonthEnergyControl(Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8, Value9, Value10, Value11, Value12);
            statusTransition.Content = obj2;
            

        }
        void ReplaceControl_temps()
        {
            //mainwind = this.Content;
            obj3 = new EnvironControl(Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8, Value9, Value10, Value11, Value12);
            statusTransition.Content = obj3;
            

        }
        void ReplaceControl_water()
        {
            //mainwind = this.Content;
            obj4 = new WaterControl(Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8, Value9, Value10, Value11, Value12);
            statusTransition.Content = obj4;

        }
}

Open in new window

LVL 1
wint100Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

wint100Author Commented:
I've been through both of those a number of times and didn't find a solution.

My main question is if the way I'm creating my strings, doubles etc.. is the best way.
0
CuteBugCommented:
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

CuteBugCommented:
I am also doubting the MinimizeMemory method could be causing the leak.
0
wint100Author Commented:
I'm not 100% where I had that method from, it was posted in a forum as a fix for a memory leak on a control I've used. Apparently the leak is fixed in .NET4, so I was going to leave it in until I move over.

I've been monitoring with .NET Memory Profiler and made some changes to the code. Mainly with the Chart and Transitionals controls. Instead of creating the Chart and TransitionElements at the constructor level, I'm not creating a Chart within  method adding it to a grid on runtime, then nulling the Chart Instance. I've done the same with the Transitionals and the memory usage is way down. There is still a slight increase in unmanaged resources though which I need to look into more.

This WPF app is designed to run on a plasma screen 24/7, updating every 10s, so any memory leak, however small, will cause problems eventually.
0
CuteBugCommented:

I believe, if you are using Visual Studio 2010 Ultimate RC, you can pinpoint the probable areas of memory leak with the tools available in the IDE.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wint100Author Commented:
Sounds interesting, I'll download a trial and see how it goes.

Thanks
0
CuteBugCommented:
You are welcome! :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.