Example #1
0
        private void CloseModelLinks(ModelPath modelPath)
        {
            // Access transmission data in the given file
            TransmissionData trans = TransmissionData.ReadTransmissionData(modelPath);

            if (trans != null)
            {
                // collect all external references
                var externalReferences = trans.GetAllExternalFileReferenceIds();
                foreach (ElementId extRefId in externalReferences)
                {
                    var extRef = trans.GetLastSavedReferenceData(extRefId);
                    if (extRef.ExternalFileReferenceType == ExternalFileReferenceType.RevitLink)
                    {
//                        var p = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetPath());
                        //set data
                        trans.SetDesiredReferenceData(extRefId, extRef.GetPath(), extRef.PathType, false);
                        Debug.Write($"{extRef.GetPath().CentralServerPath} " +
                                    $"{extRef.GetPath().ServerPath}");
                    }
                }
                // make sure the IsTransmitted property is set
                trans.IsTransmitted = true;

                // modified transmissoin data must be saved back to the model
                TransmissionData.WriteTransmissionData(modelPath, trans);
            }
        }
Example #2
0
        /// <summary>Processes a client request.</summary>
        /// <param name="clientRequest">The client request to process.</param>
        protected virtual void Process(ClientRequest clientRequest)
        {
            if (clientRequest is null)
            {
                throw new ArgumentNullException(nameof(clientRequest));
            }
            try
            {
                switch (clientRequest.RequestedAction)
                {
                case RequestedAction.GetAllCases:
                    CasesDataAccess  caseDataAccess = new CasesDataAccess();
                    List <Case>      cases          = new List <Case>();
                    Case[]           caseArray      = cases.ToArray();
                    TransmissionData transmission   = new TransmissionData(caseArray);
                    RespondToClient(transmission);
                    break;

                case RequestedAction.GetAllSummerysById:
                    SummeryDataAccess     summeryDataAccess = new SummeryDataAccess();
                    List <MettingSummery> summery           = summeryDataAccess.GetAllSummerysById();
                    TransmissionData      transmissionSum   = new TransmissionData(summery);
                    RespondToClient(transmissionSum);
                    break;

                case RequestedAction.GetAllCaseKinds:
                    break;

                case RequestedAction.SaveNewSummery:
                    SummeryDataAccess summeryData = new SummeryDataAccess();
                    foreach (MettingSummery item in clientRequest.Data.Entities)
                    {
                        summeryData.SafeSummery(item);
                    }

                    break;

                case RequestedAction.SaveNewCase:
                    CasesDataAccess caseData = new CasesDataAccess();
                    foreach (Case item in clientRequest.Data.Entities)
                    {
                        caseData.AddCase(item);
                    }
                    break;

                case RequestedAction.GetAllSecretaries:
                    break;

                case RequestedAction.GetAllCommands:
                    break;

                default:
                    break;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #3
0
        void GetKeynotesAssemblyCodesSharedParamAndLinks(IList <Document> targetDocumentsList, IList <string> targetList, Document activeDoc)
        {
            foreach (Document currentDoc in targetDocumentsList)
            {
                ModelPath        targetLocation = ModelPathUtils.ConvertUserVisiblePathToModelPath(currentDoc.PathName);
                TransmissionData targetData     = TransmissionData.ReadTransmissionData(targetLocation);

                if (targetData != null)
                {
                    ICollection <ElementId> externalReferences = targetData.GetAllExternalFileReferenceIds();

                    foreach (ElementId currentFileId in externalReferences)
                    {
                        if (currentFileId != ElementId.InvalidElementId)
                        {
                            ExternalFileReference extRef = targetData.GetLastSavedReferenceData(currentFileId);
                            //TODO CORRECT PROBLEMATIC IF STATEMENT HERE!!!!!!!!!!!!!!!!!!
                            if (extRef.GetLinkedFileStatus() != LinkedFileStatus.Invalid)
                            {
                                ModelPath currenFileLink = extRef.GetAbsolutePath();
                                if (!currenFileLink.Empty)
                                {
                                    string currentFileLinkString = ModelPathUtils.ConvertModelPathToUserVisiblePath(currenFileLink);
                                    CheckStringAValidLinkPathCorrectItAndAddToList(currentFileLinkString, targetList, activeDoc);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #4
0
        // bug683 fix: functie toegevoegd zodat IFC exporter selectief kan rapporteren welke files missen
        /// <summary>
        ///    Geef alle gelinkte files die niet langer gevonden kunnen worden
        /// </summary>
        /// <param name="app"></param>
        /// <param name="addProj"></param>
        /// <returns></returns>
        // ReSharper disable once UnusedMember.Global
        public static List <string> GetMissingLinkedFiles(UIApplication app, bool addProj)
        {
            List <string> linkedProjects = new List <string>();

            if (linkedProjects.Count == 0)
            {
                // er zijn waarschijnlijk worksets gebruikt
                ModelPath        mdlPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(app.ActiveUIDocument.Document.PathName);
                TransmissionData transData = TransmissionData.ReadTransmissionData(mdlPath);
                if (transData != null)
                {
                    ICollection <ElementId> externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (ElementId refId in externalReferences)
                    {
                        ExternalFileReference curRef = transData.GetLastSavedReferenceData(refId);
                        string refType = curRef.ExternalFileReferenceType.ToString();
                        string refPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(curRef.GetAbsolutePath());
                        if (refType == "RevitLink")
                        {
                            linkedProjects.Add(refPath);
                        }
                    }
                }
            }

            if (addProj)
            {
                linkedProjects.Add(app.ActiveUIDocument.Document.PathName);
            }

            //laatste check om te kijken of de links ook gevonden worden
            return(linkedProjects.Where(p => (false == File.Exists(p))).ToList());
        }
Example #5
0
    private void RpcReceiveBytes(int transmissionId, byte[] recBuffer)
    {
        //already completely received or not prepared?
        if (!clientTransmissionData.ContainsKey(transmissionId))
        {
            return;
        }

        //copy received data into prepared array and remember current dataposition
        TransmissionData dataToReceive = clientTransmissionData[transmissionId];

        System.Array.Copy(recBuffer, 0, dataToReceive.data, dataToReceive.curDataIndex, recBuffer.Length);
        dataToReceive.curDataIndex += recBuffer.Length;

        if (null != BeerPongOnDataFragmentReceived)
        {
            BeerPongOnDataFragmentReceived(transmissionId, recBuffer);
        }

        if (dataToReceive.curDataIndex < dataToReceive.data.Length - 1)
        {
            //current data not completely received
            return;
        }

        //current data completely received
        Debug.Log(LOG_PREFIX + "Completely Received Data at transmissionId=" + transmissionId);
        clientTransmissionData.Remove(transmissionId);

        if (null != BeerPongOnDataCompletelyReceived)
        {
            BeerPongOnDataCompletelyReceived.Invoke(transmissionId, dataToReceive.data);
        }
    }
Example #6
0
        public IPersistable SentRequestToServer(RequestedAction action, IPersistable data)
        {
            TransmissionData transmitData = new TransmissionData(data);

            byte[] buffer = Serializer <ClientRequest> .Serialize(new ClientRequest(action, transmitData));

            byte[] bufferReceiver = Transmit(buffer);
            return(Serializer <TransmissionData> .Deserialize(bufferReceiver).Entity);
        }
Example #7
0
        /// <summary>
        ///     Sets the revit link list.
        /// </summary>
        /// <param name="centralPath"></param>
        /// <param name="linkPaths"></param>
        public static void SetRevitLinkList(string centralPath, List <string> linkPaths)
        {
            if (centralPath is null)
            {
                throw new ArgumentNullException(nameof(centralPath));
            }

            if (linkPaths is null)
            {
                throw new ArgumentNullException(nameof(linkPaths));
            }

            var transData = TransmissionData.ReadTransmissionData(new FilePath(centralPath));

            if (transData is null)
            {
                return;
            }

            // If found not the link, don't submit, otherwise throw file writing exception.
            var flag = false;

            foreach (var referId in transData.GetAllExternalFileReferenceIds())
            {
                var extRef = transData.GetLastSavedReferenceData(referId);

                if (extRef.ExternalFileReferenceType != ExternalFileReferenceType.RevitLink)
                {
                    continue;
                }

                var userPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetPath());

                var linkPath = linkPaths.FirstOrDefault(w => w != null && userPath.Contains(Path.GetFileName(w)));

                if (linkPath is null)
                {
                    continue;
                }

                var elmId = extRef.GetReferencingId();

                transData.SetDesiredReferenceData(elmId, new FilePath(linkPath), PathType.Relative, true);

                flag = true;
            }

            if (!flag)
            {
                return;
            }

            transData.IsTransmitted = true;

            TransmissionData.WriteTransmissionData(new FilePath(centralPath), transData);
        }
Example #8
0
        public async void TestMethod1()
        {
            string sendText = TransmissionData.DataPackaging("Hello World", "All", "Text");
            await UDP_Util.UdpSend(sendText);

            await System.Threading.Tasks.Task.Run(async() =>
            {
                await UDP_Util.UdpSocket();
            });
        }
Example #9
0
        public DataHeader(int type, byte[] buffer, TransmissionData transmissionData)
        {
            DataContext.CheckedType(type);
            this.type             = type;
            this.buffer           = buffer;
            this.transmissionData = transmissionData;

            this.dataLength = buffer.Length;

            this.dataOffset = 0;
        }
Example #10
0
    private void RpcPrepareToReceiveBytes(int transmissionId, int expectedSize)
    {
        if (clientTransmissionData.ContainsKey(transmissionId))
        {
            return;
        }

        //prepare data array which will be filled chunk by chunk by the received data
        TransmissionData receivingData = new TransmissionData(new byte[expectedSize]);

        clientTransmissionData.Add(transmissionId, receivingData);
    }
 public void Tcp_DataReceivedEvent(TransmissionData transmissionData)
 {
     lock (lockObj)
     {
         try
         {
             this.Invoke(new Action(() => { ((DataGridView)this.Controls["dGrid"]).Rows.Add(transmissionData.TakeParameterForServer(transmissionData)); }));
         }
         catch (ObjectDisposedException)
         {
         }
     }
 }
Example #12
0
        // sample code from RevitAPI.chm entry
        // on the TransmissionData class:

        /// <summary>
        /// Unload all Revit links.
        /// This method will set all Revit links to be
        /// unloaded the next time the document at the
        /// given location is opened.
        /// The TransmissionData for a given document
        /// only contains top-level Revit links, not
        /// nested links.
        /// However, nested links will be unloaded if
        /// their parent links are unloaded, so this
        /// function only needs to look at the
        /// document's immediate links.
        /// </summary>
        void UnloadRevitLinks(ModelPath location)
        {
            // access transmission data in the given Revit file

            TransmissionData transData = TransmissionData
                                         .ReadTransmissionData(location);

            if (transData != null)
            {
                // collect all (immediate) external references in the model

                ICollection <ElementId> externalReferences
                    = transData.GetAllExternalFileReferenceIds();

                // find every reference that is a link

                foreach (ElementId refId in externalReferences)
                {
                    ExternalFileReference extRef
                        = transData.GetLastSavedReferenceData(refId);

                    if (extRef.ExternalFileReferenceType
                        == ExternalFileReferenceType.RevitLink)
                    {
                        // we do not want to change neither the
                        // path nor the path-type; we only want
                        // the links to be unloaded (shouldLoad
                        // = false)

                        transData.SetDesiredReferenceData(refId,
                                                          extRef.GetPath(), extRef.PathType, false);
                    }
                }

                // make sure the IsTransmitted property is set

                transData.IsTransmitted = true;

                // modified transmission data must be saved back to the model

                TransmissionData.WriteTransmissionData(
                    location, transData);
            }
            else
            {
                TaskDialog.Show(
                    "Unload Links",
                    "The document does not have any transmission data");
            }
        }
Example #13
0
        public IPersistable[] SentRequestToServer(RequestedAction action, List <IPersistable> data)
        {
            if (!client.Connected)
            {
                client.Connect(remoteEndPoint);
            }
            TransmissionData transmitData = new TransmissionData(data);

            byte[] buffer = Serializer <ClientRequest> .Serialize(new ClientRequest(action, transmitData));

            byte[] bufferReceiver = Transmit(buffer);
            client.Dispose();
            return(Serializer <TransmissionData> .Deserialize(bufferReceiver).Entities);
        }
Example #14
0
        /// <inheritdoc/>
        internal override int Execute(string args = null)
        {
            var filepath = _doc.PathName;

            if (filepath != null)
            {
                IList <Element> xRefLinks    = new List <Element>();
                var             modelPath    = ModelPathUtils.ConvertUserVisiblePathToModelPath(filepath);
                var             wasException = false;
                try
                {
                    var transData          = TransmissionData.ReadTransmissionData(modelPath);
                    var externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (var xRefId in externalReferences)
                    {
                        var externalReference = _doc.GetElement(xRefId);
                        if (ConfirmRemoval(externalReference))
                        {
                            xRefLinks.Add(externalReference);
                        }
                    }

                    HelperMethods.RemoveElements(Name, _doc, xRefLinks);
                }
                catch
                {
                    wasException = true;
                }

                try
                {
                    var linkTypesIds = new FilteredElementCollector(_doc).OfClass(typeof(RevitLinkType)).Select(l => l.Id).ToList();

                    HelperMethods.RemoveElements(Name, _doc, linkTypesIds);
                }
                catch
                {
                    wasException = true;
                }

                return(wasException ? 0 : 1);
            }

            // Модель должна быть сохранена для удаления внешних ссылок
            MessageBox.Show(Language.GetItem(RevitCommand.LangItem, "m1"), MessageBoxIcon.Alert);

            return(0);
        }
Example #15
0
        /// <summary>
        ///    Geef alle gelinkte files
        /// </summary>
        /// <param name="app"></param>
        /// <param name="addProj"></param>
        /// <returns></returns>
        public static List <string> GetLinkedFiles(UIApplication app, bool addProj)
        {
            List <string>            linkedProjects = new List <string>();
            List <RevitLinkInstance> instantiekes   =
                GetAllProjectElements(app.ActiveUIDocument.Document)
                .OfType <RevitLinkInstance>()
                .Where(c => c.Name.ToLower().Contains(".rvt"))
                .ToList();

            foreach (RevitLinkInstance rli in instantiekes)
            {
                if (rli.GetLinkDocument() == null)
                {
                    continue;
                }
                string linknaam = rli.GetLinkDocument().PathName;
                if (!linkedProjects.Contains(linknaam))
                {
                    linkedProjects.Add(linknaam);
                }
            }
            if (linkedProjects.Count == 0)
            {
                // er zijn waarschijnlijk worksets gebruikt
                ModelPath        mdlPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(app.ActiveUIDocument.Document.PathName);
                TransmissionData transData = TransmissionData.ReadTransmissionData(mdlPath);
                if (transData != null)
                {
                    ICollection <ElementId> externalReferences = transData.GetAllExternalFileReferenceIds();
                    foreach (ElementId refId in externalReferences)
                    {
                        ExternalFileReference curRef = transData.GetLastSavedReferenceData(refId);
                        string refType = curRef.ExternalFileReferenceType.ToString();
                        string refPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(curRef.GetAbsolutePath());
                        if (refType == "RevitLink")
                        {
                            linkedProjects.Add(refPath);
                        }
                    }
                }
            }
            if (addProj)
            {
                linkedProjects.Add(app.ActiveUIDocument.Document.PathName);
            }
            //laatste check om te kijken of de links ook gevonden worden
            return(linkedProjects.Where(File.Exists).ToList());
        }
Example #16
0
        public bool SendOpenPortRequest(
            OpenPortRequest request,
            string password)
        {
            var key            = _configuration.LoadPrivateKey(_clientName);
            var requestInBytes = Encoding.UTF8.GetBytes(
                JsonConvert.SerializeObject(request, Formatting.Indented));
            var signature      = Encryptor.Sign(requestInBytes, key, password);
            var dataToTransmit = new TransmissionData(_clientName, requestInBytes, signature);

            var streamToTransmit = Encoding.UTF8.GetBytes(
                JsonConvert.SerializeObject(dataToTransmit, Formatting.Indented));

            OnSendRequest(streamToTransmit);
            return(true);
        }
Example #17
0
    public IEnumerator SendBytesToClientsRoutine(int transmissionId, byte[] data)
    {
        Debug.Assert(!serverTransmissionIds.Contains(transmissionId));
        Debug.Log(LOG_PREFIX + "SendBytesToClients processId=" + transmissionId + " | datasize=" + data.Length);

        //tell client that he is going to receive some data and tell him how much it will be.
        RpcPrepareToReceiveBytes(transmissionId, data.Length);
        yield return(null);

        //begin transmission of data. Send chunks of 'bufferSize' until completely transmitted.
        serverTransmissionIds.Add(transmissionId);
        TransmissionData dataToTransmit = new TransmissionData(data);
        int bufferSize = defaultBufferSize;

        while (dataToTransmit.curDataIndex < dataToTransmit.data.Length - 1)
        {
            //determine the remaining amount of bytes, still need to be sent.
            int remaining = dataToTransmit.data.Length - dataToTransmit.curDataIndex;
            if (remaining < bufferSize)
            {
                bufferSize = remaining;
            }

            //prepare the chunk of data which will be sent in this iteration
            byte[] buffer = new byte[bufferSize];
            System.Array.Copy(dataToTransmit.data, dataToTransmit.curDataIndex, buffer, 0, bufferSize);

            //send the chunk
            RpcReceiveBytes(transmissionId, buffer);
            dataToTransmit.curDataIndex += bufferSize;

            yield return(null);

            if (null != BeerPongOnDataFragmentSent)
            {
                BeerPongOnDataFragmentSent.Invoke(transmissionId, buffer);
            }
        }

        //transmission complete.
        serverTransmissionIds.Remove(transmissionId);

        if (null != BeerPongOnDataCompletelySent)
        {
            BeerPongOnDataCompletelySent.Invoke(transmissionId, dataToTransmit.data);
        }
    }
Example #18
0
    private IEnumerator SendBytesToServerRoutine(int transmissionId, byte[] data)
    {
        Debug.Log(LOG_PREFIX + "SendBytesToClients processId=" + transmissionId + " | datasize=" + data.Length);

        //tell Server that he is going to receive some data and tell him how much it will be.
        CmdPrepareToReceiveData(transmissionId, data.Length);
        yield return(null);

        // Begin transmission of data. send chunks of 'bufferSize' until completely transmitted
        ClientTransmissionIds.Add(transmissionId);
        TransmissionData DataToTransmit = new TransmissionData(data);
        int BufferSize = defaultBufferSize;

        while (DataToTransmit.CurrentDataIndex < DataToTransmit.data.Length - 1)
        {
            // determine the remaining amount of bytes, still need to be sent.
            int remaining = DataToTransmit.data.Length - DataToTransmit.CurrentDataIndex;
            // in case last chunk
            if (remaining < BufferSize)
            {
                BufferSize = remaining;
            }

            // prepare the chunks of data which will be sent in this iteration
            byte[] buffer = new byte[BufferSize];
            Array.Copy(DataToTransmit.data, DataToTransmit.CurrentDataIndex, buffer, 0, BufferSize);

            // send the chunk of data which will be sent in this iteration
            CmdReceiveBytes(transmissionId, buffer);
            DataToTransmit.CurrentDataIndex += BufferSize;

            yield return(null);

            if (OnDataFragmentSent != null)
            {
                OnDataFragmentSent(transmissionId, buffer);
            }
        }

        // TransmissionComplete
        ClientTransmissionIds.Remove(transmissionId);
        if (OnDataComepletelySent != null)
        {
            OnDataComepletelySent(transmissionId, DataToTransmit.data);
        }
    }
Example #19
0
        /// <summary>Responds to the <see cref="connectedClient"/> with the provided <see cref="TransmissionData"/>.</summary>
        /// <param name="transmissionData">The <see cref="TransmissionData"/> object to transmit to the <see cref="connectedClient"/> as a response.</param>
        protected virtual void RespondToClient(TransmissionData transmissionData)
        {
            // Do not modify this method.
            if (transmissionData == null)
            {
                throw new ArgumentNullException(nameof(transmissionData));
            }
            try
            {
                Array.Clear(sendBuffer, index: 0, length: sendBuffer.Length);
                sendBuffer = Serializer <TransmissionData> .Serialize(transmissionData);

                connectedClient.GetStream().Write(sendBuffer, offset: 0, size: sendBuffer.Length);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #20
0
        private void app_ListOfLinks(ModelPath modelPath)
        {
            var temp = new List <ModelPath>();

            var trans = new TransmissionData(TransmissionData.ReadTransmissionData(modelPath));

            foreach (var refId in trans.GetAllExternalFileReferenceIds())
            {
                var extRef = trans.GetLastSavedReferenceData(refId);

                if (extRef.ExternalFileReferenceType == ExternalFileReferenceType.RevitLink)
                {
                    var path = extRef.GetPath();
                    temp.Add(path);
                }
            }

            Globals.data.Add(temp);
        }
Example #21
0
        private static List <RevitLink> GetLinks(string location)
        {
            List <RevitLink> links = new List <RevitLink>();

            try
            {
                ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(location);

                TransmissionData        transData          = TransmissionData.ReadTransmissionData(path);
                ICollection <ElementId> externalReferences = default(ICollection <ElementId>);

                if (transData != null)
                {
                    // collect all (immediate) external references in the model

                    externalReferences = transData.GetAllExternalFileReferenceIds();

                    if (externalReferences.Count > 0)
                    {
                        foreach (ElementId refId in externalReferences)
                        {
                            ExternalFileReference extRef = transData.GetLastSavedReferenceData(refId);
                            if (extRef.IsValidObject)
                            {
                                if (extRef.ExternalFileReferenceType == ExternalFileReferenceType.CADLink | extRef.ExternalFileReferenceType == ExternalFileReferenceType.DWFMarkup | extRef.ExternalFileReferenceType == ExternalFileReferenceType.RevitLink)
                                {
                                    RevitLink rl = new RevitLink();
                                    rl.LinkType     = extRef.ExternalFileReferenceType.ToString();
                                    rl.AbsolutePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetAbsolutePath());
                                    rl.Path         = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetPath());
                                    links.Add(rl);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(links);
        }
Example #22
0
        public void Run()
        {
            Trace.WriteLine("DataHeaderUnitTest");

            int              inputType             = 0xFF;
            string           inputData             = "SoulToMind";
            TransmissionData inputTransmissionData = TransmissionData.Text;
            DataHeader       dataHeader            = new DataHeader(
                inputType,
                Encoding.UTF8.GetBytes(inputData),
                inputTransmissionData);

            byte[] createBuffer = dataHeader.CreateBuffer();

            byte[] headerBuffer1 = new byte[4];
            Array.Copy(createBuffer, 0, headerBuffer1, 0, headerBuffer1.Length);

            byte[] headerBuffer2 = new byte[4];
            Array.Copy(createBuffer, headerBuffer1.Length, headerBuffer2, 0, headerBuffer2.Length);

            int length = BitConverter.ToInt32(headerBuffer2, 0);

            byte[] dataBuffer = new byte[length];
            Array.Copy(createBuffer, headerBuffer1.Length + headerBuffer2.Length, dataBuffer, 0, dataBuffer.Length);

            int outputType = headerBuffer1[0];

            Trace.WriteLine("OutputType=" + outputType);
            Assert.AreEqual(inputType, outputType, 0);

            TransmissionData outputTransmissiondata = (TransmissionData)headerBuffer1[1];

            Trace.WriteLine("OutputTransmissionData=" + outputTransmissiondata);
            Assert.AreEqual(inputTransmissionData, outputTransmissiondata);

            string outputData = Encoding.UTF8.GetString(dataBuffer);

            Trace.WriteLine("OutputData=" + outputData);
            Assert.AreEqual(inputData, outputData, false);
        }
 public TransmissionData TransmitData()
 {
     try
     {
         TcpClient        tc = new TcpClient("127.0.0.1", 8080);
         NetworkStream    ns = tc.GetStream();
         TransmissionData transmissionData = new TransmissionData(true)
         {
             ID = this.ID
         };
         string jsonData = JsonConvert.SerializeObject(transmissionData);
         byte[] giden    = Encoding.Default.GetBytes(jsonData);
         ns.Write(giden, 0, giden.Length);
         ns.Close();
         tc.Close();
         return(transmissionData);
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void ListenClients()
        {
            try
            {
                _tls.Start();
                while (true)
                {
                    Socket soc = _tls.AcceptSocket();

                    NetworkStream ns       = new NetworkStream(soc);
                    List <byte>   received = new List <byte>();
                    int           data     = ns.ReadByte();
                    while (data != -1)
                    {
                        received.Add((byte)data);
                        data = ns.ReadByte();
                    }
                    ns.Close();

                    byte[]           buffer   = received.ToArray();
                    string           readData = Encoding.Default.GetString(buffer);
                    TransmissionData td       = JsonConvert.DeserializeObject <TransmissionData>(readData);
                    if (CToken.IsCancellationRequested)
                    {
                        td = null;
                        break;
                    }
                    if (td != null)
                    {
                        Task.Run(() => DataReceivedEvent(td));
                    }
                    soc.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #25
0
        /// <summary>
        /// Get paths of external references associated with the Revit document used to initialize the class.
        /// </summary>
        /// <returns>A dictionary of reference types, and reference paths.</returns>
        public Dictionary <ExternalFileReferenceType, string> GetExternalReferencePaths()
        {
            Dictionary <ExternalFileReferenceType, string> referenceDictionary = new Dictionary <ExternalFileReferenceType, string>();
            string location = Doc.PathName;

            try
            {
                ModelPath               modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(location);
                TransmissionData        transData = TransmissionData.ReadTransmissionData(modelPath);
                ICollection <ElementId> externalFileReferenceIds = transData.GetAllExternalFileReferenceIds();

                foreach (ElementId referenceElementId in externalFileReferenceIds)
                {
                    ExternalFileReference externalFileReference = transData.GetLastSavedReferenceData(referenceElementId);
                    ModelPath             refPath = externalFileReference.GetPath();
                    string path = ModelPathUtils.ConvertModelPathToUserVisiblePath(refPath);
                    ExternalFileReferenceType referenceType = externalFileReference.ExternalFileReferenceType;
                    referenceDictionary.Add(referenceType, path);
                }
            }
            catch (Exception exceptionReference) { Console.WriteLine(exceptionReference.ToString()); }

            return(referenceDictionary);
        }
Example #26
0
        /// <summary>
        /// List all DWG, RVT and other links of a given document.
        /// </summary>
        void ListLinks(ModelPath location)
        {
            string path = ModelPathUtils
                          .ConvertModelPathToUserVisiblePath(location);

            string content = string.Format(
                "The document at '{0}' ",
                path);

            List <string> links = null;

            // access transmission data in the given Revit file

            TransmissionData transData = TransmissionData
                                         .ReadTransmissionData(location);

            if (transData == null)
            {
                content += "does not have any transmission data";
            }
            else
            {
                // collect all (immediate) external references in the model

                ICollection <ElementId> externalReferences
                    = transData.GetAllExternalFileReferenceIds();

                int n = externalReferences.Count;

                content += string.Format(
                    "has {0} external reference{1}{2}",
                    n, PluralSuffix(n), DotOrColon(n));

                links = new List <string>(n);

                // find every reference that is a link

                foreach (ElementId refId in externalReferences)
                {
                    ExternalFileReference extRef
                        = transData.GetLastSavedReferenceData(refId);

                    links.Add(string.Format("{0} {1}",
                                            extRef.ExternalFileReferenceType,
                                            ModelPathUtils.ConvertModelPathToUserVisiblePath(
                                                extRef.GetPath())));
                }
            }
            Debug.Print(content);

            TaskDialog dlg = new TaskDialog("List Links");

            dlg.MainInstruction = content;

            if (null != links && 0 < links.Count)
            {
                string s = string.Join("  \r\n",
                                       links.ToArray());

                Debug.Print(s);

                dlg.MainContent = s;
            }
            dlg.Show();
        }
            public RhCommon_Scene(List <Rhino.DocObjects.RhinoObject> ObjRef, double Temp, double hr, double Pa, int Air_Choice, bool EdgeCorrection, bool IsAcoustic)
                : base(Temp, hr, Pa, Air_Choice, EdgeCorrection, IsAcoustic)
            {
                Vector3d  NormalHolder = new Vector3d();
                Plane     PlaneHolder  = new Plane();
                Transform XHolder      = new Transform();
                Random    RND          = new Random();

                ObjectList = new List <Rhino.DocObjects.ObjRef>();

                for (int q = 0; q < ObjRef.Count; q++)
                {
                    ObjectList.Add(new Rhino.DocObjects.ObjRef(ObjRef[q]));

                    Rhino.Geometry.Brep BObj;
                    if (ObjRef[q].ObjectType == Rhino.DocObjects.ObjectType.Brep)
                    {
                        BObj = ((Rhino.DocObjects.BrepObject)ObjRef[q]).BrepGeometry;
                    }
                    else
                    {
                        BObj = ((Rhino.DocObjects.ExtrusionObject)ObjRef[q]).ExtrusionGeometry.ToBrep();
                    }

                    for (int j = 0; j < BObj.Faces.Count; j++)
                    {
                        Brep B_Temp = BObj.DuplicateSubBrep(new List <int>()
                        {
                            j
                        });
                        BrepList.Add(B_Temp);
                        string   Mode          = null;
                        string   AcousticsData = null;
                        double[] Absorption    = new double[8];
                        //double[,] Scattering = new double[8, 3];
                        //double[] Reflection = new double[8];
                        double[] phase        = new double[8];
                        double[] Transparency = new double[8];
                        double[] Transmission = new double[8];
                        Mode = BObj.GetUserString("Acoustics_User");
                        double[] Scat = new double[8];
                        for (int oct = 0; oct < 8; oct++)
                        {
                            phase[oct] = 0;
                        }

                        if (Mode == "yes")
                        {
                            AcousticsData = BObj.GetUserString("Acoustics");
                            if (AcousticsData != "")
                            {
                                UI.PachydermAc_PlugIn.DecodeAcoustics(AcousticsData, ref Absorption, ref Scat, ref Transparency);
                            }
                            else
                            {
                                if (!Custom_Method)
                                {
                                    Status   = System.Windows.Forms.MessageBox.Show("A material is not specified correctly. Please assign absorption and scattering to all layers in the model.", "Materials Error", System.Windows.Forms.MessageBoxButtons.OK);
                                    Complete = false;
                                    return;
                                }
                            }
                        }
                        else
                        {
                            Rhino.DocObjects.Layer layer = Rhino.RhinoDoc.ActiveDoc.Layers[ObjRef[q].Attributes.LayerIndex];
                            string Method = layer.GetUserString("ABSType");
                            AcousticsData = layer.GetUserString("Acoustics");
                            if (Method == "Buildup")
                            {
                                List <AbsorptionModels.ABS_Layer> Layers = new List <AbsorptionModels.ABS_Layer>();
                                string[] Buildup = layer.GetUserString("Buildup").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (string l in Buildup)
                                {
                                    Layers.Add(AbsorptionModels.ABS_Layer.LayerFromCode(l));
                                }
                                AbsorptionData.Add(new Smart_Material(false, Layers, 44100, Env_Prop.Rho(0), Env_Prop.Sound_Speed(0), 2));
                            }
                            if (!string.IsNullOrEmpty(AcousticsData))
                            {
                                UI.PachydermAc_PlugIn.DecodeAcoustics(AcousticsData, ref Absorption, ref Scat, ref Transparency);
                                AbsorptionData.Add(new Basic_Material(Absorption, phase));
                            }
                            else
                            {
                                if (!Custom_Method)
                                {
                                    Status   = System.Windows.Forms.MessageBox.Show("A material is not specified correctly. Please assign absorption and scattering to all layers in the model.", "Materials Error", System.Windows.Forms.MessageBoxButtons.OK);
                                    Complete = false;
                                    return;
                                }
                            }
                        }

                        for (int oct = 0; oct < 8; oct++)
                        {
                            //Reflection[oct] = (1 - Absorption[oct]);
                            Transmission[oct] = Transparency[oct];
                            //Scattering[oct, 1] = Scat[oct];
                            //phase[oct] = 0;
                        }

                        //ReflectionData.Add(Reflection);
                        ScatteringData.Add(new Lambert_Scattering(Scat, SplitRatio));
                        TransmissionData.Add(Transmission);
                        //PhaseData.Add(phase);
                        bool Trans = false;
                        for (int t_oct = 0; t_oct < 8; t_oct++)
                        {
                            if (Transmission[t_oct] > 0)
                            {
                                Trans = true;
                                break;
                            }
                        }
                        Transmissive.Add(Trans);
                        PlaneBoolean.Add(BObj.Faces[j].IsPlanar());

                        if (PlaneBoolean[PlaneBoolean.Count - 1])
                        {
                            Vector3d Normal = new Vector3d();
                            Point3d  Origin = new Point3d();
                            //Transform MirrorSingle = new Transform();
                            //Plane PlaneSingle = new Plane();
                            Origin = BObj.Faces[j].PointAt(0, 0);
                            Normal = BObj.Faces[j].NormalAt(RND.NextDouble(), RND.NextDouble());
                            Mirror.Add(Transform.Mirror(Origin, Normal));
                            Plane.Add(new Plane(Origin, Normal));
                            PlanarNormal.Add(Normal);
                        }
                        else
                        {
                            PlanarNormal.Add(NormalHolder);
                            Plane.Add(PlaneHolder);
                            Mirror.Add(XHolder);
                        }
                    }
                }
                Valid = true;
            }
            public RhCommon_Scene(List <Rhino.Geometry.Brep> ObjRef, double Temp, double hr, double Pa, int Air_Choice, bool EdgeCorrection, bool IsAcoustic)
                : base(Temp, hr, Pa, Air_Choice, EdgeCorrection, IsAcoustic)
            {
                Vector3d  NormalHolder = new Vector3d();
                Plane     PlaneHolder  = new Plane();
                Transform XHolder      = new Transform();
                Random    RND          = new Random();

                for (int q = 0; q < ObjRef.Count; q++)
                {
                    //ObjectList.Add(new Rhino.DocObjects.ObjRef(ObjRef[q]));

                    //Rhino.Geometry.Brep BObj;
                    //if (ObjRef[q].ObjectType == Rhino.DocObjects.ObjectType.Brep)
                    //{
                    //    BObj = ((Rhino.DocObjects.BrepObject)ObjRef[q]).BrepGeometry;
                    //}
                    //else
                    //{
                    //    BObj = ((Rhino.DocObjects.ExtrusionObject)ObjRef[q]).ExtrusionGeometry.ToBrep();
                    //}

                    for (int j = 0; j < ObjRef[q].Faces.Count; j++)
                    {
                        Brep B_Temp = ObjRef[q].DuplicateSubBrep(new List <int>()
                        {
                            j
                        });
                        BrepList.Add(B_Temp);
                        string   Mode       = null;
                        double[] Absorption = new double[8] {
                            0, 0, 0, 0, 0, 0, 0, 0
                        };
                        double[,] Scattering = new double[8, 3] {
                            { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }
                        };
//                        double[] Reflection = new double[8]{0, 0, 0, 0, 0, 0, 0, 0};
                        double[] Transparency = new double[8] {
                            0, 0, 0, 0, 0, 0, 0, 0
                        };
                        double[] Transmission = new double[8] {
                            0, 0, 0, 0, 0, 0, 0, 0
                        };
                        Mode = ObjRef[q].GetUserString("Acoustics_User");
                        double[] Scat = new double[8] {
                            0, 0, 0, 0, 0, 0, 0, 0
                        };
                        double[] phase = new double[8] {
                            0, 0, 0, 0, 0, 0, 0, 0
                        };

                        //ReflectionData.Add(Reflection);
                        AbsorptionData.Add(new Basic_Material(Absorption, phase));
                        ScatteringData.Add(new Lambert_Scattering(Scat, SplitRatio));
                        TransmissionData.Add(Transmission);
                        //PhaseData.Add(phase);

                        Transmissive.Add(false);
                        PlaneBoolean.Add(ObjRef[q].Faces[j].IsPlanar());

                        if (PlaneBoolean[PlaneBoolean.Count - 1])
                        {
                            Vector3d Normal = new Vector3d();
                            Point3d  Origin = new Point3d();
                            //Transform MirrorSingle = new Transform();
                            //Plane PlaneSingle = new Plane();
                            Origin = ObjRef[q].Faces[j].PointAt(0, 0);
                            Normal = ObjRef[q].Faces[j].NormalAt(RND.NextDouble(), RND.NextDouble());
                            Mirror.Add(Transform.Mirror(Origin, Normal));
                            Plane.Add(new Plane(Origin, Normal));
                            PlanarNormal.Add(Normal);
                        }
                        else
                        {
                            PlanarNormal.Add(NormalHolder);
                            Plane.Add(PlaneHolder);
                            Mirror.Add(XHolder);
                        }
                    }
                }
                //SurfaceArray = SurfaceList.ToArray();
                Valid = true;
            }
Example #29
0
 public void SelecttransmisionByListPosition(int listPosition)
 {
     _selectedTransmision = _locomotiveData.Train.SortedTransmissionList[listPosition];
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            FilePath location = new FilePath("C:/file.rvt");

            TransmissionData transData
                = TransmissionData.ReadTransmissionData(
                      location);

            if (null != transData)
            {
                // Collect all (immediate) external
                // references in the model

                ICollection <ElementId> externalReferences
                    = transData.GetAllExternalFileReferenceIds();

                // Find every reference that is a link

                foreach (ElementId refId in externalReferences)
                {
                    ExternalFileReference extRef
                        = transData.GetLastSavedReferenceData(
                              refId);

                    if (extRef.ExternalFileReferenceType
                        == ExternalFileReferenceType.RevitLink)
                    {
                        // Change the path of the linked file,
                        // leaving everything else unchanged:

                        transData.SetDesiredReferenceData(refId,
                                                          new FilePath("C:/MyNewPath/cut.rvt"),
                                                          extRef.PathType, true);
                    }
                }

                // Make sure the IsTransmitted property is set

                transData.IsTransmitted = true;

                // Modified transmission data must be saved
                // back to the model

                TransmissionData.WriteTransmissionData(
                    location, transData);
            }
            else
            {
                TaskDialog.Show("Unload Links",
                                "The document does not have"
                                + " any transmission data");
            }
            return(Result.Succeeded);
        }