static void SendOneWayQuery(string query)
        {
            #region Authorizing on remote machine
            // Get rights to access remote machine.
            //
            // If you use anonymous conection than you need to apply server's LSA (LocalSecurityAuthority) rules:
            // - permit Guest connection over network.
            // - activate Guest user.
            // Without this conection will terminated by server.
            //
            // Relative to setting of pipes also could be required:
            // - anonymous access to named pipes
            //
            // ATTENTION: Message will not be encrypted before post.
            // User SetRoutingInstruction (whrer instruction has RSAEncryption fields as true) instead TryLogon.
            bool logonResult = General.TryToLogonAtRemoteDevice(
                routingInstruction.logonConfig,
                out SafeAccessTokenHandle safeTokenHandle);
            if (!logonResult)
            {
                Console.WriteLine("Logon failed. Connection not possible.\nPress any key...");
                Console.ReadKey();
                return;
            }
            #endregion

            // Create transmission line.
            TransmissionLine lineProcessor = OpenOutTransmissionLineViaPP(SERVER_NAME, SERVER_PIPE_NAME);
            // Set impersonate token.
            lineProcessor.accessToken = safeTokenHandle;

            // Add sample query to queue. You can use this way if you not need answer from server.
            lineProcessor.EnqueueQuery(new Query(query));
        }
Beispiel #2
0
        public TransmissionLineDetailViewModel(object transmissionLine)
        {
            if (transmissionLine != null && transmissionLine is TransmissionLine)
            {
                m_transmissionLine = transmissionLine as TransmissionLine;

                GetDivisions();
                GetSubstations();
            }
        }
 /// <summary>
 /// The designated initializer for the <see cref="SynchrophasorAnalytics.Modeling.Node"/> class which requires the <see cref="SynchrophasorAnalytics.Modeling.VoltageLevel.InternalID"/> of the <see cref="SynchrophasorAnalytics.Modeling.VoltageLevel"/> and the required properties defined by the <see cref="SynchrophasorAnalytics.Modeling.INetworkDescribable"/> interface as well as references to its parent <see cref="SynchrophasorAnalytics.Modeling.Substation"/> and/or <see cref="SynchrophasorAnalytics.Modeling.TransmissionLine"/>.
 /// </summary>
 /// <param name="internalID">An integer identifier for each <see cref="SynchrophasorAnalytics.Modeling.Node"/> which is intended to be unique among other objects of the same type.</param>
 /// <param name="number">A descriptive integer for the instance of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>. There are no restrictions on uniqueness.</param>
 /// <param name="acronym">A string acronym for the instance of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 /// <param name="name">The string name of the instance of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 /// <param name="description">A string description of the instance of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 /// <param name="voltageLevelID">The <see cref="SynchrophasorAnalytics.Modeling.VoltageLevel.InternalID"/> of the <see cref="SynchrophasorAnalytics.Modeling.VoltageLevel"/> of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 /// <param name="parentSubstation">The parent <see cref="SynchrophasorAnalytics.Modeling.Substation"/> of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 /// <param name="parentTransmissionLine">The parent <see cref="SynchrophasorAnalytics.Modeling.TransmissionLine"/> of the <see cref="SynchrophasorAnalytics.Modeling.Node"/>.</param>
 public Node(int internalID, int number, string acronym, string name, string description, int voltageLevelID, Substation parentSubstation, TransmissionLine parentTransmissionLine)
 {
     m_internalID             = internalID;
     m_number                 = number;
     m_acronym                = acronym;
     m_name                   = name;
     m_description            = description;
     m_voltageLevelID         = voltageLevelID;
     m_parentSubstation       = parentSubstation;
     m_parentTransmissionLine = parentTransmissionLine;
 }
Beispiel #4
0
        public bool TryMerge(ObservableIsland island, NetworkModel model)
        {
            TransmissionLine connectingLine = ConnectingLineBetween(island, model);

            if (connectingLine != null)
            {
                m_substations.AddRange(island.Substations);
                return(true);
            }
            return(false);
        }
Beispiel #5
0
        /// <summary>
        /// Adds a query to the queue.
        /// Opens a backward line that will calls an answer handler.
        /// </summary>
        /// <param name="line">Line proccessor that control queries posting to target server.</param>
        /// <param name="query">Query that will sent to server.</param>
        /// <param name="answerHandler">Callback that will recive answer.</param>
        public static void EnqueueDuplexQueryViaPP(
            TransmissionLine line,
            UniformQueries.Query query,
            Action <TransmissionLine, UniformQueries.Query> answerHandler)
        {
            // Add our query to line processor queue.
            line.EnqueueQuery(query);

            // Open backward chanel to recive answer from server.
            ReceiveDelayedAnswerViaPP(line, query, answerHandler);
        }
Beispiel #6
0
        private void BuildVertexSet(TransmissionLine transmissionLine)
        {
            m_vertexSet = new List <Node>();

            foreach (Node node in transmissionLine.Nodes)
            {
                m_vertexSet.Add(node);
            }

            // The FromNode and ToNode are children of the FromSubstation and ToSubstation respectively but should be included in this vertex set.
            m_vertexSet.Add(transmissionLine.FromNode);
            m_vertexSet.Add(transmissionLine.ToNode);
        }
Beispiel #7
0
        /// <summary>
        /// Adds a query to the queue.
        /// Opens a backward line that will calls an answer handler.
        /// </summary>
        /// <param name="serverName">Name of the server. "." if local.</param>
        /// <param name="serverPipeName">Name of pipe provided by server.</param>
        /// <param name="query">Query that will sent to server.</param>
        /// <param name="answerHandler">Callback that will recive answer.</param>
        /// <returns>Established transmission line.</returns>
        public static TransmissionLine EnqueueDuplexQueryViaPP(
            string serverName,
            string serverPipeName,
            UniformQueries.Query query,
            Action <TransmissionLine, UniformQueries.Query> answerHandler)
        {
            // Open transmission line.
            TransmissionLine line = OpenOutTransmissionLineViaPP(serverName, serverPipeName);

            // Equeue query to line.
            EnqueueDuplexQueryViaPP(line, query, answerHandler);

            return(line);
        }
Beispiel #8
0
        /// <summary>
        /// Open a line that will be ready to recive server answer.
        /// New line will created related to params of requesting line and sended query.
        ///
        /// Attention: Not work with broadcasting server.
        /// </summary>
        /// <param name="line">Line that was used to transmition</param>
        /// <param name="answerHandler">Delegate that will be called as handler for answer processing.
        /// TransmissionLine contain data about actual transmission.
        /// object contain recived query (usualy string or byte[]).</param>
        /// <param name="entryQuery">Query that was recived from client.
        /// Method will detect core part and establish backward connection.</param>
        /// <returns></returns>
        public static bool ReceiveDelayedAnswerViaPP(
            TransmissionLine line,
            UniformQueries.Query entryQuery,
            Action <TransmissionLine, UniformQueries.Query> answerHandler)
        {
            #region Create backward domain
            // Try to compute bacward domaint to contact with client.
            if (!UniformQueries.QueryPart.TryGetBackwardDomain(entryQuery, out string domain))
            {
                Console.WriteLine("ERROR (BCRA0): Unable to buid backward domain. QUERY: " + entryQuery.ToString());
                return(false);
            }
            #endregion

            #region Append answer handler to backward table.
            string hashKey = line.ServerName + "\\" + domain;
            // Try to load registred callback to overriding.
            if (DuplexBackwardCallbacks[hashKey] is
                System.Action <TransmissionLine, UniformQueries.Query> registredCallback)
            {
                DuplexBackwardCallbacks[hashKey] = answerHandler;
            }
            else
            {
                // Add colback to table as new.
                DuplexBackwardCallbacks.Add(hashKey, answerHandler);
            }
            #endregion

            #region Opening transmition line
            // Create transmission line.
            TransmissionLine lineProcessor = OpenTransmissionLineViaPP(
                new Standard.SimpleClient(),
                line.ServerName, domain,
                ref line.accessToken,
                HandlerInputTransmissionAsync);

            // Set input direction.
            lineProcessor.Direction = TransmissionLine.TransmissionDirection.In;
            #endregion

            // Skip line
            Console.WriteLine();
            return(true);
        }
Beispiel #9
0
        private void BuildEdgeSet(TransmissionLine transmissionLine)
        {
            m_edgeSet = new List <ITwoTerminal>();

            foreach (LineSegment lineSegment in transmissionLine.LineSegments)
            {
                m_edgeSet.Add(lineSegment);
            }

            foreach (Switch circuitSwitch in transmissionLine.Switches)
            {
                m_edgeSet.Add(circuitSwitch);
            }

            foreach (SeriesCompensator seriesCompensationDevice in transmissionLine.SeriesCompensators)
            {
                m_edgeSet.Add(seriesCompensationDevice);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Recive message from broadcasting server.
        /// ATTENTION: Eould connect to server as guest user.
        /// </summary>
        /// <param name="serverName">Srver name or ip.</param>
        /// <param name="pipeName">Name of pipe started on server.</param>
        /// <param name="answerHandler">Delegate that would to call when message received.</param>
        /// <returns>Created line.</returns>
        public static TransmissionLine ReceiveAnonymousBroadcastMessage(
            string serverName,
            string pipeName,
            Action <TransmissionLine, UniformQueries.Query> answerHandler)
        {
            #region Append answer handler to backward table.
            string hashKey = serverName + "\\" + pipeName;
            // Try to load registred callback to overriding.
            if (DuplexBackwardCallbacks[hashKey] is
                System.Action <TransmissionLine, UniformQueries.Query> registredCallback)
            {
                // Override current delegate.
                DuplexBackwardCallbacks[hashKey] = answerHandler;
            }
            else
            {
                // Add callback to table as new.
                DuplexBackwardCallbacks.Add(hashKey, answerHandler);
            }
            #endregion

            #region Opening transmition line
            // Create transmission line.
            Console.WriteLine("RABM: Oppening line to " + serverName + "/" + pipeName);
            TransmissionLine line = OpenTransmissionLineViaPP(
                serverName, pipeName,
                HandlerInputTransmissionAsync);

            // Set input direction.
            line.Direction = TransmissionLine.TransmissionDirection.In;
            #endregion

            // Skip line
            Console.WriteLine();

            // Return created line.
            return(line);
        }
Beispiel #11
0
    private void Start()
    {
        Transmitters = FindObjectsOfType <Transmitter>();

        foreach (TransmissionLink link in TransmissionLinks)
        {
            TransmissionLine line = Instantiate(TransmissionLinePrefab);
            line.Link       = link;
            line.Controller = this;

            Transmitter t1 = Transmitters.First(t => t.Id == link.Transmitter1);
            Transmitter t2 = Transmitters.First(t => t.Id == link.Transmitter2);

            Vector3[] pos = new Vector3[]
            {
                Transmitters.First(t => t.Id == link.Transmitter1).transform.position,
                Transmitters.First(t => t.Id == link.Transmitter2).transform.position
            };

            line.LineRenderer.SetPositions(pos);
            line.LineRenderer.startWidth = .1f;
            line.LineRenderer.startWidth = .2f;

            t1.Links.Add(new Link()
            {
                Other = t2,
                TLink = link
            });

            t2.Links.Add(new Link()
            {
                Other = t1,
                TLink = link
            });
        }
    }
Beispiel #12
0
 private static void DeleteTransmissionLine(TransmissionLine transmissionLine)
 {
     transmissionLine.ParentDivision.TransmissionLines.Remove(transmissionLine);
 }
Beispiel #13
0
        /// <summary>
        /// Redirect recived query from current server to other.
        /// </summary>
        /// <param name="tc">Server's transmission controller.</param>
        /// <param name="query">Query received from client.</param>
        public static void QueryHandler_DuplexRelay(BaseServerTransmissionController tc, UniformQueries.Query query)
        {
            bool decryptionComplete = false;
            bool decryptionResult   = false;

            Task decryptionOperation = new Task(async delegate()
            {
                // Try to encrypt receved message.
                decryptionResult = await EnctyptionOperatorsHandler.TryToDecryptAsync(
                    query,
                    EnctyptionOperatorsHandler.AsymmetricEO);

                decryptionComplete = true;
            });

            decryptionOperation.Start();

            // Whait for decription completing.
            while (!decryptionComplete)
            {
                Thread.Sleep(5);
            }

            // Loging error to client.
            if (!decryptionResult)
            {
                // Try to get answer in string format.
                SendAnswerViaPP("DUPLEX RELEAY ERROR: Data corrupted." +
                                " Decryption not possible. Relay terminated.", query);
                return;
            }

            // Detect routing target.
            bool relayTargetFound =
                UniformClient.BaseClient.routingTable.
                TryGetRoutingInstruction(query, out Instruction instruction);

            // If instruction not found.
            if (!relayTargetFound)
            {
                // If reley target not found then server will mean that query requested to itself.
                PipesProvider.Handlers.Queries.ProcessingAsync(tc, query);

                //// Log
                //Console.WriteLine("RELAY TARGET NOT FOUND: {q}", query);

                //// DO BACKWARED ERROR INFORMATION.
                //SendAnswer("error=404", UniformQueries.API.DetectQueryParts(query));

                // Drop continue computing.
                return;
            }

            // Open connection.
            TransmissionLine tl = UniformClient.BaseClient.EnqueueDuplexQueryViaPP(
                instruction.routingIP,
                instruction.pipeName,
                query,
                // Delegate that will invoked when relayed server send answer.
                // Redirects the answer to a client.
                delegate(TransmissionLine answerTL, UniformQueries.Query receivedData)
            {
                // Try to get answer in string format.
                SendAnswerViaPP(receivedData, query);
                return;
            });
        }
        // Create delegate that will recive and procced the server's answer.
        static void ServerAnswerHandler_RSAPublicKey(TransmissionLine tl, object message)
        {
            string messageS = message as string;

            Console.WriteLine("RSA Public Key recived:\n" + (messageS ?? "Message is null"));
        }
Beispiel #15
0
        /// <summary>
        /// Provide complex initalization of all relative systems.
        /// Build meta data, regitrate line in common table.
        /// Start new thread to avoid freezes.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="token">Token that will be used for logon. on remote machine LSA.
        /// Sharing by ref to allow update in internal lines.</param>
        /// <param name="serverName">Name of IP adress of remote or local server.</param>
        /// <param name="pipeName">Name of the pipe started on the server.</param>
        /// <param name="callback">Method that will be called when connection will be established.</param>
        /// <returns>Opened transmission line. Use line.Enqueue to add your query.</returns>
        public static TransmissionLine OpenTransmissionLineViaPP(
            BaseClient client,
            string serverName,
            string pipeName,
            ref SafeAccessTokenHandle token,
            Action <TransmissionLine> callback)
        {
            lock (lineLocker)
            {
                // Validate client.
                if (client == null)
                {
                    Console.WriteLine("CLIENT is NULL (BC_OTL_0). Unable to open new transmission line.");
                    return(null);
                }

                // Get target GUID.
                string guid = TransmissionLine.GenerateGUID(serverName, pipeName);

                //// Try to load  trans line by GUID.
                //ClientAPI.TryGetTransmissionLineByGUID(guid, out TransmissionLine trnsLine);

                //if (trnsLine != null &&
                //    trnsLine.Direction == TransmissionLine.TransmissionDirection.Out)
                if (ClientAPI.TryGetTransmissionLineByGUID(guid, out TransmissionLine trnsLine))
                {
                    // If not obsolterd transmission line then drop operation.
                    if (!trnsLine.Closed)
                    {
                        Console.WriteLine("OTL {0} | FOUND", guid);
                        return(trnsLine);
                    }
                    else
                    {
                        // Unregister line and recall method.
                        ClientAPI.TryToUnregisterTransmissionLine(guid);

                        Console.WriteLine("OTL {0} | RETRY", guid);

                        // Retry.
                        return(OpenTransmissionLineViaPP(client, serverName, pipeName, ref token, callback));
                    }
                }
                // If full new pipe.
                else
                {
                    // Create new if not registred.
                    trnsLine = new TransmissionLine(
                        serverName,
                        pipeName,
                        callback,
                        ref token);

                    // Request thread start but let a time quantum only when this thread will pass order.
                    _ = StartPPClientThreadAsync(client, guid, trnsLine);
                }

                // Return oppened line.
                return(trnsLine);
            }
        }
 /// <summary>
 /// Allow to start thread but previous return turn to current thread.
 /// Allow to use single line queries.
 /// </summary>
 /// <param name="client"></param>
 /// <param name="guid"></param>
 /// <param name="trnsLine"></param>
 protected static async Task StartPPClientThreadAsync(BaseClient client, string guid, TransmissionLine trnsLine)
 {
     await Task.Run(() => {
         client.StartClientThread(
             guid,
             trnsLine,
             TransmissionLine.ThreadLoop);
     });
 }
Beispiel #17
0
        /// <summary>
        /// Requsting a public encryption key from a server definded into the instruction.
        /// </summary>
        /// <param name="pai">An instruction that would be used for routing to target server.</param>
        /// <returns>A started async task that returns result of keys exchanging process.</returns>
        private static async Task <bool> RequestPublicEncryptionKeyAsync(PartialAuthorizedInstruction pai)
        {
            // TODO not work.

            // Create base part of query for reciving of public RSA key.
            UniformQueries.Query query = null;

            try
            {
                query = new UniformQueries.Query(
                    null,
                    new UniformQueries.QueryPart("token", pai.GuestToken),
                    new UniformQueries.QueryPart("get"),
                    new UniformQueries.QueryPart("publickey"),
                    new UniformQueries.QueryPart("guid", pai.GetHashCode().ToString()))
                {
                    WaitForAnswer = true // Request waiting for answer before computing of the next query in queue.
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encryption failed (rpeka10): " + ex.Message);
                return(false);
            }

            // Getting line to prevent conflict.
            TransmissionLine line = OpenOutTransmissionLineViaPP(pai.routingIP, pai.pipeName);

            // Insert query to processing with termination of current query.
            line.InsertQuery(query, true);

            bool result    = false;
            bool completed = false;

            // Open backward chanel to recive answer from server.
            ReceiveDelayedAnswerViaPP(line, query,
                                      // Create callback delegate that will set recived value to routing table.
                                      delegate(TransmissionLine answerLine, UniformQueries.Query answer)
            {
                // Try to apply recived answer.
                result = pai.AsymmetricEncryptionOperator.UpdateWithQuery(answer);

                // Log about update
                Console.WriteLine("{0}/{1}: \"{2}\" public key updating status {3}",
                                  pai.routingIP, pai.pipeName,

                                  PipesProvider.Security.Encryption.EnctyptionOperatorsHandler
                                  .GetOperatorCode(pai.AsymmetricEncryptionOperator),

                                  result);

                // Finalize operation.
                completed = true;
            });

            // Wait for result.
            while (!completed)
            {
                await Task.Delay(20, ClientAppConfigurator.TerminationTokenSource.Token);
            }

            return(result);
        }
Beispiel #18
0
        public void Filter(List <string> companyNames)
        {
            List <Company>           retainedCompanies         = new List <Company>();
            List <Division>          retainedDivisions         = new List <Division>();
            List <Station>           retainedStations          = new List <Station>();
            List <Station>           stationsToRemove          = new List <Station>();
            List <Node>              retainedNodes             = new List <Node>();
            List <Node>              nodesToRemove             = new List <Node>();
            List <LineSegment>       lineSegmentsToRemove      = new List <LineSegment>();
            List <TransmissionLine>  transmissionLinesToRemove = new List <TransmissionLine>();
            List <CircuitBreaker>    circuitBreakersToRemove   = new List <CircuitBreaker>();
            List <Shunt>             shuntsToRemove            = new List <Shunt>();
            List <Transformer>       transformersToRemove      = new List <Transformer>();
            List <TransformerTap>    retainedTaps = new List <TransformerTap>();
            List <ParentTransformer> parentTransformersToRemove = new List <ParentTransformer>();

            Console.WriteLine("1");
            // Line segments, companies, stations
            Parallel.ForEach(m_lineSegments, (lineSegment) =>
            {
                string fromNodeId   = $"{lineSegment.FromStationName}_{lineSegment.FromNodeId}";
                string toNodeId     = $"{lineSegment.ToStationName}_{lineSegment.ToNodeId}";
                Node fromNode       = m_nodes.Find(x => $"{x.StationName}_{x.Id}" == fromNodeId);
                Node toNode         = m_nodes.Find(x => $"{x.StationName}_{x.Id}" == toNodeId);
                Company fromCompany = GetNodeCompany(fromNode);
                Company toCompany   = GetNodeCompany(toNode);

                Station fromStation = m_stations.Find(x => x.Name == lineSegment.FromStationName);
                Station toStation   = m_stations.Find(x => x.Name == lineSegment.ToStationName);

                if (companyNames.Contains(fromCompany.Name) || companyNames.Contains(toCompany.Name))
                {
                    if (!retainedStations.Contains(fromStation))
                    {
                        retainedStations.Add(fromStation);
                    }
                    if (!retainedStations.Contains(toStation))
                    {
                        retainedStations.Add(toStation);
                    }
                    if (!retainedNodes.Contains(fromNode))
                    {
                        retainedNodes.Add(fromNode);
                    }
                    if (!retainedNodes.Contains(toNode))
                    {
                        retainedNodes.Add(toNode);
                    }
                    if (!retainedCompanies.Contains(fromCompany))
                    {
                        retainedCompanies.Add(fromCompany);
                    }
                    if (!retainedCompanies.Contains(toCompany))
                    {
                        retainedCompanies.Add(toCompany);
                    }
                }
                else
                {
                    if (!lineSegmentsToRemove.Contains(lineSegment))
                    {
                        lineSegmentsToRemove.Add(lineSegment);
                    }
                    if (!stationsToRemove.Contains(fromStation))
                    {
                        stationsToRemove.Add(fromStation);
                    }
                    if (!stationsToRemove.Contains(toStation))
                    {
                        stationsToRemove.Add(toStation);
                    }
                }
            });

            Console.WriteLine("2");
            // Transmission Lines
            foreach (LineSegment lineSegment in lineSegmentsToRemove)
            {
                TransmissionLine transmissionLine = m_transmissionLines.Find(x => x.Id == lineSegment.TransmissionLineId);
                if (!transmissionLinesToRemove.Contains(transmissionLine))
                {
                    transmissionLinesToRemove.Add(transmissionLine);
                }
            }

            Console.WriteLine("3");
            // Nodes
            foreach (Station station in stationsToRemove)
            {
                List <Node> stationNodes = m_nodes.FindAll(x => x.StationName == station.Name);
                foreach (Node node in stationNodes)
                {
                    if (!nodesToRemove.Contains(node))
                    {
                        nodesToRemove.Add(node);
                    }
                }
            }

            Console.WriteLine("4");
            // Divisions
            foreach (Station station in retainedStations)
            {
                List <Node> stationNodes = m_nodes.FindAll(x => x.StationName == station.Name);
                foreach (Node node in stationNodes)
                {
                    Division division = m_divisions.Find(x => x.Name == node.DivisionName);

                    if (!retainedDivisions.Contains(division))
                    {
                        retainedDivisions.Add(division);
                    }
                }
            }

            Console.WriteLine("5");
            // Circuit breakers
            foreach (CircuitBreaker breaker in m_circuitBreakers)
            {
                Station parentStation = m_stations.Find(x => x.Name == breaker.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!circuitBreakersToRemove.Contains(breaker))
                    {
                        circuitBreakersToRemove.Add(breaker);
                    }
                }
            }


            Console.WriteLine("6");
            // shunts
            foreach (Shunt shunt in m_shunts)
            {
                Station parentStation = m_stations.Find(x => x.Name == shunt.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!shuntsToRemove.Contains(shunt))
                    {
                        shuntsToRemove.Add(shunt);
                    }
                }
            }

            Console.WriteLine("7");
            // Transformers and Transformer Taps
            foreach (Transformer transformer in m_transformers)
            {
                Station parentStation = m_stations.Find(x => x.Name == transformer.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!transformersToRemove.Contains(transformer))
                    {
                        transformersToRemove.Add(transformer);
                    }
                }
                else
                {
                    TransformerTap fromTap = m_transformerTaps.Find(x => x.Id == transformer.FromNodeTap);
                    TransformerTap toTap   = m_transformerTaps.Find(x => x.Id == transformer.ToNodeTap);
                    if (!retainedTaps.Contains(fromTap))
                    {
                        retainedTaps.Add(fromTap);
                    }
                    if (!retainedTaps.Contains(toTap))
                    {
                        retainedTaps.Add(toTap);
                    }
                }
            }
            Console.WriteLine("8");
            // Parent Transformer
            foreach (Transformer transformer in transformersToRemove)
            {
                ParentTransformer parentTransformer = m_parentTransformers.Find(x => x.Id == transformer.Parent);
                if (!parentTransformersToRemove.Contains(parentTransformer))
                {
                    parentTransformersToRemove.Add(parentTransformer);
                }
            }
            m_companies       = retainedCompanies;
            m_divisions       = retainedDivisions;
            m_transformerTaps = retainedTaps;

            Console.WriteLine("9");
            foreach (Station station in stationsToRemove)
            {
                m_stations.Remove(station);
            }

            foreach (LineSegment lineSegment in lineSegmentsToRemove)
            {
                m_lineSegments.Remove(lineSegment);
            }

            foreach (Node node in nodesToRemove)
            {
                m_nodes.Remove(node);
            }

            foreach (Shunt shunt in shuntsToRemove)
            {
                m_shunts.Remove(shunt);
            }

            foreach (CircuitBreaker breaker in circuitBreakersToRemove)
            {
                m_circuitBreakers.Remove(breaker);
            }

            foreach (Transformer transformer in transformersToRemove)
            {
                m_transformers.Remove(transformer);
            }

            foreach (ParentTransformer transformer in parentTransformersToRemove)
            {
                m_parentTransformers.Remove(transformer);
            }

            foreach (TransmissionLine transmissionLine in transmissionLinesToRemove)
            {
                m_transmissionLines.Remove(transmissionLine);
            }
        }
        /// <summary>
        /// Validates and fixed a configuration and params of the transmission line.
        /// </summary>
        /// <param name="line">A transmission line for configuration.</param>
        /// <returns>A result of configurating. False if failed.</returns>
        public static async Task <bool> ConfigurateTransmissionLineAsync(TransmissionLine line)
        {
            if (line.RoutingInstruction != null) // Routing instruction applied.
            {
                // Is partial autorized instruction.
                if (line.RoutingInstruction is PartialAuthorizedInstruction pai)
                {
                    #region Token validation
                    // If token not exist, or emoty, or expired.
                    if (line.LastQuery.Data.TryGetParamValue("token", out UniformQueries.QueryPart token))
                    {
                        // If token value is emoty.
                        if (string.IsNullOrEmpty(token.PropertyValueString))
                        {
                            if (await TokenValidation(pai))
                            {
                                // Apply received token.
                                line.LastQuery.Data.SetParam(new UniformQueries.QueryPart("token", pai.GuestToken));
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        // Validate token
                        if (await TokenValidation(pai))
                        {
                            // Add tokent to query,
                            line.LastQuery.Data.ListedContent?.Add(new UniformQueries.QueryPart("token", pai.GuestToken));
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    #region Methods
                    // Trying to porovide valid guest token.
                    // Returns result of validation. False - token invalid.
                    async Task <bool> TokenValidation(PartialAuthorizedInstruction instruction)
                    {
                        // If guest token is not found or expired.
                        if (pai.GuestToken == null ||
                            UniformQueries.Tokens.IsExpired(instruction.GuestToken, instruction.GuestTokenHandler.ExpiryTime))
                        {
                            // Wait for token.
                            if (!await pai.TryToGetGuestTokenAsync(ClientAppConfigurator.TerminationTokenSource.Token))
                            {
                                return(false);
                            }
                        }

                        return(true);
                    }

                    #endregion
                    #endregion

                    #region Encriprion operators validation
                    if (line.LastQuery.Data.IsEncrypted && // Is query require encryption? (Query can't be encrypted if that query must request key for encryption.)
                        line.RoutingInstruction != null && // Is routing instruction is valid and allow encryption?
                        line.RoutingInstruction.encryption)
                    {
                        // Check asymmetric operator.
                        if (pai.AsymmetricEncryptionOperator == null)
                        {
                            Console.WriteLine("Encryption operator not configurated. Operation declined.");
                            return(false);
                        }

                        #region Receiving public key from intruction's target server
                        // Check if operator is valid.
                        if (!pai.AsymmetricEncryptionOperator.IsValid)
                        {
                            try
                            {
                                // Start async key exchanging.
                                var keysExchangingOperator = RequestPublicEncryptionKeyAsync(pai);

                                try
                                {
                                    if (!keysExchangingOperator.IsCompleted)
                                    {
                                        keysExchangingOperator.Start();
                                    }
                                }
                                catch { };

                                // Drop current query as invalid cause encryption operator still in processing.
                                line.Processing = false;
                                return(false);
                            }
                            catch (Exception ex)
                            {
                                // Unlock loop.
                                line.Processing = false;
                                Console.WriteLine("SECRET KEY ERROR (bcpph1): " + ex.Message);
                                return(false);
                            }
                        }
                        #endregion

                        #region Adding public key for backward encryption if not added yet
                        if (!line.LastQuery.Data.QueryParamExist("pk"))
                        {
                            line.LastQuery.Data.SetParam(new UniformQueries.QueryPart(
                                                             "pk",
                                                             EnctyptionOperatorsHandler.AsymmetricEO.EncryptionKey));
                        }
                        #endregion

                        // Encrypt query by public key of target server.
                        return(await EnctyptionOperatorsHandler.TryToEncryptAsync(
                                   line.LastQuery.Data,
                                   line.RoutingInstruction.sEncCode,
                                   line.RoutingInstruction.AsymmetricEncryptionOperator,
                                   ClientAppConfigurator.TerminationTokenSource.Token));
                    }
                    #endregion
                }
            }

            return(true);
        }
 public TransmissionLineOPFResult(TransmissionLine transmissionLine, double power_flow)
 {
     this.TransmissionLine = transmissionLine;
     this.PowerFlow = power_flow;
 }
Beispiel #21
0
 /// <summary>
 /// The designated constructor for the <see cref="LinearStateEstimator.Graphs.TransmissionLineGraph"/> class. Requires a reference to a <see cref="LinearStateEstimator.Modeling.TransmissionLine"/> of interest.
 /// </summary>
 /// <param name="transmissionLine">The <see cref="LinearStateEstimator.Modeling.TransmissionLine"/> desired to represent as a graph.</param>
 public TransmissionLineGraph(TransmissionLine transmissionLine)
 {
     m_transmissionLine = transmissionLine;
     BuildVertexSet(transmissionLine);
     BuildEdgeSet(transmissionLine);
 }