Example #1
0
 public bool WriteBytes(byte[] data)
 {
     try
     {
         if ((tcpClient == null) || !IsOpen())
         {
             return(false);
         }
         return(WriteNoCatch(data));
     }
     catch (ArgumentOutOfRangeException ex)
     {
         ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Write Invalid data to write. - exception: {0}", ex.Message));
         throw;
         //return false;
     }
     catch (ObjectDisposedException ex)
     {
         ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Write Stream was disposed. - exception: {0}", ex.Message));
         throw;
         //return false;
     }
     catch (System.IO.IOException ex)
     {
         ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Write IO Error. - exception: {0}. \r\nError while writing {2} to {1}", ex.Message, IpAddr, data));
         throw;
         //return false;
     }
     catch (ArgumentNullException ex)
     {
         ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Write IO Error. - ArgumentNullException: {0}", ex.Message));
         throw;
     }
 }
Example #2
0
        public static bool IsDateValue(string valueIn, string format, ref DateTime dtValue)
        {
            try
            {
                if (string.IsNullOrEmpty(valueIn))
                {
                    return(false);
                }
                if (string.IsNullOrEmpty(format))
                {
                    return(false);
                }

                DateTime result      = new DateTime();
                bool     validFormat = DateTime.TryParseExact(valueIn, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
                if (validFormat)
                {
                    dtValue = result;
                }

                return(validFormat);
            }

            catch (System.FormatException ex)
            {
                Debug.Assert(false, "exception " + ex.Message);
                ExceptionRecorder.RecordException(" Error while converting date value (expecting " + format + "): " + valueIn, ex);
                return(false);
            }
        }
Example #3
0
        // return decimal part
        public static bool GetDecimalPart(string valueIn, ref Decimal decimalPart)
        {
            try
            {
                if (valueIn == null)
                {
                    return(false);
                }

                int i = valueIn.IndexOf(".", StringComparison.Ordinal);
                if (i < 1)
                {
                    decimalPart = 0M;
                    return(true);
                }

                Decimal dValue = Decimal.Parse(valueIn, NumberStyles.Float, CultureInfo.InvariantCulture);
                decimalPart = Math.Abs(dValue - (int)dValue);

                return(true);
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message + " error getting decimal part of " + valueIn);
                ExceptionRecorder.RecordException(ex.Message + " Assert while converting: " + valueIn);
                return(false);
            }
        }
Example #4
0
        public bool GetMeasByName(string name, ref Meas meas)
        {
            try
            {
                Debug.Assert(!string.IsNullOrEmpty(name), "GetMeasByName, invalid argument");
                if (string.IsNullOrEmpty(name))
                {
                    return(false);
                }

                var m1 = measList.Find(item => item.Name == name);
                if (m1.Name != null && m1.Name == name)
                {
                    meas = m1;
                    return(true);
                }

                //foreach (var m1 in measList)
                //    if (m1.Name == name)
                //    {
                //        meas = m1;
                //        return true;
                //    }

                return(false);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("GetMeasByName " + ex.Message);
                return(false);
            }
        }
Example #5
0
        public static bool IsValidIpAddress(string address)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(address))
                {
                    return(false);
                }

                address = address.Trim();
                if (!CheckAddress(address))
                {
                    return(false);
                }

                IPAddress test;
                bool      ok = IPAddress.TryParse(address, out test);
                return(ok);
            }
            catch (FormatException ex)
            {
                ExceptionRecorder.RecordException("FormatException: " + ex.Message);
                return(false);
            }
        }
Example #6
0
        /// <summary>
        /// Read bytes from current NetworkStream.
        /// Return null if stream is not available.
        /// </summary>
        /// <returns></returns>
        public byte[] ReadBytes()
        {
            try
            {
                if (tcpClient == null)
                {
                    return(null);
                }
                if (!tcpClient.Connected)
                {
                    return(null);
                }
                stream = GetStream();
                if (stream == null)
                {
                    return(null);
                }

                var data = new Byte[ReadBufferSize];
                stream.ReadTimeout = 5000;
                var bytes = stream.Read(data, 0, data.Length);

                return(data);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "read - exception: {0}", ex));
                throw;
            }
        }
Example #7
0
        object CreateService(IServiceContainer container, Type serviceType)
        {
            _taskContext.ThrowIfNotOnMainThread();

            if (typeof(YetiVSIService) == serviceType)
            {
                var options = GetDialogPage(typeof(OptionPageGrid)) as OptionPageGrid;
                var yeti = new YetiVSIService(options);
                yeti.DebuggerOptions.ValueChanged += OnDebuggerOptionChanged;
                return yeti;
            }

            if (typeof(SLLDBShell) == serviceType)
            {
                var writer = new CommandWindowWriter(_taskContext,
                                                     (IVsCommandWindow) GetService(
                                                         typeof(SVsCommandWindow)));
                return new LLDBShell.LLDBShell(_taskContext, writer);
            }

            if (typeof(SMetrics) == serviceType)
            {
                return new MetricsService(_taskContext,
                                          Versions.Populate(
                                              (GetService(typeof(EnvDTE.DTE)) as EnvDTE._DTE)
                                              ?.RegistryRoot));
            }

            if (typeof(SDebugEngineManager) == serviceType)
            {
                return new DebugEngineManager();
            }

            if (typeof(SSessionNotifier) == serviceType)
            {
                ISessionNotifier sessionNotifier = new SessionNotifierService();
                var vsiService = (YetiVSIService) GetGlobalService(typeof(YetiVSIService));
                var exceptionRecorder =
                    new ExceptionRecorder((IMetrics) GetService(typeof(SMetrics)));
                var loadSymbolsCommand = new LoadSymbolsCommand(
                    _taskContext, this, exceptionRecorder, vsiService);
                sessionNotifier.SessionLaunched += loadSymbolsCommand.OnSessionLaunched;
                sessionNotifier.SessionStopped += loadSymbolsCommand.OnSessionStopped;

                var noSourceWindowHider = new NoSourceWindowHider(_taskContext, this,
                                                                  exceptionRecorder, vsiService);
                sessionNotifier.SessionLaunched += noSourceWindowHider.OnSessionLaunched;
                sessionNotifier.SessionStopped += noSourceWindowHider.OnSessionStopped;

                return sessionNotifier;
            }

            return null;
        }
Example #8
0
 public bool HasDataAvailable()
 {
     try
     {
         bool?result = GetStream()?.DataAvailable;
         return(result == true);
     }
     catch (Exception ex)
     {
         ExceptionRecorder.RecordException("Exception in TcpIpClient HasDataAvailable :" + ex.Message);
         return(false);
     }
 }
Example #9
0
 public bool Parse(string[] args)
 {
     try
     {
         DoParse(args);
         return(true);
     }
     catch (Exception ex)
     {
         ExceptionRecorder.RecordException("Exception in command line parser " + ex.Message);
         return(false);
     }
 }
Example #10
0
 // return true if valueIn is valid double value (. as decimal separator)
 public static bool IsNumericDataValue(string valueIn)
 {
     try
     {
         double dValue = 0;
         return(StringUtil.TryParseDouble(valueIn, out dValue));
     }
     catch (System.ArgumentNullException ex)
     {
         Debug.Assert(false, "Validation.TryParseDouble should never throw. " + valueIn);
         ExceptionRecorder.RecordException("Assert while converting: " + valueIn, ex);
         return(false);
     }
 }
Example #11
0
 internal void RaiseTextWithEndCharReceived(string messageText)
 {
     try
     {
         if (iNamedPort != null)
         {
             NamedPortEventRaiser.RaiseTextWithEndCharReceived(iNamedPort, messageText);
         }
     }
     catch (NullReferenceException)
     {
         Debug.Assert(true);
     }
     catch (Exception ex)
     {
         ExceptionRecorder.RecordException("Exception in RaiseTextWithEndCharReceived " + ":" + ex.Message);
     }
 }
Example #12
0
 public bool IsOpen()
 {
     try
     {
         //       Debug.WriteLine("IsOpen tcpClient != null" + tcpClient != null);
         if (tcpClient != null && tcpClient.Client != null)
         {
             //           Debug.WriteLine("IsOpen tcpClient.Connected:" + tcpClient.Connected);
             return(tcpClient.Connected);
         }
         return(false);
     }
     catch (NullReferenceException ex)
     {
         ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "client null reference in IsOpen. - exception: {0}", ex.Message));
         //  throw;
         return(false);
     }
 }
Example #13
0
 internal void RaiseTextReceived(string messageText)
 {
     try
     {
         if (iNamedPort != null)
         {
             NamedPortEventRaiser.RaiseTextReceived(iNamedPort, messageText);
         }
     }
     catch (NullReferenceException)
     {
         Debug.Assert(true);
     }
     catch (Exception ex)
     {
         string message = "Exception in RaiseTextReceived " + (messageText ?? "messageText is null");
         ExceptionRecorder.RecordException(message, ex);
     }
 }
Example #14
0
        public void StartListening()
        {
            IsListening = true;

            while (IsListening)
            {
                lineTimeoutManager.StartTimer();
                try
                {
                    Listen();
                }
                catch (Exception ex)
                {
                    ExceptionRecorder.RecordException("Exception in TcpServer ListenNoThrow :" + ex.Message);
                    Thread.Sleep(50);
                    IsListening = false;
                }
                lineTimeoutManager.StopTimer();
            }
        }
Example #15
0
 private void CloseAllClients()
 {
     try
     {
         //    SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, "Closing socket server CloseAllClients " + IpAndPort + " clients:" + clients.Count);
         lock (clientsToBeRemovedLock)
         {
             foreach (VaiTcpIpClient tcpClient in clients)
             {
                 MarkClientToBeRemoved(tcpClient);
             }
         }
         Thread.Sleep(cRemoveClientsLoopMs);
         //   RemoveClients();
     }
     catch (Exception ex)
     {
         ExceptionRecorder.RecordException("Exception in CloseAllClients " + ex.Message);
     }
 }
Example #16
0
        internal void Enqueue(T msg)
        {
            if (msg == null)
            {
                return;
            }

            try
            {
                if (OutQueueLocked)
                {
                    WaitForQueueToOpen();
                }

                if (OutQueueLocked)
                {
                    ExceptionRecorder.RecordException("Output queue lock could not be opened 2. Count = " + OutQueue.Count + ". Failing to send command: " + msg);
                    return;
                }

                OutQueueLocked = true;
                lock (OutQueueLock)
                {
                    OutQueue.Enqueue(msg);
                    if (outQueue.Count > capacity)
                    {
                        InformCapacityLimitReached();
                        outQueue.Dequeue();
                    }
                }
            }
            catch (Exception ex)
            {
                var s = string.Format(CultureInfo.InvariantCulture, "{0}{1}", "Exception while sending message: ", ex.Message);
                ExceptionRecorder.RecordException(s);
            }
            finally
            {
                OutQueueLocked = false;
            }
        }
Example #17
0
 private NetworkStream GetStream()
 {
     try
     {
         if ((tcpClient != null) && (tcpClient.Connected))
         {
             return(tcpClient.GetStream());
         }
         return(null);
     }
     catch (ObjectDisposedException ex)
     {
         ExceptionRecorder.RecordException("Exception in GetStream " + ex.Message);
         return(null);
     }
     catch (InvalidOperationException ex)
     {
         ExceptionRecorder.RecordException("Exception in GetStream " + ex.Message);
         return(null);
     }
 }
Example #18
0
        /// <summary>
        /// Read data from current NetworkStream.
        /// Return null if stream is not available.
        /// </summary>
        /// <returns></returns>
        public string Read()
        {
            try
            {
                var data   = new Byte[PortDataParser.MaxReadBlock];
                var stream = GetStream();

                if (stream == null)
                {
                    return(null);
                }
                var bytes        = stream.Read(data, 0, data.Length);
                var responseData = encoding.GetString(data, 0, bytes);
                return(responseData);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, @"tcp/ip client read - exception: {0}", ex));
                return(string.Empty);
            }
        }
Example #19
0
        internal static bool Initialise(string sInput, out Meas meas)
        {
            meas = new Meas();
            try
            {
                if (null == sInput)
                {
                    return(false);
                }

                const string cMeas = "MEAS";
                if (sInput.IndexOf(cMeas) != 0)
                {
                    return(false);
                }

                return(InitialiseFields(sInput, out meas));
            }
            catch (System.ArgumentNullException)
            {
                ExceptionRecorder.RecordException("Null argument in meas initialisation, string =" + sInput);
                return(false);
            }
            catch (System.ArgumentException)
            {
                Debug.Assert(false, "Check date format in meas " + sInput);
                ExceptionRecorder.RecordException("Argument exception in meas initialisation, string =" + sInput);
                return(false);
            }
            catch (System.FormatException)
            {
                ExceptionRecorder.RecordException("Format exception in meas initialisation, string =" + sInput);
                return(false);
            }
            catch (System.OverflowException)
            {
                ExceptionRecorder.RecordException("Overflow exception in meas initialisation, string =" + sInput);
                return(false);
            }
        }
Example #20
0
        private static string GetNthIpAddress(int n)
        {
            const string defaultIp = "127.0.0.1";

            try
            {
                // SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "GetNthIpAddress n=" + n);

                var list         = GetHostAddresses(Dns.GetHostName());
                int numAddresses = list.Count;
                // SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "address:" + address);

                for (var newIndex = n; newIndex < numAddresses; newIndex++)
                {
                    if (list[newIndex].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return(list[newIndex].ToString());
                    }
                }

                return(defaultIp);

                /*
                 * int index = n - 1;
                 * if (index >= numAddresses )
                 *  return GetNthIpAddress(index);
                 *
                 * if (address[index].AddressFamily == AddressFamily.InterNetwork)
                 *  return address[index].ToString();
                 *
                 * return GetNthIpAddress(index);
                 * */
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Exception while getting  ip address. n=" + n + " . " + ex.Message);
                return(defaultIp);
            }
        }
Example #21
0
        public static string Code(MeasMsg measMsg, string replaceSemicolonInData = ",")
        {
            try
            {
                if (measMsg == null)
                {
                    return(string.Empty);
                }

                var sb = new StringBuilder();
                sb.Append("(S:");
                sb.Append(measMsg.Station);
                sb.Append(";D:");
                sb.Append(measMsg.Time.ToString("yyMMdd", CultureInfo.InvariantCulture));
                sb.Append(";T:");
                sb.Append(measMsg.Time.ToString("HHmmss", CultureInfo.InvariantCulture));
                foreach (var meas in measMsg.MeasValues)
                {
                    //		measMsg.MeasList.ForEach(delegate(Meas meas)
                    //		{
                    if ((meas.Name != null) && (meas.ObsValue != null))
                    {
                        sb.Append(";");
                        sb.Append(meas.Name);
                        sb.Append(":");
                        sb.Append(meas.ObsValue.Replace(";", replaceSemicolonInData));
                    }
                    //	});
                }
                //   sb.Append(";");
                sb.Append(")");
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Exception in Code(MeasMsg) " + ex.Message);
                return(string.Empty);
            }
        }
Example #22
0
        public static bool IsValidDirectoryName(string directoryName)
        {
            try
            {
                if (string.IsNullOrEmpty(directoryName))
                {
                    return(false);
                }

                if (directoryName.IndexOfAny(invPathChars) > -1)
                {
                    return(false);
                }


                new System.IO.DirectoryInfo(directoryName);
                return(true);
            }
            catch (ArgumentException ex)
            {
                ExceptionRecorder.RecordException("ArgumentException in IsValidDirectoryName ", ex);
                return(false);
            }
            catch (System.IO.PathTooLongException ex)
            {
                ExceptionRecorder.RecordException("PathTooLongException in IsValidDirectoryName ", ex);
                return(false);
            }
            catch (System.Security.SecurityException ex)
            {
                ExceptionRecorder.RecordException("SecurityException in IsValidDirectoryName ", ex);
                return(false);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Exception in IsValidDirectoryName ", ex);
                return(false);
            }
        }
Example #23
0
        public static bool IsValidFileName(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    return(false);
                }

                if (fileName.IndexOfAny(invFileNameChars) > -1)
                {
                    return(false);
                }

                new System.IO.FileInfo(fileName);

                return(true);
            }
            catch (System.Security.SecurityException ex)
            {
                ExceptionRecorder.RecordException("SecurityException in IsValidFileName " + fileName, ex);
                return(false);
            }
            catch (System.ArgumentException ex)
            {
                ExceptionRecorder.RecordException("ArgumentException in IsValidFileName " + fileName, ex);
                return(false);
            }
            catch (System.UnauthorizedAccessException ex)
            {
                ExceptionRecorder.RecordException("UnauthorizedAccessException in IsValidFileName " + fileName, ex);
                return(false);
            }
            catch (System.IO.PathTooLongException ex)
            {
                ExceptionRecorder.RecordException("PathTooLongException in IsValidFileName " + fileName, ex);
                return(false);
            }
        }
Example #24
0
 public static bool IsValidFullFileName(string fileNameWithPath)
 {
     try
     {
         if (string.IsNullOrEmpty(fileNameWithPath))
         {
             return(false);
         }
         char[] invChars = Path.GetInvalidPathChars();
         if (fileNameWithPath.IndexOfAny(invChars) > -1)
         {
             return(false);
         }
         string fileName = Path.GetFileName(fileNameWithPath);
         return(IsValidFileName(fileName));
     }
     catch (Exception ex)
     {
         ExceptionRecorder.RecordException("Exception in isValidFullFileName " + fileNameWithPath, ex);
         return(false);
     }
 }
Example #25
0
        // return true if date is in Format yyyy-MM-dd HH:mm:ss
        public static bool IsDateValue(string valueIn, ref DateTime dtValue)
        {
            try
            {
                if (valueIn == null)
                {
                    return(false);
                }
                if (valueIn.IndexOf(@"/") > -1) // this handles most common cases
                {
                    return(false);
                }
                if (valueIn.Length == 0) // this handles most common cases
                {
                    return(false);
                }

                String Format = "yyyy-MM-dd HH:mm:ss";
                //				CultureInfo en = new CultureInfo("en-US");
                //				DateTime parsedBack =DateTime.ParseExact(valueIn,Format,en.DateTimeFormat);
                CultureInfo MyCultureInfo = new CultureInfo("fi-FI");
                DateTime    result        = new DateTime();
                bool        validFormat   = DateTime.TryParseExact(valueIn, Format, MyCultureInfo, DateTimeStyles.None, out result);
                if (validFormat)
                {
                    dtValue = result;
                }
                MyCultureInfo = null;
                return(validFormat);
            }
            catch (System.FormatException ex)
            {
                ExceptionRecorder.RecordException(" Assert while converting date value (expecting YYYY-MM-DD HH:mm:ss): " + valueIn, ex);
                return(false);
            }
        }
Example #26
0
        internal bool Parse(string data, out MeasMsg measMsg)
        {
            //    Debug.WriteLine(DateTimeEx.NowToStringWithMs + "\tYourview Parser starts" + data.Substring(0, Math.Min(data.Length, 30)));


            measMsg = new MeasMsg();
            try
            {
                if (variableNames.Count == 0)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, "YourView parser has not been initialised. Variable names have not been set.");
                    return(false);
                }

                CheckControlParameters();

                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: null or empty input data.");
                    return(false);
                }

                string messageName = GetMessageName(data);

                if (string.IsNullOrEmpty(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: unable to solve message name.");
                    return(false);
                }

                if (!fieldSeparators.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: field separator has not been defined for message " + messageName);
                    return(false);
                }


                string   fieldSeparator = ConvertFieldSeparator(fieldSeparators[messageName]);
                string[] separator      = { fieldSeparator };


                if (!messageStarts.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: field start character(s) have not been defined for message " + messageName);
                    return(false);
                }

                string convertedStart = ConvertMsgStart(messageStarts[messageName]).Trim();

                string msgStart = convertedStart;
                if (messageStarts.Count > 1)
                {
                    msgStart = messageName + convertedStart;
                }

                string tmp = sSTX + " ";
                while (data.Contains(tmp))
                {
                    data = data.Replace(tmp, sSTX);
                }
                string tmp2 = " " + sSTX;
                while (data.Contains(tmp2))
                {
                    data = data.Replace(tmp2, sSTX);
                }


                int startOfDataValues = data.IndexOf(msgStart);
                if (startOfDataValues == -1)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". Looking for:" + msgStart + ".Data to be parsed is:" + data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". msgStart len" + msgStart.Length + ".Data len:" + data.Length);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of STX:" + data.IndexOf(STX).ToIcString() + " ");
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of first 0:" + data.IndexOf("0").ToIcString() + " ");
                    foreach (var c in msgStart)
                    {
                        SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of first " + c + ":" + data.IndexOf(c).ToIcString() + " ");
                    }
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". Looking for:" + msgStart.ReplaceSohStxEtx() + ".Data to be parsed is:" + data.ReplaceSohStxEtx());
                    return(false);
                }

                int    msgStartLen     = msgStart.Length;
                string dataValueString = data.Substring(startOfDataValues + msgStartLen);
                if (fieldSeparators[messageName] == YV_SPACE)
                {
                    while (dataValueString.Contains("  "))
                    {
                        dataValueString = dataValueString.Replace("  ", " ");
                    }
                }

                Debug.Assert(data.Contains(msgStart), "data.Contains(msgStart)");

                /*
                 * Debug.WriteLine("message  in data:" + data.Contains(msgStart));
                 * Debug.WriteLine("data:" + data.ReplaceLfCr() + "\t\t" + "datavalue:" + dataValueString);
                 * Debug.WriteLine("messageStarts[messageName]:" + messageStarts[messageName] +"\t" +"startOfDataValues:" + startOfDataValues);
                 */

                if (!doNotUseSeparatorAtBeginningOfMessage[messageName])
                {
                    if (dataValueString.StartsWith(fieldSeparator))
                    {
                        dataValueString = dataValueString.Substring(fieldSeparator.Length);
                    }
                }

                if (subParsers.ContainsKey(messageName))
                {
                    if (subParsers[messageName] == "CTK25KAM61")
                    {
                        int ceiloStart = data.IndexOf("CT");
                        if (ceiloStart == -1)
                        {
                            return(false);
                        }
                        return(this.ceiloParser.Parse(data.Substring(ceiloStart), out measMsg));
                    }
                }

                string[] lines = dataValueString.Split(separator, StringSplitOptions.None);

                /*
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:dataValueString :" + dataValueString.ReplaceSohStxEtx());
                 * for(int i = 0; i< lines.GetLength(0);i++)
                 *  SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:line " + i + ":" + lines[i].ReplaceSohStxEtx());
                 */
                if (UseStationName)
                {
                    measMsg.Station = StationName;
                }
                measMsg.Time = DateTimeEx.Now;


                // char[] charsToTrim = { '\n', 'r', SOH, STX, ETX };
                // string messageName = lines[0].Trim(charsToTrim);



                if (!variableNames.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: unknown message received. Message name =" + messageName);
                    return(false);
                }

                var varList   = variableNames[messageName];
                int lineLen   = lines.GetLength(0);
                int lineIndex = 0;
                var max       = varList.Count;
                for (var varCount = 0; varCount < max; varCount++)
                {
                    lineIndex = varCount;
                    if (lineIndex < lineLen)
                    {
                        string varname = varList[varCount];
                        if (string.IsNullOrEmpty(varname))
                        {
                            continue;
                        }

                        string lineValue = lines[lineIndex];
                        if (SpecialFields.Contains(varname) || varname.StartsWith("<DATE ") || varname.StartsWith("<TIME "))
                        {
                            measMsg = HandleSpecialField(varname, lineValue, measMsg);
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(lineValue))
                            {
                                continue;
                            }
                            measMsg.AddMeas(new Meas(varname, measMsg.Time, lineValue, MeasStatus.c*K, measMsg.Station));
                        }
                    }
                }

                /*
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message successfully parsed.Station name" + measMsg.Station);
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message date:" + measMsg.Time);
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message contents:" + measMsg.ToString());
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:UseStation:" + UseStationName);
                 */

                //                Debug.WriteLine(DateTimeEx.NowToStringWithMs + "\tYourview Parser ends" + data.Substring(0, Math.Min(data.Length, 30)));
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing yourview message." + " data:" + data, ex);
                return(false);
            }
        }
Example #27
0
        new internal bool Parse(string data, out MeasMsg measMsg)
        {
            var progress = 0;

            measMsg = new MeasMsg();
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: null or empty input data.");
                    return(false);
                }
                progress++;


                int indexOfSOH = data.IndexOf('\x01');
                if (indexOfSOH > -1)
                {
                    data = data.Substring(indexOfSOH);
                }

                char[] charsToTrim = { '\n', '\r' };
                data = data.TrimStart(charsToTrim);
                char[] separator = { '\n' };
                var    lines     = data.Split(separator);
                if (!CheckLines(lines))
                {
                    return(false);
                }


                if (lines.GetLength(0) < 3)
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: incomplete message. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }

                progress++;

                string pw1 = lines[0].Substring(0, 5).Trim(invalidChars).Replace("\r", "").Replace("\n", "").Replace('\x01', ' ').Replace('\x02', ' ').Replace(" ", string.Empty);
                if (!Validation.IsValidFileName(pw1) || !Validation.IsValidDirectoryName(pw1))
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: invalid station name. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }
                measMsg.Station = pw1;
                measMsg.Time    = DateTimeEx.Now;

                ResetVariables();
                progress++;

                const char STX      = '\x02';
                var        stxIndex = lines[0].IndexOf(STX);
                if (stxIndex < 0)
                {
                    return(false);
                }
                var tmp = lines[0].Substring(stxIndex + 1).Trim(charsToTrim);
                if (!ParseDataItems(tmp))
                {
                    return(false);
                }
                progress++;

                measMsg.AddMeas(new Meas(GetVariableName("PWD_VISALARM"), measMsg.Time, visibilityAlarm, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PWD_WARNING"), measMsg.Time, alarmsAndWarningsInformation, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("VISAVG1M"), measMsg.Time, visibility1MinAvg, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("VISAVG10M"), measMsg.Time, visibility10MinAvg, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("NWSCODE"), measMsg.Time, instantPresentWeatherNwsCode, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW"), measMsg.Time, instantPresentWeather, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW15M"), measMsg.Time, presentWeather15m, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW1H"), measMsg.Time, presentWeather1h, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PRFAVG1M"), measMsg.Time, precipitationIntensity, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PRSUM24H"), measMsg.Time, cumulativeWaterSum, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("SNOWSUM24H"), measMsg.Time, cumulativeSnowSum, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PWD_TA"), measMsg.Time, temperature, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("LMAVG1M"), measMsg.Time, backgroundLuminance, MeasStatus.c*K, measMsg.Station));


                progress++;

                if (lines.GetLength(0) > 1)
                {
                    progress++;
                    string line = (lines[1].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas(GetVariableName("METARPWCODE"), measMsg.Time, line, MeasStatus.c*K, measMsg.Station));
                }
                if (lines.GetLength(0) > 2)
                {
                    progress++;
                    string line = (lines[2].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas(GetVariableName("METARRWCODE"), measMsg.Time, line, MeasStatus.c*K, measMsg.Station));
                }
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing pwd message. Progress:" + progress + " data:" + data, ex);
                return(false);
            }
        }
Example #28
0
        /// <summary>
        /// Open a connection to the given socket
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="tcpPort"></param>
        /// <returns></returns>
        public async Task <bool> ConnectAsync(IPAddress ipAddress, int tcpPort)
        {
            try
            {
                InitializeConnection(ipAddress, tcpPort);
                await tcpClient.Client.ConnectAsync(IpAddr, Port);

                return(true);
            }
            catch (SocketException ex)
            {
                var msg = string.Format(CultureInfo.InvariantCulture, "Please check connection port parameters: {0} ", ex.Message);
                if (null != IpAddr)
                {
                    msg += " Ip: " + IpAddr;
                }
#if DEBUG
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, msg);
#endif
                Debug.Assert(true, msg);

                // keep this delay above 100 ms. If the connection is broken, the system will try again
                Thread.Sleep(250);
                ConnectionState = NamedPortState.Disconnected;

                //     Debug.WriteLine(DateTimeEx.NowToString + msg);
                return(false);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                //     port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort.
                Debug.Assert(false, " port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort." + ex.Message);
                ExceptionRecorder.RecordException(" port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort." + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                Debug.WriteLine(DateTimeEx.NowToString + " port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort.");
                return(false);
            }
            catch (ObjectDisposedException ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Connect. - ObjectDisposedException: {0}", ex.Message));
                Debug.Assert(false, " System.Net.Sockets.TcpClient is closed" + ex.Message);
                Debug.WriteLine(DateTimeEx.NowToString + " System.Net.Sockets.TcpClient is closed" + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (ArgumentNullException ex)
            {
                ExceptionRecorder.RecordException("hostname is null " + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (System.Security.SecurityException ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Connect. - SecurityException: {0}", ex.Message));
                Debug.WriteLine(DateTimeEx.NowToString + " Connect. - SecurityException:" + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
                return(false);
            }
        } // Connect
Example #29
0
        new internal bool Parse(string data, out MeasMsg measMsg)
        {
            var progress = 0;

            measMsg = new MeasMsg();
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: null or empty input data.");
                    return(false);
                }
                progress++;


                char[] charsToTrim = { '\n', '\r', '\x01' };
                data = data.TrimStart(charsToTrim);
                char[] separator = { '\n' };
                var    lines     = data.Split(separator);
                if (!CheckLines(lines))
                {
                    return(false);
                }

                var lineCount = lines.GetLength(0);
                if (lineCount < 2)
                {
                    string error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: incomplete message. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }

                progress++;
                lines[0] = lines[0].Replace("\x01", string.Empty);
                var stationName = lines[0].Trim().Substring(0, 3).Replace("\r", "").Replace("\n", "");
                if (!Validation.IsValidDirectoryName(stationName))
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: invalid station name. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }
                measMsg.Station = stationName;
                measMsg.Time    = DateTimeEx.Now;

                ResetVariables();
                progress++;


                string tmp = lines[1].Trim(charsToTrim);
                if (!ParseSecondLine(tmp))
                {
                    return(false);
                }
                progress++;

                measMsg.AddMeas(new Meas("CL_HDSTATUS", measMsg.Time, cloudHeightDetectionStatus, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CL_WARNING", measMsg.Time, alarmsAndWarningsInformation, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB1", measMsg.Time, lowestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB2", measMsg.Time, secondLowestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB3", measMsg.Time, highestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("VV", measMsg.Time, verticalVisibility, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CL_STATUSCODE", measMsg.Time, alarmsAndWarnings, MeasStatus.c*K, measMsg.Station));

                progress++;
                if (lineCount > 2)
                {
                    progress++;
                    ParseThirdLine(lines[2].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas("CL_SCSTATUS", measMsg.Time, skyConditionDetectionStatus, MeasStatus.c*K, measMsg.Station));
                    if (cloudHeightsBySkycondition.Count > 0)
                    {
                        measMsg.AddMeas(new Meas("CL1", measMsg.Time, cloudHeightsBySkycondition[0], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 1)
                    {
                        measMsg.AddMeas(new Meas("CL2", measMsg.Time, cloudHeightsBySkycondition[1], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 2)
                    {
                        measMsg.AddMeas(new Meas("CL3", measMsg.Time, cloudHeightsBySkycondition[2], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 3)
                    {
                        measMsg.AddMeas(new Meas("CL4", measMsg.Time, cloudHeightsBySkycondition[3], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 4)
                    {
                        measMsg.AddMeas(new Meas("CL5", measMsg.Time, cloudHeightsBySkycondition[4], MeasStatus.c*K, measMsg.Station));
                    }

                    if (cloudAmountBySkycondition.Count > 0)
                    {
                        measMsg.AddMeas(new Meas("SC1", measMsg.Time, cloudAmountBySkycondition[0], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 1)
                    {
                        measMsg.AddMeas(new Meas("SC2", measMsg.Time, cloudAmountBySkycondition[1], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 2)
                    {
                        measMsg.AddMeas(new Meas("SC3", measMsg.Time, cloudAmountBySkycondition[2], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 3)
                    {
                        measMsg.AddMeas(new Meas("SC4", measMsg.Time, cloudAmountBySkycondition[3], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 4)
                    {
                        measMsg.AddMeas(new Meas("SC5", measMsg.Time, cloudAmountBySkycondition[4], MeasStatus.c*K, measMsg.Station));
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing ceilo message. Progress:" + progress + " data:" + data, ex);
                return(false);
            }
        }
 public void SetUp()
 {
     fakeMetrics       = Substitute.For <IMetrics>();
     exceptionRecorder = new ExceptionRecorder(fakeMetrics, MaxExceptionsChainLength);
 }