Esempio n. 1
0
        /// <summary>
        /// Report the user status
        /// </summary>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool ReportUserStatus(MacomberMapCommunications.Messages.MM_Client_Status Status)
        {
            try
            {
                return(innerChannel.ReportUserStatus(Status));
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex.Message);

                try
                {
                    if (ex.Message.IndexOf("aborted", StringComparison.OrdinalIgnoreCase) >= 0 || ex.Message.IndexOf("Faulted", StringComparison.OrdinalIgnoreCase) >= 0 && (!lastConnect.HasValue || (DateTime.Now - lastConnect.Value).TotalSeconds > 10))
                    {
                        // can we reconnect?
                        Exception error = null;
                        // this login method should reconnect us.
                        MM_Server_Interface.TryLogin(MM_Server_Interface.ServerName, MM_Server_Interface.ConnectionURI, MM_Server_Interface.UserName, MM_Server_Interface.Password, out error);
                        lastConnect = DateTime.Now;
                        if (error != null)
                        {
                            throw error;
                        }
                    }
                }
                catch (Exception exp)
                {
                    MM_System_Interfaces.LogError(exp.Message);
                }
                return(false);
            }
        }
 /// <summary>
 /// Add our value in as necessary, and update our fields as present
 /// </summary>
 /// <param name="Field"></param>
 /// <param name="Header"></param>
 /// <param name="IsEst"></param>
 /// <param name="Value"></param>
 public void AddValue(String Field, String Header, bool IsEst, String Value)
 {
     try
     {
         int FieldID, HeaderID;
         if (!Fields.TryGetValue(Field, out FieldID))
         {
             Fields.Add(Field, FieldID = Fields.Count);
         }
         if (!Headers.TryGetValue(Header, out HeaderID))
         {
             Headers.Add(Header, HeaderID = Headers.Count);
         }
         if (IsEst)
         {
             EstValues.Add(new Point(HeaderID, FieldID), Value);
         }
         else
         {
             TelemValues.Add(new Point(HeaderID, FieldID), Value);
         }
     } catch (Exception ex)
     {
         MM_System_Interfaces.LogError(ex);
     }
 }
Esempio n. 3
0
        /// <summary>Report the server name</summary>
        /// <returns></returns>
        public string ServerName()
        {
            try
            {
                return(innerChannel.ServerName());
            } catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex.Message);

                try
                {
                    if (ex.Message.IndexOf("aborted", StringComparison.OrdinalIgnoreCase) >= 0 || ex.Message.IndexOf("Faulted", StringComparison.OrdinalIgnoreCase) >= 0 && (!lastConnect.HasValue || (DateTime.Now - lastConnect.Value).TotalSeconds > 10))
                    {
                        // can we reconnect?
                        Exception error = null;
                        // this login method should reconnect us.
                        if (MM_Server_Interface.TryLogin(MM_Server_Interface.ServerName, MM_Server_Interface.ConnectionURI, MM_Server_Interface.UserName, MM_Server_Interface.Password, out error))
                        {
                            return(MM_Server_Interface.ServerName);
                        }
                        lastConnect = DateTime.Now;
                        if (error != null)
                        {
                            throw error;
                        }
                    }
                }
                catch (Exception exp)
                {
                    MM_System_Interfaces.LogError(exp.Message);
                }

                return("SERVER ERROR");
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Initialize the Macomber Map
        /// </summary>
        /// <param name="Coordinates">The coordinates to be used in the map</param>
        /// <param name="Starter">Our startup form</param>
        public MacomberMap_Form(MM_Coordinates Coordinates, MM_Startup_Form Starter)
        {
            InitializeComponent();


            var size = ClientSize;

            this.Size = Screen.PrimaryScreen.WorkingArea.Size;
            if (this.Size.Width >= 1900)
            {
                size = new Size(1900, this.Size.Height);
            }
            if (this.Size.Height >= 1200)
            {
                size = new Size(this.Size.Width, 1180);
            }
            this.ClientSize = new Size(size.Width - 10, size.Height - 10);
            this.Size       = ClientSize;

            this.Title   = "Main Map";
            this.Starter = Starter;
            MM_System_Interfaces.LogError("MM: Initializing network map/coordinates");
            InitNetworkMap(Coordinates);

            if (!Data_Integration.Permissions.ShowViolations)
            {
                SwitchMMView(false, false);
            }


            //Assign our integration layer, add the thread and form to it

            Data_Integration.RunningForms.Add(this);
            Data_Integration.RunningThreads.Add(System.Threading.Thread.CurrentThread);
            System.Threading.Thread.Sleep(3000); // wait for model kv levels to load
            //Assign our controls
            MM_System_Interfaces.LogError("MM: Starting network map");
            ctlNetworkMap.SetControls(ctlViolationViewer, 0);
            MM_System_Interfaces.LogError("MM: Starting violation viewer");
            ctlViolationViewer.SetControls(ctlNetworkMap);
            MM_System_Interfaces.LogError("MM: Starting key indicators");

            ctlKeyIndicators.SetControls(ctlNetworkMap, ctlViolationViewer, MM_Repository.xConfiguration.DocumentElement["DisplayParameters"]["KeyIndicators"]);

            ResizeLeftSlider(this, null);

            //Set up our results helper
            ResultsHelper         = new MM_Search_Results_Helper();
            ResultsHelper.Visible = false;
            Controls.Add(ResultsHelper);
            ResultsHelper.BringToFront();
            (this.FindForm() as MacomberMap_Form).ctlKeyIndicators.AssignResultsHelper(ResultsHelper);



            //Set up our main timer
            Program.MainFormChecker = new System.Threading.Timer(Program.ThreadChecker, System.Threading.Thread.CurrentThread, 15000, 15000);

            StartRender();
        }
Esempio n. 5
0
 /// <summary>
 /// Assign a value that we've specified
 /// </summary>
 /// <param name="TargetObject"></param>
 /// <param name="FieldName"></param>
 /// <param name="TargetValue"></param>
 private void AssignValue(Object TargetObject, String FieldName, Object TargetValue)
 {
     if (TargetObject == null)
     {
         return;
     }
     try
     {
         if (TargetValue is DataRowView)
         {
             TargetValue = (TargetValue as DataRowView).Row[1];
         }
         if (TargetValue is DBNull)
         {
             TargetValue = null;
         }
         ChangedValues.Add(FieldName);
         string[] splStr = FieldName.TrimEnd(']').Split('[');
         foreach (MemberInfo mI in TargetObject.GetType().GetMember(splStr[0]))
         {
             if (splStr.Length == 1 && mI is FieldInfo)
             {
                 (mI as FieldInfo).SetValue(TargetObject, ChangeType(TargetValue, (mI as FieldInfo).FieldType));
             }
             else if (splStr.Length == 1 && mI is PropertyInfo)
             {
                 (mI as PropertyInfo).SetValue(TargetObject, ChangeType(TargetValue, (mI as PropertyInfo).PropertyType), null);
             }
             else
             {
                 Array InVal;
                 Type  SingleType;
                 if (mI is FieldInfo)
                 {
                     InVal      = (Array)(mI as FieldInfo).GetValue(TargetObject);
                     SingleType = (mI as FieldInfo).FieldType.GetElementType();
                 }
                 else
                 {
                     InVal      = (Array)(mI as PropertyInfo).GetValue(TargetObject, null);
                     SingleType = (mI as PropertyInfo).PropertyType.GetElementType();
                 }
                 InVal.SetValue(ChangeType(TargetValue, SingleType), int.Parse(splStr[1]));
             }
         }
     }
     catch (Exception ex)
     {
         MM_System_Interfaces.MessageBox("Error setting " + FieldName + " for " + TargetObject + "\n" + ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 6
0
        /// <summary>
        /// This thread processes the pipe
        /// </summary>
        /// <param name="state"></param>
        private static void PipeHandler(object state)
        {
            //First, process any information, if it's passed via command line.
            if (!String.IsNullOrEmpty(CommandTSystemWiderse))
            {
                String[] InCmd = CommandTSystemWiderse.Split(new string[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries);
                CommandTSystemWiderse = null;
                ProcessCommand(InCmd);
            }

            SafeFileHandle clientPipeHandle;

            while (true)
            {
                //Try and create the pipe
                clientPipeHandle = CreateNamedPipe(PIPE_NAME, DUPLEX | FILE_FLAG_OVERLAPPED, 0, 255, BUFFER_SIZE, BUFFER_SIZE, 0, IntPtr.Zero);

                //failed to create named pipe
                if (clientPipeHandle.IsInvalid)
                {
                    break;
                }

                //Indicate the success of the process
                if (ConnectNamedPipe(clientPipeHandle, IntPtr.Zero) != 1)
                {
                    break;
                }


                //Open our stream and read everything in
                try
                {
                    List <String> InLine = new List <string>();
                    using (FileStream fStream = new FileStream(clientPipeHandle, FileAccess.ReadWrite, BUFFER_SIZE, true))
                        using (StreamReader sRd = new StreamReader(fStream))
                            while (!sRd.EndOfStream)
                            {
                                InLine.Add(sRd.ReadLine());
                            }

                    //Now, process accordingly. Command: [Zoom/Property/OneLine] [Element Type] [Name or TEID]
                    ProcessCommand(InLine.ToArray());
                }
                catch (Exception ex)
                {
                    MM_System_Interfaces.MessageBox("Error receiving out-of-process command: " + ex.Message + "\n\n" + ex.StackTrace, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Handle the timer tick
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void UpdateTimer_Tick(object sender, EventArgs e)
 {
     pbToExcel.Value = CurrentRow;
     if (ExportThread.ThreadState == System.Threading.ThreadState.Stopped)
     {
         UpdateTimer.Stop();
         try
         {
             Process.Start(FileName);
         }
         catch (Exception ex)
         {
             MM_System_Interfaces.MessageBox("The Excel file has been exported, but could not be opened: " + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
         this.Close();
     }
 }
Esempio n. 8
0
        /// <summary>
        /// Integrate the information from a base line into the DCTie.
        /// </summary>
        /// <param name="BaseLine"></param>
        public void IntegrateFromLine(MM_Line BaseLine)
        {
            try
            {
                //Pull all data in from the base line
                foreach (FieldInfo fI in BaseLine.GetType().GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
                {
                    this.GetType().GetField(fI.Name).SetValue(this, fI.GetValue(BaseLine));
                }

                //Check our line length. If it's less than 10 miles, expand the side closest to the border to make it wider
                float MileLength = 20f;
                if (this.Length < MileLength)
                {
                    float[] Dist = new float[] { float.NaN, float.NaN };
                    foreach (PointF PtToCheck in MM_Repository.Counties["STATE"].Coordinates)
                    {
                        for (int a = 0; a < 2; a++)
                        {
                            if (float.IsNaN(Dist[a]) || CalculateDistance(ConnectedStations[a].LngLat, PtToCheck) < Dist[a])
                            {
                                Dist[a] = CalculateDistance(ConnectedStations[a].LngLat, PtToCheck);
                            }
                        }
                    }

                    //Now, determine which one is closer, and keep moving it until we are at our minimum mile length.
                    int i = 1000;
                    while (this.Length < MileLength && i < 1000)
                    {
                        //Now, find the station with the DC tie elements

                        int TieStation = Math.Max(0, Array.IndexOf(ConnectedStations, this.Unit == null ? this.Substation : this.Unit.Substation));

                        //int ShorterStation = (Dist[0] < Dist[1] ? 0 : 1);
                        ConnectedStations[TieStation].LngLat.X += .01f * Math.Sign(ConnectedStations[TieStation].LngLat.X - ConnectedStations[1 - TieStation].LngLat.X);
                        ConnectedStations[TieStation].LngLat.Y += .01f * Math.Sign(ConnectedStations[TieStation].LngLat.Y - ConnectedStations[1 - TieStation].LngLat.Y);
                        i++;
                    }
                }
            } catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex);
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Create a new property page
 /// </summary>
 public MM_Property_Page(MM_Network_Map_DX nMap, MM_Violation_Viewer violView, MM_Mini_Map miniMap)
 {
     this.nMap     = nMap;
     this.violView = violView;
     this.miniMap  = miniMap;
     DetermineDefaultStyle();
     try
     {
         if (!Cef.IsInitialized)
         {
             Cef.Initialize();
         }
     }
     catch (Exception ex)
     {
         MM_System_Interfaces.LogError(ex);
     }
 }
Esempio n. 10
0
 static MM_Property_Page()
 {
     try
     {
         try
         {
             rh = new rHandler();
             Cef.OnContextInitialized += AddCefPlugins;
             Cef.Initialize();
         }
         catch (Exception ex)
         {
             Cef.OnContextInitialized -= AddCefPlugins;
             MM_System_Interfaces.LogError(ex);
         }
     }
     catch (Exception)
     {
     }
 }
        /// <summary>
        /// Handle a double-click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvQueryStatus_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo hti = lvQueryStatus.HitTest(e.Location);

            if (hti.Item != null)
            {
                MM_DataRetrieval_Information Retrieval = (MM_DataRetrieval_Information)hti.Item.Tag;
                if (!String.IsNullOrEmpty(Retrieval.RefreshCommand))
                {
                    MethodInfo FoundMethod = typeof(MM_Server_Interface).GetMethod(Retrieval.RefreshCommand);
                    if (FoundMethod == null)
                    {
                        MM_System_Interfaces.LogError("Unable to find method to update type {0}", Retrieval.BaseType.Name);
                    }
                    else
                    {
                        FoundMethod.Invoke(null, null);
                    }
                }
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Handle a selection change within the data table, and send it to the associated property page
 /// </summary>
 /// <param name="e"></param>
 protected override void OnSelectionChanged(EventArgs e)
 {
     try
     {
         if (SettingDataSource || MM_Server_Interface.Client == null)
         {
             return;
         }
         else if (this.SelectedCells.Count == 1)
         {
             AssociatedPropertyPage.SetElement(this.CurrentRow.Cells["TEID"].Value as MM_Element);
         }
         else
         {
             AssociatedPropertyPage.SetElement(null);
         }
         base.OnSelectionChanged(e);
     }
     catch (Exception ex)
     {
         MM_System_Interfaces.WriteConsoleLine("Error updating data table selection: " + ex.Message);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Update the KV level, and its underlying components
        /// </summary>
        /// <param name="ElementSource"></param>
        /// <param name="AddIfNew"></param>
        public new void ReadXML(XmlElement ElementSource, bool AddIfNew)
        {
            try
            {
                this.Energized.ReadXML(ElementSource["Energized"], AddIfNew);
                this.PartiallyEnergized.ReadXML(ElementSource["PartiallyEnergized"], AddIfNew);
                this.DeEnergized.ReadXML(ElementSource["DeEnergized"], AddIfNew);

                if (ElementSource["Unknown"] != null)
                {
                    this.Unknown.ReadXML(ElementSource["Unknown"], AddIfNew);
                }
                else
                {
                    this.Unknown.ReadXML(ElementSource["PartiallyEnergized"], AddIfNew);
                }

                base.ReadXML(ElementSource, AddIfNew);
            } catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Handle the submission of a new violation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitButton_Click(object sender, EventArgs e)
        {
            if (SelectedElement == null)
            {
                MM_System_Interfaces.MessageBox("Please select an element to be violated.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                try
                {
                    Data_Integration.CheckAddViolation(NewViolation);
                }
                catch (Exception ex)
                {
                    MM_System_Interfaces.MessageBox("Error generating specific alarm: " + ex.Message + "\n" + ex.StackTrace, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            //Now, clear our components and reset our violation
            NewViolation = new MM_AlarmViolation();
            NewViolation.ViolatedElement = SelectedElement;
            foreach (Control ctl in tabViolations.Controls)
            {
                if (ctl is ComboBox)
                {
                    (ctl as ComboBox).SelectedItem = null;
                }
                else if (ctl is TextBox)
                {
                    (ctl as TextBox).Text = "";
                }
                else if (ctl is CheckBox)
                {
                    (ctl as CheckBox).Checked = false;
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Initialize DirectX factories, swap chain and render targets.
        /// </summary>
        protected void InitGraphics()
        {
            var width  = Size.Width;
            var height = Size.Height;

            Factory2D          = new Factory();
            FactoryDirectWrite = new SharpDX.DirectWrite.Factory();

            var desc = new SwapChainDescription
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput | Usage.BackBuffer,
            };

            // use software driver if RDP or VirtualMachine
            _driverType = MM_System_Profiling.IsTerminalOrVirtual() ? DriverType.Warp : DriverType.Hardware;
            bool swapChainCreated = false;

            while (!swapChainCreated)
            {
                try
                {
                    Device.CreateWithSwapChain(_driverType, DeviceCreationFlags.BgraSupport, desc, out _device, out _swapChain);
                    MM_System_Interfaces.LogError("Initialized DirectX Driver: {0}", _driverType);
                    swapChainCreated = true;
                }
                catch (Exception ex)
                {
                    // downgrade driver and try again using outer while loop
                    if (_driverType == DriverType.Hardware)
                    {
                        _driverType = DriverType.Warp;
                    }
                    else if (_driverType == DriverType.Warp)
                    {
                        _driverType = DriverType.Software;
                    }
                    else
                    {
                        MM_System_Interfaces.LogError(ex);
                        throw new NotSupportedException("DirectX Rendering could not be initialized using hardware of software.", ex);
                    }
                }
            }

            Context = _device.ImmediateContext;

            // Ignore all windows events
            FactoryDxgi = _swapChain.GetParent <SharpDX.DXGI.Factory>();
            FactoryDxgi.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            _backBuffer                  = Resource.FromSwapChain <Texture2D>(_swapChain, 0);
            RenderTargetView             = new RenderTargetView(_device, _backBuffer);
            DxgiSurface                  = _backBuffer.QueryInterface <Surface>();
            RenderTarget2D               = new RenderTarget(Factory2D, DxgiSurface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            RenderTarget2D.AntialiasMode = AntialiasMode;

            PresenterReady = true;
        }
Esempio n. 16
0
 /// <summary>
 /// Handle a grid data error
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Data_Table_DataError(object sender, DataGridViewDataErrorEventArgs e)
 {
     MM_System_Interfaces.LogError(e.Exception);
     e.ThrowException = false;
 }
Esempio n. 17
0
        /// <summary>
        /// When the primary/secondary path is selected, display all of our elements
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbPrimarySecondary_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lvItems.Columns.Clear();
                lvItems.Items.Clear();
                lvItems.View = View.Details;

                lvItems.Columns.Add("#");
                lvItems.Columns.Add("Action");
                lvItems.Columns.Add("Subsatation");
                lvItems.Columns.Add("Type");
                lvItems.Columns.Add("Element");
                lvItems.Columns.Add("Operator");
                lvItems.FullRowSelect = true;
                lvItems.CheckBoxes    = true;
                MM_Blackstart_Corridor_Target Target = cmbCorridorTarget.SelectedItem as MM_Blackstart_Corridor_Target;
                FieldInfo fI = Target.GetType().GetField(cmbPrimarySecondary.Text);
                if (Target != null && fI != null)
                {
                    MM_Blackstart_Corridor_Element[] Elems = fI.GetValue(Target) as MM_Blackstart_Corridor_Element[];
                    MM_Substation LastSub = null;
                    for (int a = 0; a < Elems.Length; a++)
                    {
                        try
                        {
                            ListViewItem lvI = new ListViewItem((a + 1).ToString("#,##0"));
                            lvI.UseItemStyleForSubItems = true;
                            if (MM_Server_Interface.Client != null && Array.IndexOf(Data_Integration.UserOperatorships, 999999) == -1 && Array.IndexOf(Data_Integration.UserOperatorships, Elems[a].AssociatedElement.Operator.TEID) == -1)
                            {
                                lvI.ForeColor = Color.Gray;
                            }

                            lvI.SubItems.Add(Elems[a].Action.ToString());

                            if (Elems[a].AssociatedElement != null)
                            {
                                MM_Element Elem = Elems[a].AssociatedElement;


                                if (Elem is MM_Line)
                                {
                                    MM_Line Line = (MM_Line)Elem;
                                    if (LastSub == Line.Substation2)
                                    {
                                        lvI.SubItems.Add(Line.Substation2.Name + " to " + Line.Substation1.Name);
                                    }
                                    else
                                    {
                                        lvI.SubItems.Add(Line.Substation1.Name + " to " + Line.Substation2.Name);
                                    }
                                    LastSub = Line.Substation2;
                                }
                                else
                                {
                                    lvI.SubItems.Add(Elem.Substation.Name);
                                    LastSub = Elem.Substation;
                                }

                                lvI.SubItems.Add(Elem.ElemType.Name);
                                lvI.SubItems.Add(MM_Repository.TitleCase(Elem.Name));
                                lvI.SubItems.Add(Elem.Operator.Alias.Substring(0, 1) + MM_Repository.TitleCase(Elem.Operator.Alias.Substring(1)));
                            }
                            else
                            {
                                if (Elems[a].Substation == null)
                                {
                                    lvI.SubItems.Add("?");
                                }
                                else
                                {
                                    lvI.SubItems.Add(MM_Repository.TitleCase(Elems[a].Substation.Name));
                                }
                                lvI.SubItems.Add("?");
                                lvI.SubItems.Add("?");
                                lvI.SubItems.Add("?");
                                lvI.ForeColor = Color.Red;
                                lvI.UseItemStyleForSubItems = true;
                            }
                            lvI.Tag = Elems[a];
                            lvItems.Items.Add(lvI);
                        }
                        catch (Exception ex)
                        {
                            MM_System_Interfaces.LogError(ex);
                        }
                    }
                    tmrUpdate_Tick(tmrUpdate, EventArgs.Empty);
                    lvItems.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                }
            }
            catch (Exception)
            { }
        }
Esempio n. 18
0
        /// <summary>
        /// Handle the timer update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateTimer(object sender, EventArgs e)
        {
            int WorstProcess = 0;

            foreach (MM_Process Process in new List <MM_Process>(Data_Integration.Processes.Values))
            {
                try
                {
                    TimeSpan ThisTime = (Data_Integration.SaveTime.ToOADate() == 0 ? DateTime.Now : Data_Integration.SaveTime) - Process.LastExecution;
                    //If it's not already set, locate the item associated with the process
                    if (Process.lvItem == null)
                    {
                        Process.lvItem = lvProcesses.Items.Add(Process.Name);
                        if (Process.LastExecution.ToOADate() == 0)
                        {
                            Process.lvItem.SubItems.Add("Never");
                        }
                        else
                        {
                            Process.lvItem.SubItems.Add(MM_Repository.TimeSpanToText(ThisTime));
                        }
                        ListViewGroup ProcessGroup = lvProcesses.Groups[Process.BaseElement.ParentNode.Attributes["Name"].Value];
                        if (ProcessGroup == null)
                        {
                            ProcessGroup = lvProcesses.Groups.Add(Process.BaseElement.ParentNode.Attributes["Name"].Value, Process.BaseElement.ParentNode.Attributes["Name"].Value);
                        }
                        Process.lvItem.Group = ProcessGroup;
                    }
                    else if (Process.LastExecution.ToOADate() == 0)
                    {
                        Process.lvItem.SubItems[1].Text = "Never";
                    }
                    else
                    {
                        Process.lvItem.SubItems[1].Text = MM_Repository.TimeSpanToText(ThisTime);
                    }
                    if (Process.ErrorTime == TimeSpan.Zero)
                    {
                    }
                    else if (ThisTime >= Process.ErrorTime)
                    {
                        WorstProcess = 2;
                    }
                    else if (ThisTime >= Process.WarningTime && WorstProcess != 2)
                    {
                        WorstProcess = 1;
                    }
                }
                catch (Exception ex)
                {
                    MM_System_Interfaces.LogError("Error processing process completion " + Process.Name + ": " + ex.Message);
                }
            }

            foreach (ColumnHeader col in lvProcesses.Columns)
            {
                col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            }

            //Update our process viewer
            SetProcessColor(WorstProcess);
        }
Esempio n. 19
0
        /// <summary>
        /// Load the XML Configuration file for the Macomber Map system
        /// </summary>
        /// <param name="MapConfiguration"></param>
        private static void LoadXmlConfiguration(String MapConfiguration)
        {
            //Create a blank violation entry for 'none'
            //ViolationImages.Images.Add("None", new Bitmap(16, 16));

            xConfiguration = new XmlDocument();
            xConfiguration.LoadXml(MapConfiguration);
            Data_Integration.Permissions = new MM_Permissions(xConfiguration["Configuration"]["Permissions"]);
            foreach (XmlElement xElem in xConfiguration["Configuration"]["DisplayParameters"].ChildNodes.OfType <XmlElement>())
            {
                try
                {
                    if (xElem.Name == "VoltageLevel")
                    {
                        KVLevels.Add(xElem.Attributes["Name"].Value, new MM_KVLevel(xElem, true));
                    }
                    else if (xElem.Name == "ElementType")
                    {
                        ElemTypes.Add(xElem.Attributes["Name"].Value, new MM_Element_Type(xElem, true));
                    }
                    else if (xElem.Name == "MM_Unit_Type" || xElem.Name == "GenerationType" || xElem.Name == "UnitType")
                    {
                        MM_Unit_Type NewGen = new MM_Unit_Type(xElem, true);
                        GenerationTypes.Add(NewGen.Name, NewGen);
                        if (!GenerationTypes.ContainsKey(NewGen.EMSName))
                        {
                            GenerationTypes.Add(NewGen.EMSName, NewGen);
                        }
                    }
                    else if (xElem.Name == "Violation")
                    {
                        ViolationTypes.Add(xElem.Attributes["Name"].Value, new MM_AlarmViolation_Type(xElem, true));
                    }
                    else if (xElem.Name == "Substation")
                    {
                        SubstationDisplay = new MM_Substation_Display(xElem, true);
                    }
                    else if (xElem.Name == "Overall")
                    {
                        OverallDisplay = new MM_Display(xElem, true);
                    }
                    else if (xElem.Name == "WeatherStationDetail")
                    {
                        Weather.MM_WeatherStation.QueryPrepend = xElem.Attributes["URL"].Value;
                    }
                    else if (xElem.Name == "WeatherStations")
                    {
                        Weather.MM_WeatherStationCollection.QueryPrepend = xElem.Attributes["URL"].Value;
                    }
                    else if (xElem.Name == "WeatherStationAlerts")
                    {
                        Weather.MM_WeatherStationCollection.AlertsPrepend = xElem.Attributes["URL"].Value;
                    }
                    else if (xElem.Name == "WeatherStationForecast")
                    {
                        Weather.MM_WeatherStationCollection.ForecastPrepend = xElem.Attributes["URL"].Value;
                    }
                    else if (xElem.Name == "StateBorder")
                    {
                        MM_Boundary.StateDisplay = new MM_DisplayParameter(xElem, true);
                    }
                    else if (xElem.Name == "CountyBorder")
                    {
                        MM_Boundary.CountyDisplay = new MM_DisplayParameter(xElem, true);
                    }
                    else if (xElem.Name == "Displays" || xElem.Name == "Views" || xElem.Name == "KeyIndicators")
                    {
                    }
                    else
                    {
                        MM_System_Interfaces.WriteConsoleLine("Unknown element from XML configuration: " + xElem.Name);
                    }
                }
                catch
                { }
            }

            //Now pull in our views
            Views.Add(xConfiguration["Configuration"]["DisplayParameters"], new MM_Display_View(xConfiguration["Configuration"]["DisplayParameters"].Attributes["DefaultName"].Value));
            foreach (XmlElement xElem in xConfiguration["Configuration"]["DisplayParameters"]["Views"].SelectNodes("//View"))
            {
                Views.Add(xElem, new MM_Display_View(xElem));
            }

            //Pull in our commands
            foreach (XmlElement xElem in xConfiguration.SelectNodes("/Configuration/Commands/Command").OfType <XmlElement>())
            {
                try
                {
                    Data_Integration.Commands.Add(new MM_Command(xElem, true));
                }
                catch
                { }
            }
            try
            {
                foreach (XmlElement xElem in xConfiguration.SelectNodes("/Configuration/DataTypes/DataType").OfType <XmlElement>())
                {
                    MM_DataRetrieval_Information Retr = new MM_DataRetrieval_Information(xElem);
                    MM_Server_Interface.DataRetrievalInformation.Add(Retr.BaseType, Retr);
                }
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex);
            }

            //Now add in our icons for actions to our image collection
            ViolationImages.Images.Add("Note", Properties.Resources.NoteHS);
            ViolationImages.Images.Add("OneLine", Properties.Resources.OneLine);
            ViolationImages.Images.Add("MoveMap", Properties.Resources.MoveMap);
            ViolationImages.Images.Add("Web", Properties.Resources.SearchWebHS);
            ViolationImages.Images.Add("Acknowledge", Properties.Resources.Acknowledge);
            ViolationImages.Images.Add("Archive", Properties.Resources.Archive);
            ViolationImages.Images.Add("Properties", Properties.Resources.PropertiesHS);

            //Pull in any one-line or element type information
            foreach (XmlElement xElem in xConfiguration["Configuration"]["OneLineData"].ChildNodes.OfType <XmlElement>())
            {
                if (!MM_Repository.ElemTypes.ContainsKey(xElem.Attributes["Name"].Value))
                {
                    MM_Repository.ElemTypes.Add(xElem.Attributes["Name"].Value, new MM_Element_Type(xElem, false));
                }
            }

            //override the permissions
            if (MM_Server_Interface.ISQse)
            {
                Data_Integration.Permissions.LassoStandard  = false;
                Data_Integration.Permissions.ShowViolations = false;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Process the command
        /// </summary>
        /// <param name="InLine"></param>
        private static void ProcessCommand(String[] InLine)
        {
            MM_Element Element = null;

            if (InLine.Length == 3)
            {
                if (InLine[1].Equals("Substation", StringComparison.CurrentCultureIgnoreCase))
                {
                    MM_Substation FoundSub;
                    if (MM_Repository.Substations.TryGetValue(InLine[2], out FoundSub))
                    {
                        Element = FoundSub;
                    }
                    else
                    {
                        foreach (MM_Substation Sub in MM_Repository.Substations.Values)
                        {
                            if (Sub.LongName.Equals(InLine[2], StringComparison.CurrentCultureIgnoreCase))
                            {
                                Element = Sub;
                                break;
                            }
                        }
                    }
                }
                else if (InLine[1].Equals("Line", StringComparison.CurrentCultureIgnoreCase))
                {
                    Element = MM_Repository.Lines[InLine[2]];
                }
                else if (InLine[1].Equals("Contingency", StringComparison.CurrentCultureIgnoreCase))
                {
                    Element = MM_Repository.Contingencies[InLine[2]];
                }
                else
                {
                    Element = MM_Repository.LocateElement(InLine[2].Split('.')[0], InLine[2].Split('.')[1], InLine[1], "");
                }
            }
            else if (InLine.Length == 2)
            {
                Int32 TryNum;
                if (!Int32.TryParse(InLine[1], out TryNum) || !MM_Repository.TEIDs.TryGetValue(TryNum, out Element))
                {
                    return;
                }
            }


            if (InLine[0].Equals("Search", StringComparison.CurrentCultureIgnoreCase))
            {
                MM_Form_Builder.SearchDisplay(Map.ctlNetworkMap, InLine[1], false, false);
            }
            else if (InLine[0].Equals("Message", StringComparison.CurrentCultureIgnoreCase))
            {
                MM_System_Interfaces.MessageBox("Message received: " + String.Join(" ", InLine, 1, InLine.Length - 1), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (InLine[0].Equals("Zoom", StringComparison.CurrentCultureIgnoreCase))
            {
                if (Element is MM_AlarmViolation)
                {
                    Element = (Element as MM_AlarmViolation).ViolatedElement;
                }
                if (Element is MM_Substation)
                {
                    Map.ctlNetworkMap.Coordinates.Center = ((Element as MM_Substation).LngLat);
                    Map.ctlNetworkMap.Coordinates.UpdateZoom(MM_Repository.OverallDisplay.StationZoomLevel);
                }
                else if (Element is MM_Line)
                {
                    Map.ctlNetworkMap.Coordinates.Center = (((Element as MM_Line).Midpoint));
                    Map.ctlNetworkMap.Coordinates.UpdateZoom(MM_Repository.OverallDisplay.StationZoomLevel);
                }
                else if (Element.Substation != null)
                {
                    Map.ctlNetworkMap.Coordinates.Center = (Element.Substation.LngLat);
                    Map.ctlNetworkMap.Coordinates.UpdateZoom(MM_Repository.OverallDisplay.StationZoomLevel);
                }
            }
            else if (InLine[0].Equals("Property", StringComparison.CurrentCultureIgnoreCase))
            {
                MM_Form_Builder.PropertyPage(Element, Map.ctlNetworkMap);
            }
            else if (InLine[0].Equals("OneLine", StringComparison.CurrentCultureIgnoreCase))
            {
                MM_Form_Builder.OneLine_Display(Element, Map.ctlNetworkMap);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Handle the timer update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrUpdate_Tick(object sender, EventArgs e)
        {
            //First, fill in our reserves
            try
            {
                lock (Data_Integration.Reserves)
                    foreach (MM_Reserve Reserve in Data_Integration.Reserves.Values)
                    {
                        if (Reserve.DisplayItem == null)
                        {
                            Reserve.CreateDisplayItem(this.lv);
                        }
                        else
                        {
                            String InVal = Reserve.Value.ToString("#,##0") + " mw";
                            if (Reserve.DisplayItem.SubItems[1].Text != InVal)
                            {
                                Reserve.DisplayItem.SubItems[1].Text = InVal;
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError("UI Error updating reserves: " + ex.Message);
            }

            //Now, fill in our limits
            try
            {
                lock (Data_Integration.CSCIROLLimits)
                    foreach (MM_Limit Limit in Data_Integration.CSCIROLLimits.Values)
                    {
                        ListViewItem lvI = lv.Items[Limit.Name];
                        if (lvI == null)
                        {
                            lvI = lv.Items.Add(Limit.Name, Limit.Name, 0);
                            lvI.SubItems.Add((Limit.Current / Limit.Max).ToString("0.0%") + " (" + Limit.Current.ToString("#,##0") + " / " + Limit.Max.ToString("#,##0") + " mw)");
                            if (Limit.Name.StartsWith("Stability"))
                            {
                                lvI.Group = lv.Groups["IROL Limits"];
                            }
                            else
                            {
                                lvI.Group = lv.Groups["CSC Limits"];
                            }
                        }
                        else
                        {
                            lvI.SubItems[1].Text = (Limit.Current / Limit.Max).ToString("0.0%") + " (" + Limit.Current.ToString("#,##0") + " / " + Limit.Max.ToString("#,##0") + " mw)";
                        }
                    }
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError("UI Error updating CSC/IROL limits: " + ex.Message);
            }

            //Now, autosize everything
            if (!HasResized && lv.Items.Count > 0)
            {
                foreach (ColumnHeader col in lv.Columns)
                {
                    col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                }
                Rectangle LastOne = lv.Items[lv.Items.Count - 1].Bounds;
                this.Size  = new Size(253, 491);
                HasResized = true;
            }
        }
Esempio n. 22
0
 private void Cbrowser_LoadError(object sender, LoadErrorEventArgs e)
 {
     MM_System_Interfaces.LogError(e.ErrorText);
 }
Esempio n. 23
0
        /// <summary>
        /// Assign a new element to the property page
        /// </summary>
        /// <param name="Element"></param>
        public void SetElement(MM_Element Element)
        {
            //Don't go through the work of reassigning the same element
            this.ImageList = MM_Repository.ViolationImages;
            if ((Element != null) && (this.Element == Element))
            {
                return;
            }

            //Assign the element
            this.Element = Element;


            //Clear all tabs
            this.TabPages.Clear();

            if (Element == null)
            {
                SetStyle(ControlStyles.UserPaint, true);
            }
            else
            {
                //Reset to our default style
                SetDefaultStyle();

                //Now add in the information from our XML configuration file for this item.
                TabPage LocalPage = new TabPage(Element.ElemType.Name + " " + Element.Name);
                this.TabPages.Add(LocalPage);

                TreeView NewView = new TreeView();
                NewView.NodeMouseClick += new TreeNodeMouseClickEventHandler(NewView_NodeMouseClick);
                NewView.Dock            = DockStyle.Fill;

                SortedDictionary <String, Object> InValues = new SortedDictionary <string, object>(StringComparer.CurrentCultureIgnoreCase);
                InValues.Add("Name", Element.Name);
                if (Element.Substation != null)
                {
                    InValues.Add("Substation", Element.Substation);
                }
                if (Element.KVLevel != null)
                {
                    InValues.Add("KV Level", Element.KVLevel);
                }



                //Now, pull in all of the members
                MemberInfo[] inMembers = Element.GetType().GetMembers();
                foreach (MemberInfo mI in inMembers)
                {
                    try
                    {
                        if (mI.Name != "Coordinates" && !InValues.ContainsKey(mI.Name))
                        {
                            if (mI is FieldInfo)
                            {
                                InValues.Add(mI.Name, ((FieldInfo)mI).GetValue(Element));
                            }
                            else if (mI is PropertyInfo)
                            {
                                InValues.Add(mI.Name, ((PropertyInfo)mI).GetValue(Element, null));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MM_System_Interfaces.LogError(ex);
                    }
                }

                //Now, handle our information
                MM_AlarmViolation_Type ViolTmp;
                foreach (KeyValuePair <String, Object> kvp in InValues)
                {
                    try
                    {
                        AddValue(kvp.Key, kvp.Value, NewView.Nodes, out ViolTmp);
                    }
                    catch (Exception ex)
                    { }
                }


                if (Element is MM_Substation)
                {
                    TreeNode LineNode = NewView.Nodes.Add("Lines");
                    Dictionary <MM_KVLevel, List <MM_Line> > Lines = new Dictionary <MM_KVLevel, List <MM_Line> >();
                    foreach (MM_Line TestLine in MM_Repository.Lines.Values)
                    {
                        if (TestLine.Permitted)
                        {
                            if (Array.IndexOf(TestLine.ConnectedStations, Element) != -1)
                            {
                                if (!Lines.ContainsKey(TestLine.KVLevel))
                                {
                                    Lines.Add(TestLine.KVLevel, new List <MM_Line>());
                                }
                                Lines[TestLine.KVLevel].Add(TestLine);
                            }
                        }
                    }
                    foreach (KeyValuePair <MM_KVLevel, List <MM_Line> > kvp in Lines)
                    {
                        TreeNode KVNode = LineNode.Nodes.Add(kvp.Key.ToString());
                        foreach (MM_Line LineToAdd in kvp.Value)
                        {
                            (KVNode.Nodes.Add(LineToAdd.MenuDescription()) as TreeNode).Tag = LineToAdd;
                        }
                    }
                }

                if (Element.Violations.Count > 0)
                {
                    TreeNode NewNode = NewView.Nodes.Add("Violations");
                    foreach (MM_AlarmViolation Viol in Element.Violations.Values)
                    {
                        TreeNode ViolNode = (NewNode.Nodes.Add(Viol.MenuDescription()) as TreeNode);
                        ViolNode.Tag        = Viol;
                        ViolNode.ImageIndex = Viol.Type.ViolationIndex;
                    }
                }
                LocalPage.Controls.Add(NewView);

                //Add in our tracking option
                TabPage TrackingPage = new TabPage();
                TrackingPage.Text = "Tracking";
                this.TabPages.Add(TrackingPage);
                FlowLayoutPanel flpTrack = new FlowLayoutPanel();
                flpTrack.ForeColor  = Color.White;
                flpTrack.BackColor  = Color.Black;
                flpTrack.AutoScroll = true;
                flpTrack.Dock       = DockStyle.Fill;
                TrackingPage.Controls.Add(flpTrack);

                foreach (MemberInfo mI in Element.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
                {
                    if ((mI is FieldInfo && ((FieldInfo)mI).FieldType == typeof(float)) || (mI is PropertyInfo && ((PropertyInfo)mI).PropertyType == typeof(float)))
                    {
                        MM_LoadGen_Tracking_Operator Oper = new MM_LoadGen_Tracking_Operator(mI.Name, Element.ElemType, mI);
                        Oper.Elements.Add(Element);
                        flpTrack.Controls.Add(Oper);
                        Oper.BeginTracking();
                    }
                }

                if (!string.IsNullOrWhiteSpace(Element.HistoricServerPath) && HistoricServerUrl != null && HistoricServerUrl.Length > 2)
                {
                    try
                    {
                        if (!HistoricServerUrl.EndsWith("/"))
                        {
                            HistoricServerUrl += "/";
                        }

                        TabPage historyPage = new TabPage();
                        historyPage.Text = "HistoricServer";
                        this.TabPages.Add(historyPage);
                        string url = HistoricServerUrl + @"/#/Displays/Adhoc?DataItems=" + TranslateElementPath(Element.HistoricServerPath) + "&mode=kiosk&hideToolBar";


                        browser = new ChromiumWebBrowser(url);
                        browser.RequestHandler = rh;
                        historyPage.Controls.Add(browser);
                    }
                    catch (Exception ex)
                    {
                        MM_System_Interfaces.LogError(ex);
                    }
                }
                //If we have historic data access, add a history tab
                if (MM_Server_Interface.Client != null)
                {
                    TabPage NewPage = new TabPage();
                    NewPage.Text = "History";
                    this.TabPages.Add(NewPage);
                    MM_Historic_Viewer hView = new MM_Historic_Viewer(MM_Historic_Viewer.GraphModeEnum.HistoricalOnly, MM_Historic_Viewer.GetMappings(Element), new string[] { }, "");
                    hView.Dock = DockStyle.Fill;
                    NewPage.Controls.Add(hView);
                    SelectedTab = NewPage;
                    if (this.Parent.Controls.Count == 1)
                    {
                        TabPage NewPage2 = new TabPage();
                        NewPage2.Text = "Switch orientation";
                        this.TabPages.Add(NewPage2);
                    }
                }
                if (((Element is MM_Unit && !string.IsNullOrWhiteSpace(((MM_Unit)Element).MarketResourceName)) || (Element is MM_Contingency && ((MM_Contingency)Element).Type == "Flowgate")) && FlowgateUrl != null && FlowgateUrl.Length > 2)
                {
                    try
                    {
                        if (!FlowgateUrl.EndsWith("/"))
                        {
                            FlowgateUrl += "/";
                        }
                        TabPage FlowgatePage = new TabPage();
                        FlowgatePage.Text = "Flowgate";
                        this.TabPages.Add(FlowgatePage);
                        string url = "";
                        if (Element is MM_Unit)
                        {
                            url = FlowgateUrl + @"#/rc/gendetails?item=" + Element.Operator.Name.Replace("TOPOLOGY.", "") + "." + ((MM_Unit)Element).MarketResourceName;
                        }
                        else if (Element is MM_Contingency)
                        {
                            url = FlowgateUrl + @"#/rc/flowgatedetails?flowgate=" + ((MM_Contingency)Element).Name;
                        }
                        cbrowser = new ChromiumWebBrowser(url);
                        cbrowser.RequestHandler = rh;
                        cbrowser.LoadError     += Cbrowser_LoadError;
                        FlowgatePage.Controls.Add(cbrowser);
                        SelectedTab = FlowgatePage;
                    }
                    catch (Exception ex)
                    {
                        MM_System_Interfaces.LogError(ex);
                    }
                }

                this.Visible = true;
                this.BringToFront();

                //If we're sharing this control with another, offer a back button
                if (this.Parent.Controls.Count != 1)
                {
                    this.TabPages.Add("(back) ");
                }
            }
        }
Esempio n. 24
0
        static void Main(params string[] args)
        {
            // CreateModelXml user password filepath (Build thMM_System_Interfacesis as a console app for this job).
            if (args.Length > 0 && args[0].Equals("CreateModelXml", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    System.Console.Error.WriteLine("Starting XML Model creator client");
                    MM_Server_Interface.LoadModelFromSql = true;
                    MM_System_Interfaces.Headless        = true;
                    MM_Repository.OverallDisplay         = new MM_Display();
                    MM_Coordinates coord = new MM_Coordinates(-109f, 29f, -86f, 51f, 1f);

                    System.Console.Error.WriteLine("Waiting for server...");
                    while (MM_Server_Interface.MMServers == null || MM_Server_Interface.MMServers.Count == 0)
                    {
                        Thread.Sleep(3000);
                    }

                    var list = MM_Server_Interface.MMServers.Values.ToList();

                    System.Console.Error.WriteLine("Connecting to server: " + list[0].ServerName);

                    string user     = "******";
                    string password = "";
                    string file     = "MacomberMap-Combined.MM_Model";

                    if (args.Length > 1)
                    {
                        if (args[1].EndsWith(".MM_Model"))
                        {
                            file = args[1];
                        }
                        else
                        {
                            user = args[1];
                        }
                    }
                    if (args.Length > 2)
                    {
                        if (args[2].EndsWith(".MM_Model"))
                        {
                            file = args[2];
                        }
                        else
                        {
                            password = args[2];
                        }
                    }
                    if (args.Length > 3)
                    {
                        file = args[3];
                    }
                    Exception exp = new Exception();
                    MM_Server_Interface.TryLogin(list[0].ServerName, list[0].ServerURI, user, password, out exp);
                    MM_Server_Interface.LoadMacomberMapConfiguration();

                    Data_Integration.InitializationComplete = false;
                    System.Console.Error.WriteLine("Starting SQL Model Loader...");
                    SqlModelLoader sqlModelLoader = new SqlModelLoader();
                    sqlModelLoader.ConnectionString = Settings.Default.ModelDatabase;
                    sqlModelLoader.LoadStaticRepository();
                    System.Console.Error.WriteLine("Rolling up Elements...");
                    Data_Integration.UseEstimates = false;
                    Data_Integration.RollUpElementsToSubstation();
                    Data_Integration.CommLoaded                 = true;
                    Data_Integration.ModelLoadCompletion        = DateTime.Now;
                    Data_Integration.NetworkSource              = new MM_Data_Source();
                    Data_Integration.NetworkSource.Estimates    = false;
                    Data_Integration.NetworkSource.Database     = "NETMOM";
                    Data_Integration.NetworkSource.Application  = "RTNET";
                    Data_Integration.NetworkSource.BackColor    = Color.Blue;
                    Data_Integration.NetworkSource.Telemetry    = true;
                    Data_Integration.NetworkSource.Default      = true;
                    Data_Integration.NetworkSource.Master       = true;
                    Data_Integration.NetworkSource.ViolationApp = "RTCA";
                    Data_Integration.InitializationComplete     = true;
                    // Data_Integration.RestartModel(MM_Server_Interface.Client);
                    Data_Integration.SaveXMLData(file, coord);
                    System.Console.WriteLine("Waiting for data...");
                    for (int i = 0; i < 60 * 8; i++)
                    {
                        System.Console.Write(".");
                        Thread.Sleep(1000); // wait for EMS data to flow in.
                    }
                    Data_Integration.SaveXMLData(file, coord);
                }
                catch (Exception ex)
                {
                    System.Console.Error.WriteLine(ex.Message);
                    System.Console.Error.WriteLine(ex.StackTrace);
                    System.Environment.Exit(1);
                }
                System.Environment.Exit(0);
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
            //   Application.Run(new frmControlTester());
            // return;
            try
            {
                Microsoft.Win32.RegistryKey key;
                key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Policies", true);

                if (!key.GetSubKeyNames().Contains("Chromium"))
                {
                    key.CreateSubKey("Chromium");
                }
                key = key.OpenSubKey("Chromium", true);
                if (!key.GetSubKeyNames().Contains("EnabledPlugins"))
                {
                    key.CreateSubKey("EnabledPlugins");
                }
                key = key.OpenSubKey("EnabledPlugins", true);

                if (!key.GetValueNames().Contains("1"))
                {
                    key.SetValue("1", "Silverlight*");
                    key.SetValue("2", "npapi");
                }
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex);
            }
            if (Environment.CommandLine.IndexOf("/Test", StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                Application.Run(new frmTest());
            }
            else
            {
                using (MM_Startup_Form Startup = new MM_Startup_Form())
                    if (Startup.ShowDialog(StartNetworkMap) == DialogResult.OK)
                    {
                        Application.Run();
                    }
                    else
                    {
                        Application.Exit();
                    }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Initialize a new boundary
        /// </summary>
        /// <param name="xE"></param>
        /// <param name="AddIfNew">Whether to add any new elements that may be created</param>
        public MM_Boundary(XmlElement xE, bool AddIfNew)
            : base(xE, AddIfNew)
        {
            //Because of an issue where some boundaries contain multiple substations of the same TEID, fix it here.
            Dictionary <Int32, MM_Substation> Subs = new Dictionary <Int32, MM_Substation>(Substations.Count);

            foreach (MM_Substation Sub in this.Substations)
            {
                if (!Subs.ContainsKey(Sub.TEID))
                {
                    Subs.Add(Sub.TEID, Sub);
                }
            }
            Substations.Clear();
            Substations.AddRange(Subs.Values);

            if (xE.HasAttribute("Max_X"))
            {
                this.Max      = new PointF(MM_Converter.ToSingle(xE.Attributes["Max_X"].Value), MM_Converter.ToSingle(xE.Attributes["Max_Y"].Value));
                this.Min      = new PointF(MM_Converter.ToSingle(xE.Attributes["Min_X"].Value), MM_Converter.ToSingle(xE.Attributes["Min_Y"].Value));
                this.Centroid = new PointF(MM_Converter.ToSingle(xE.Attributes["Centroid_X"].Value), MM_Converter.ToSingle(xE.Attributes["Centroid_Y"].Value));
            }
            if (xE.HasAttribute("Boundary_Website"))
            {
                this.Website = xE.Attributes["Boundary_Website"].Value;
            }

            if (xE.HasAttribute("Coordinates") || xE["Coordinates"] != null)
            {
                String[] Coords = null;
                if (xE["Coordinates"] != null)
                {
                    Coords = xE["Coordinates"].InnerText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    Coords = xE.Attributes["Coordinates"].InnerText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                List <PointF> OutCoordinates          = new List <PointF>();
                List <PointF> OutConvertedCoordinates = new List <PointF>();
                for (int a = 0; a < Coords.Length; a += 2)
                {
                    PointF OutPt = new PointF(MM_Converter.ToSingle(Coords[a]), MM_Converter.ToSingle(Coords[a + 1]));
                    OutCoordinates.Add(OutPt);
                    OutConvertedCoordinates.Add(new PointF(OutPt.X * 1000f, OutPt.Y * 1000f));
                }

                //Now make sure the last coordiante closes it out.
                if (OutCoordinates[OutCoordinates.Count - 1].Equals(OutCoordinates[0]) == false)
                {
                    OutCoordinates.Add(OutCoordinates[0]);
                    OutConvertedCoordinates.Add(OutConvertedCoordinates[0]);
                }
                Coordinates = OutCoordinates;
                HitTestPath.AddLines(OutConvertedCoordinates.ToArray());
            }
            else
            {
                List <PointF> OutConvertedCoordinates = new List <PointF>();
                foreach (PointF OutPt in Coordinates)
                {
                    OutConvertedCoordinates.Add(new PointF(OutPt.X * 1000f, OutPt.Y * 1000f));
                }
                try
                {
                    HitTestPath.AddLines(OutConvertedCoordinates.ToArray());
                } catch (Exception ex)
                {
                    MM_System_Interfaces.LogError(ex);
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Determine the worst violation type within the substation
        /// </summary>
        public MM_AlarmViolation_Type WorstVisibleViolation(Dictionary <MM_AlarmViolation, ListViewItem> ShownViolations, Object CallingForm)
        {
            MM_AlarmViolation_Type WorstViolation = null;

            try
            {
                if (CallingForm is MM_Mini_Map)
                {
                    foreach (MM_AlarmViolation Viol in Violations.Values)
                    {
                        if ((Viol.Type.MiniMap == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.MiniMap == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected) && (ShownViolations.ContainsKey(Viol))))
                        {
                            if ((WorstViolation == null) || (Viol.Type.ViolationIndex < WorstViolation.ViolationIndex))
                            {
                                WorstViolation = Viol.Type;
                            }
                        }
                    }
                }
                else if (this is MM_Line)
                {
                    foreach (MM_AlarmViolation Viol in Violations.Values)
                    {
                        if ((Viol.Type.NetworkMap_Line == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.NetworkMap_Line == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected) && (ShownViolations.ContainsKey(Viol))))
                        {
                            if ((WorstViolation == null) || (Viol.Type.ViolationIndex < WorstViolation.ViolationIndex))
                            {
                                WorstViolation = Viol.Type;
                            }
                        }
                    }
                    foreach (var contingency in Contingencies)
                    {
                        foreach (MM_AlarmViolation Viol in contingency.Violations.Values)
                        {
                            if ((Viol.Type.NetworkMap_Line == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.NetworkMap_Line == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected) && (ShownViolations.ContainsKey(Viol))))
                            {
                                if ((WorstViolation == null || Viol.Type.ViolationIndex < WorstViolation.ViolationIndex) && (Viol.ViolatedElement == this || Viol.Contingency != null))
                                {
                                    WorstViolation = Viol.Type;
                                }
                            }
                        }
                    }
                }
                else if (this is MM_Substation)
                {
                    foreach (MM_AlarmViolation Viol in Violations.Values)
                    {
                        if ((Viol.Type.NetworkMap_Substation == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.NetworkMap_Substation == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected) && (ShownViolations.ContainsKey(Viol))))
                        {
                            if ((WorstViolation == null) || (Viol.Type.ViolationIndex < WorstViolation.ViolationIndex))
                            {
                                WorstViolation = Viol.Type;
                            }
                        }
                    }
                }
                else if (this is MM_Node && Violations.Count == 0 && ShownViolations.Count > 0)
                {
                    foreach (MM_AlarmViolation Viol in ShownViolations.Keys)
                    {
                        if (Viol.ViolatedElement.ElemType.Name == "BusbarSection" && Viol.ViolatedElement.Substation.Equals(this.Substation) && Viol.ViolatedElement.Name.Equals(this.Name))
                        {
                            if ((Viol.Type.OneLineElement == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.OneLineElement == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected)))
                            {
                                if ((WorstViolation == null) || (Viol.Type.ViolationIndex < WorstViolation.ViolationIndex))
                                {
                                    WorstViolation = Viol.Type;
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (MM_AlarmViolation Viol in Violations.Values)
                    {
                        if ((Viol.Type.OneLineElement == MM_AlarmViolation_Type.DisplayModeEnum.Always) || ((Viol.Type.OneLineElement == MM_AlarmViolation_Type.DisplayModeEnum.WhenSelected) && (ShownViolations.ContainsKey(Viol))))
                        {
                            if ((WorstViolation == null) || (Viol.Type.ViolationIndex < WorstViolation.ViolationIndex))
                            {
                                WorstViolation = Viol.Type;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MM_System_Interfaces.LogError(ex);
            }
            return(WorstViolation);
        }