Esempio n. 1
0
        /// <summary>
        /// Parses the About contract after a client successfully connects and downloads the lobby contract.
        /// </summary>
        /// <returns>kObixClientSuccess if the operation succeeded, another value otherwise.</returns>
        private ObixResult ParseAboutContract()
        {
            ObixResult <XElement> data  = null;
            ObixAbout             about = null;

            if (WebClient == null || AboutUri == null)
            {
                return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientInputError,
                                       "WebClient is nothing, or the oBIX:About URI could not be found from the lobby contract."));
            }

            data = ReadUriXml(AboutUri);
            if (data.ResultSucceeded == false)
            {
                return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientXMLParseError,
                                       "ParseAboutContract received an error from ReadUriXml."));
            }

            about = ObixAbout.FromXElement(data.Result);
            if (about == null)
            {
                return(ErrorStack.Push(this.GetType(), ObixResult.kObixClientXMLParseError,
                                       "ParseAboutContract could not parse the obix:About contract."));
            }

            this.About = about;

            return(ObixResult.kObixClientSuccess);
        }
Esempio n. 2
0
        public void ResetStackData(string errorStackId)
        {
            if (String.IsNullOrEmpty(errorStackId))
            {
                return;
            }

            ErrorStack stack = _errorStackRepository.GetById(errorStackId);

            if (stack == null)
            {
                return;
            }

            try {
                stack.TotalOccurrences = 0;
                stack.LastOccurrence   = DateTime.MinValue.ToUniversalTime();
                stack.FirstOccurrence  = DateTime.MinValue.ToUniversalTime();
                _errorStackRepository.Update(stack);

                _statsHelper.DecrementDayProjectStatsByStackId(stack.ProjectId, errorStackId);
                _statsHelper.DecrementMonthProjectStatsByStackId(stack.ProjectId, errorStackId);

                _errorRepository.RemoveAllByErrorStackId(errorStackId);
                _dayStackStats.RemoveAllByErrorStackId(errorStackId);
                _monthStackStats.RemoveAllByErrorStackId(errorStackId);
            } catch (Exception e) {
                Log.Error().Project(stack.ProjectId).Exception(e).Message("Error resetting stack data.").Report().Write();
                throw;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Get content of Report
        /// </summary>
        /// <returns></returns>
        public static string GetContent()
        {
            // Get final content
            string output = Environment.NewLine + Environment.NewLine +
                            "PROCESS REPORT:        " + ErrorCount.ToString() + " ERRORS OCCURRED" + Environment.NewLine +
                            "--------------" + Environment.NewLine +
                            Environment.NewLine;

            if (ReportContent.Replace(" ", "") != "")
            {
                output += ReportContent;
            }
            else
            {
                output += "NO ERRORS.";
            }

            // Reset Report Service
            ReportContent = "";
            ErrorStack.Clear();
            ErrorCount = 0;

            // Return final content
            return(output);
        }
Esempio n. 4
0
        /// <summary>
        /// Writes the data provided by <paramref name="data"/> to the endpoint specified by
        /// <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The oBIX endpoint to send data to</param>
        /// <param name="data">A byte array of the data to send to the oBIX server</param>
        /// <returns>kObixClientResultSuccess on success with the response byte array from the server,
        /// another value otherwise.</returns>
        /// <remarks>
        /// This method should be regarded as raw data, see the derived implementations of ReadUriAsync
        /// for high-level oBIX reads.
        /// </remarks>
        public ObixResult <byte[]> WriteUri(Uri uri, byte[] data)
        {
            HttpResponseMessage response;

            byte[] responseContent = null;

            if (WebClient == null || connected == false)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientNotConnectedError, (byte[])null));
            }

            if (data == null || data.Length == 0)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError,
                                                 "WriteUri called with no data to write to the oBIX endpoint.", (byte[])null));
            }

            try {
                response = WebClient.PutAsync(uri, new ByteArrayContent(data)).Result;
            } catch (Exception ex) {
                return(ErrorStack.PushWithObject(GetType(), ex, (byte[])null));
            }

            if (response.IsSuccessStatusCode == false)
            {
                return(ErrorStack.PushWithObject <byte[]>(GetType(), ObixResult.kObixClientSocketError, response.ReasonPhrase));
            }

            responseContent = response.Content.ReadAsByteArrayAsync().Result;

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseContent));
        }
Esempio n. 5
0
        /// <summary>
        /// Asynchronously invokes an obix:op(eration) on the oBIX server at endpoint <paramref name="uri"/>, optionally
        /// with the data specified by <paramref name="data"/>.
        /// </summary>
        /// <param name="uri">The URI of the obix:op endpoint to invoke</param>
        /// <param name="data">(optional) The data to send as parameters to the obix:op</param>
        /// <returns>kObixClientResultSuccess on success with the response byte array on success,
        /// another value otherwise.</returns>
        public async Task <ObixResult <byte[]> > InvokeUriAsync(Uri uri, byte[] data)
        {
            HttpResponseMessage responseMessage = null;
            HttpRequestMessage  requestMessage  = null;

            byte[] response = null;

            if (WebClient == null || connected == false)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientNotConnectedError, (byte[])null));
            }

            try {
                requestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
                requestMessage.Headers.ExpectContinue = false;
                requestMessage.Content = new ByteArrayContent(data);
                requestMessage.Content.Headers.ContentLength = data.Length;

                responseMessage = await WebClient.SendAsync(requestMessage);
            } catch (Exception ex) {
                return(ErrorStack.PushWithObject(GetType(), ex, (byte[])null));
            }

            if (responseMessage.IsSuccessStatusCode == false)
            {
                return(ErrorStack.PushWithObject <byte[]>(GetType(), ObixResult.kObixClientSocketError, responseMessage.ReasonPhrase));
            }

            response = await responseMessage.Content.ReadAsByteArrayAsync();

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, response));
        }
Esempio n. 6
0
 public void Add(string text)
 {
     if (!String.IsNullOrEmpty(text))
     {
         ErrorStack.Push(text);
     }
 }
        /// <summary>
        /// This method is here to check to make sure that all the inputs on this current block
        /// are/have a valid connection.
        /// </summary>
        /// <returns></returns>
        public override bool OnStartEvaluateInternalData()
        {
            bool temp = true;
            int  i    = 0;

            this.ActiveStatus = EActiveStatus.Active;
            foreach (ConnectionNode cn in InputNodes)
            {
                if (!(cn.ConnectedNodes.Count > 0))
                {
                    if (InputNodes.Count - 1 == i && (!newvalconnected && NewValue_Constant != ""))
                    {
                        continue;
                    }
                    temp = false;
                    ErrorStack.Push(new InputNodeConnectionException(i, this.GetType().Name));
                }
                i++;
            }

            if (!temp)
            {
                this.ActiveStatus = EActiveStatus.Error;
                return(temp);
            }
            else
            {
                //no error found we can evaluate
                foreach (ConnectionNode cn in this.InputNodes)
                {
                    if (cn.ConnectedNodes.Count != 0)
                    {
                        temp &= EvaluateInternalData(cn.ConnectedNodes[0].ParentBlock);
                    }
                    else                     //this is here for the constants that one can manually enter.
                    {
                        if (this.NewValue_Constant == "T")
                        {
                            ResultsStack.Push(true);
                        }
                        else if (this.NewValue_Constant == "F")
                        {
                            ResultsStack.Push(false);
                        }
                        Console.WriteLine(String.Format("Result: {0}", ResultsStack.Peek()));
                    }
                }

                if (!temp)
                {
                    this.ActiveStatus = EActiveStatus.Error;
                    return(temp);
                }
                else
                {
                    temp &= OnEndEvaluateInternalData();
                }
            }
            return(temp);
        }
Esempio n. 8
0
        /// <summary>
        ///Invokes the obix:op(eration) at endpoint <paramref name="uri"/> with optional parameters specified by <paramref name="element"/>.
        /// <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">URI of the obix:op</param>
        /// <param name="element">An oBIX object to send as parameters to the URI.  If null, no parameters are sent.</param>
        /// <returns>kObixClientResultSuccess on success with the result of the obix:op as an XElement, another value otherwise.</returns>
        public async Task <ObixResult <XElement> > InvokeUriXmlAsync(Uri uri, XElement element)
        {
            XmlWriter           writer;
            XmlReader           reader;
            XElement            responseElement;
            XDocument           doc;
            MemoryStream        ms;
            ObixResult <byte[]> response;

            byte[] request = null;

            if (uri == null)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri is nothing.", (XElement)null));
            }

            if (element != null)
            {
                try {
                    using (ms = new MemoryStream()) {
                        using (writer = XmlWriter.Create(ms)) {
                            element.WriteTo(writer);
                        }

                        request = ms.ToArray();
                    }
                } catch (Exception) {
                    return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                     "InvokeUriXmlAsync could not understand the XML document provided.", (XElement)null));
                }
            }

            response = await InvokeUriAsync(uri, request);

            if (response.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(GetType(), response, (XElement)null));
            }

            ms = new MemoryStream(response.Result);
            ms.Seek(0, SeekOrigin.Begin);
            reader = XmlReader.Create(ms);

            try {
                doc = await Task.Factory.StartNew(() => doc = XDocument.Load(reader));
            } catch (Exception) {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                 "WriteUriXmlAsync could not understand the response document provided.", (XElement)null));
            }

            responseElement = doc.Root;
            if (responseElement.IsObixErrorContract() == true)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement));
        }
Esempio n. 9
0
        public static ErrorStack ToProjectLocalTime(this ErrorStack errorStack, IProjectRepository repository)
        {
            if (errorStack == null)
            {
                return(null);
            }

            return(errorStack.ToProjectLocalTime(repository.GetByIdCached(errorStack.ProjectId)));
        }
Esempio n. 10
0
        /// <summary>
        /// Asynchronously writes the oBIX object specified by <paramref name="element"/> to the endpoint specified by
        /// <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The oBIX endpoint to send data to</param>
        /// <param name="element">An oBIX object to send to the oBIX server</param>
        /// <returns>kObixClientResultSuccess on success with the response oBIX object from the server,
        /// another value otherwise.</returns>
        public async Task <ObixResult <XElement> > WriteUriXmlAsync(Uri uri, XElement element)
        {
            XmlWriter           writer;
            XmlReader           reader;
            XElement            responseElement;
            XDocument           doc;
            MemoryStream        ms;
            ObixResult <byte[]> response;

            byte[] data;

            if (uri == null || element == null)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError, "Uri, or data to write is nothing.", (XElement)null));
            }

            try {
                ms     = new MemoryStream();
                writer = XmlWriter.Create(ms);
                element.WriteTo(writer);
                data = ms.ToArray();

                writer.Dispose();
                writer = null;
                ms.Dispose();
                ms = null;
            } catch (Exception) {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                 "WriteUriXmlAsync could not understand the XML document provided.", (XElement)null));
            }

            response = await WriteUriAsync(uri, data);

            if (response.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(GetType(), response, (XElement)null));
            }

            ms     = new MemoryStream(response);
            reader = XmlReader.Create(ms);

            try {
                doc = await Task.Factory.StartNew(() => doc = XDocument.Load(reader));
            } catch (Exception) {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                 "WriteUriXmlAsync could not understand the response document provided.", (XElement)null));
            }

            responseElement = doc.Root;
            if (responseElement.IsObixErrorContract() == true)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement));
        }
        public bool ValidationInputData(string trainingName)
        {
            ErrorStack.Clear();

            if (StringUtils.IsEmpty(trainingName))
            {
                ErrorStack.Add(CreateErrorLabel(LanguageKeys.TrainingName, LanguageKeys.NotInputRequireData));
            }
            return(ErrorStack.Count == 0);
        }
Esempio n. 12
0
        public override async Task <ObixResult> ConnectAsync()
        {
            byte[]              data = null;
            XDocument           doc  = null;
            MemoryStream        ms   = null;
            ObixResult          result;
            HttpResponseMessage responseMessage = null;

            if (WebClient == null || connected == true)
            {
                return(ObixResult.kObixClientInputError);
            }

            try {
                responseMessage = await WebClient.GetAsync(this.LobbyUri);
            } catch (Exception ex) {
                return(ErrorStack.Push(this.GetType(), ex));
            }

            if (responseMessage.IsSuccessStatusCode == false)
            {
                return(ErrorStack.Push(GetType(), ObixResult.kObixClientSocketError, responseMessage.ReasonPhrase));
            }

            try {
                data = await responseMessage.Content.ReadAsByteArrayAsync();
            } catch (Exception ex) {
                return(ErrorStack.Push(GetType(), ex));
            }

            ms = new MemoryStream(data);
            try {
                doc = await Task.Factory.StartNew(() => XDocument.Load(ms));
            } catch (Exception ex) {
                ErrorStack.Push(this.GetType(), ex);
                return(ObixResult.kObixClientXMLParseError);
            }
            ms.Dispose();
            ms = null;

            result = ParseLobbyContract(doc);
            if (result != ObixResult.kObixClientSuccess)
            {
                return(ErrorStack.Push(this.GetType(), result));
            }

            result = ParseAboutContract();
            if (result != ObixResult.kObixClientSuccess)
            {
                return(ErrorStack.Push(this.GetType(), result));
            }

            connected = true;
            return(ObixResult.kObixClientSuccess);
        }
Esempio n. 13
0
        /// <summary>
        /// Invokes the obix:op(eration) at endpoint <paramref name="uri"/> with optional parameters specified by <paramref name="element"/>.
        /// </summary>
        /// <param name="uri">URI of the obix:op</param>
        /// <param name="element">An oBIX object to send as parameters to the URI.  If null, no parameters are sent.</param>
        /// <returns>kObixClientResultSuccess on success with the result of the obix:op as an XElement, another value otherwise.</returns>
        public ObixResult <XElement> InvokeUriXml(Uri uri, XElement element)
        {
            XmlWriter    writer          = null;
            XmlReader    reader          = null;
            XElement     responseElement = null;
            XDocument    doc             = null;
            MemoryStream ms = null;

            byte[] request = null;
            ObixResult <byte[]> response = null;

            if (uri == null)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError,
                                                 "Uri is nothing.", (XElement)null));
            }

            if (element != null)
            {
                using (ms = new MemoryStream()) {
                    using (writer = XmlWriter.Create(ms)) {
                        element.WriteTo(writer);
                    }
                    request = ms.ToArray();
                }
            }

            response = InvokeUri(uri, request);
            if (response.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(GetType(), response,
                                                 "WriteUri failed to invoke operation: " + uri.ToString() + ": " + ObixResult.Message(response), (XElement)null));
            }

            try {
                using (ms = new MemoryStream(response.Result)) {
                    using (reader = XmlReader.Create(ms)) {
                        doc = XDocument.Load(reader);
                    }
                }
            } catch (Exception ex) {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                 "Could not parse the XML response from the server: " + ex.ToString(), (XElement)null));
            }

            responseElement = doc.Root;
            if (responseElement.IsObixErrorContract() == true)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement));
        }
Esempio n. 14
0
        public PlanPagedResult <ErrorResult> GetByStack(string stackId, int page = 1, int pageSize = 10, DateTime?start = null, DateTime?end = null)
        {
            if (String.IsNullOrEmpty(stackId))
            {
                throw new ArgumentNullException("stackId"); // TODO: These should probably throw http Response exceptions.
            }
            ErrorStack errorStack = ErrorStackRepository.GetByIdCached(stackId);

            if (errorStack == null || !User.CanAccessOrganization(errorStack.OrganizationId))
            {
                throw new ArgumentException("Invalid error stack id.", "stackId"); // TODO: These should probably throw http Response exceptions.
            }
            start = start ?? DateTime.MinValue;
            end   = end ?? DateTime.MaxValue;

            if (end.Value <= start.Value)
            {
                throw new ArgumentException("End date must be greater than start date.", "end"); // TODO: These should probably throw http Response exceptions.
            }
            DateTime utcStart = _projectRepository.DefaultProjectLocalTimeToUtc(errorStack.ProjectId, start.Value);
            DateTime utcEnd   = _projectRepository.DefaultProjectLocalTimeToUtc(errorStack.ProjectId, end.Value);

            Project  project            = _projectRepository.GetByIdCached(errorStack.ProjectId);
            DateTime retentionUtcCutoff = _organizationRepository.GetByIdCached(project.OrganizationId).GetRetentionUtcCutoff();

            int skip = (page - 1) * pageSize;

            if (skip < 0)
            {
                skip = 0;
            }

            if (pageSize < 1)
            {
                pageSize = 10;
            }

            long         count;
            List <Error> query = _repository.GetByErrorStackIdOccurrenceDate(stackId, utcStart, utcEnd, skip, pageSize, out count).ToList();

            List <ErrorResult> models = query.Where(m => m.OccurrenceDate.UtcDateTime >= retentionUtcCutoff).Select(e => e.ToProjectLocalTime(_projectRepository)).Select(Mapper.Map <Error, ErrorResult>).ToList();

            long totalLimitedByPlan = (query.Count - models.Count) > 0 ? count - (skip + models.Count) : 0;
            var  result             = new PlanPagedResult <ErrorResult>(models, totalLimitedByPlan)
            {
                Page       = page > 1 ? page : 1,
                PageSize   = pageSize >= 1 ? pageSize : 10,
                TotalCount = count
            };

            // TODO: Only return the populated fields (currently all properties are being returned).
            return(result);
        }
Esempio n. 15
0
        public override ObixResult Connect()
        {
            byte[]              data = null;
            XDocument           doc  = null;
            MemoryStream        ms   = null;
            ObixResult          result;
            HttpResponseMessage responseMessage = null;

            if (WebClient == null || connected == true)
            {
                return(ObixResult.kObixClientInputError);
            }

            try {
                responseMessage = WebClient.GetAsync(base.LobbyUri).Result;
            } catch (Exception ex) {
                return(ErrorStack.Push(this.GetType(), ex));
            }

            if (responseMessage.IsSuccessStatusCode == false)
            {
                return(ErrorStack.Push(GetType(), ObixResult.kObixClientSocketError, responseMessage.ReasonPhrase));
            }

            try {
                data = responseMessage.Content.ReadAsByteArrayAsync().Result;
            } catch (Exception ex) {
                return(ErrorStack.Push(GetType(), ex));
            }

            using (ms = new MemoryStream(data)) {
                try {
                    doc = XDocument.Load(ms);
                } catch (Exception ex) {
                    return(ErrorStack.Push(this.GetType(), ex));
                }
            }

            result = ParseLobbyContract(doc);
            if (result != ObixResult.kObixClientSuccess)
            {
                return(ErrorStack.Push(this.GetType(), result));
            }

            result = ParseAboutContract();
            if (result != ObixResult.kObixClientSuccess)
            {
                return(ErrorStack.Push(this.GetType(), result));
            }

            connected = true;
            return(ObixResult.kObixClientSuccess);
        }
        /*----------------------------------------------------------------------------------------------------------------------------------------*/
        //
        // ViewModel Logic
        //
        /*----------------------------------------------------------------------------------------------------------------------------------------*/
        #region ViewModel Logic

        private bool Validate()
        {
            ErrorStack.Clear();

            if (Off)
            {
                return(true);
            }

            var trainingStack = TrainingStack.Children;

            foreach (var training in trainingStack)
            {
                var trainingseCount = ((Entry)((StackLayout)training).Children[3]).Text;
                if (StringUtils.IsEmpty(trainingseCount))
                {
                    ErrorStack.Add(CreateErrorLabel(LanguageKeys.SetCount, LanguageKeys.NotInputRequireData));
                }
                else
                {
                    if (!int.TryParse(trainingseCount, out var _))
                    {
                        ErrorStack.Add(CreateErrorLabel(LanguageKeys.SetCount, LanguageKeys.NotAvailableDataInput));
                    }
                }

                var loadStack = ((StackLayout)((StackLayout)training).Children[4]).Children;
                foreach (var load in loadStack)
                {
                    var subLoad = ((StackLayout)load).Children[1];
                    var nums    = ((Entry)((StackLayout)subLoad).Children[0]).Text;
                    if (StringUtils.IsEmpty(nums))
                    {
                        ErrorStack.Add(CreateErrorLabel(LanguageKeys.LoadNum, LanguageKeys.NotInputRequireData));
                    }
                    else
                    {
                        if (!float.TryParse(nums, out var _))
                        {
                            ErrorStack.Add(CreateErrorLabel(LanguageKeys.LoadNum, LanguageKeys.NotAvailableDataInput));
                        }
                    }
                }

                if (ErrorStack.Count != 0)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 17
0
        public static WebHookErrorStack FromErrorStack(ErrorStack stack, IProjectRepository projectRepository, IOrganizationRepository organizationRepository)
        {
            if (stack == null)
            {
                throw new ArgumentNullException("stack");
            }

            if (projectRepository == null)
            {
                throw new ArgumentNullException("projectRepository");
            }

            if (organizationRepository == null)
            {
                throw new ArgumentNullException("organizationRepository");
            }

            var project = projectRepository.GetByIdCached(stack.ProjectId);

            if (project == null)
            {
                throw new ArgumentException("ProjectId not found.");
            }

            var organization = organizationRepository.GetByIdCached(stack.OrganizationId);

            if (organization == null)
            {
                throw new ArgumentException("OrganizationId not found.");
            }

            return(new WebHookErrorStack {
                Id = stack.Id,
                Title = stack.Title,
                Description = stack.Description,
                Tags = stack.Tags,
                RequestPath = stack.SignatureInfo.ContainsKey("Path") ? stack.SignatureInfo["Path"] : null,
                Type = stack.SignatureInfo.ContainsKey("ExceptionType") ? stack.SignatureInfo["ExceptionType"] : null,
                TargetMethod = stack.SignatureInfo.ContainsKey("Method") ? stack.SignatureInfo["Method"] : null,
                ProjectId = stack.ProjectId,
                ProjectName = project.Name,
                OrganizationId = stack.OrganizationId,
                OrganizationName = organization.Name,
                TotalOccurrences = stack.TotalOccurrences,
                FirstOccurrence = stack.FirstOccurrence,
                LastOccurrence = stack.LastOccurrence,
                DateFixed = stack.DateFixed,
                IsRegression = stack.IsRegressed,
                IsCritical = stack.OccurrencesAreCritical || stack.Tags != null && stack.Tags.Contains("Critical"),
                FixedInVersion = stack.FixedInVersion
            });
        }
Esempio n. 18
0
        public StackStatsResult GetByStack(string stackId, DateTime?start = null, DateTime?end = null)
        {
            ErrorStack errorStack = _errorStackRepository.GetById(stackId);

            if (errorStack == null || !User.CanAccessOrganization(errorStack.OrganizationId))
            {
                throw new ArgumentException("Invalid error stack id.", "stackId"); // TODO: These should probably throw http Response exceptions.
            }
            Project  project            = _projectRepository.GetByIdCached(errorStack.ProjectId);
            DateTime retentionUtcCutoff = _organizationRepository.GetByIdCached(project.OrganizationId).GetRetentionUtcCutoff();

            return(_statsHelper.GetErrorStackStats(stackId, _projectRepository.GetDefaultTimeOffset(errorStack.ProjectId), start, end, retentionUtcCutoff));
        }
Esempio n. 19
0
        /// <summary>
        /// Writes the oBIX object specified by <paramref name="element"/> to the endpoint specified by
        /// <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The oBIX endpoint to send data to</param>
        /// <param name="element">An oBIX object to send to the oBIX server</param>
        /// <returns>kObixClientResultSuccess on success with the response oBIX object from the server,
        /// another value otherwise.</returns>
        public ObixResult <XElement> WriteUriXml(Uri uri, XElement element)
        {
            XmlWriter           writer;
            XmlReader           reader;
            XElement            responseElement;
            XDocument           doc;
            MemoryStream        ms;
            ObixResult <byte[]> response;

            if (uri == null || element == null)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientInputError,
                                                 "Uri, or data to write is nothing.", (XElement)null));
            }

            using (ms = new MemoryStream()) {
                using (writer = XmlWriter.Create(ms)) {
                    element.WriteTo(writer);
                }
                response = WriteUri(uri, ms.ToArray());
            }

            if (response.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(GetType(), response,
                                                 "WriteUri failed to write data to the obix server: " + response.ToString(), (XElement)null));
            }

            try {
                using (ms = new MemoryStream(response.Result)) {
                    using (reader = XmlReader.Create(ms)) {
                        doc = XDocument.Load(reader);
                    }
                }
            } catch (Exception) {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixClientXMLParseError,
                                                 "Could not parse the XML response from the server.", (XElement)null));
            }

            responseElement = doc.Root;
            if (responseElement.IsObixErrorContract() == true)
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, responseElement.ObixDisplay(), responseElement));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, responseElement));
        }
Esempio n. 20
0
        public static ErrorStack ToProjectLocalTime(this ErrorStack errorStack, Project project)
        {
            if (errorStack == null)
            {
                return(null);
            }

            if (errorStack.DateFixed.HasValue)
            {
                errorStack.DateFixed = TimeZoneInfo.ConvertTime(errorStack.DateFixed.Value, project.DefaultTimeZone());
            }

            errorStack.FirstOccurrence = TimeZoneInfo.ConvertTime(errorStack.FirstOccurrence, project.DefaultTimeZone());
            errorStack.LastOccurrence  = TimeZoneInfo.ConvertTime(errorStack.LastOccurrence, project.DefaultTimeZone());

            return(errorStack);
        }
Esempio n. 21
0
        /// <summary>
        /// Asynchronously gets raw data from the oBIX server specified by <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The URI of the oBIX data point to read</param>
        /// <returns>kObixClientResultSuccess with the data array on success, another value otherwise.</returns>
        /// <remarks>
        /// This method should be regarded as raw data, see the derived implementations of ReadUriAsync
        /// for high-level oBIX reads.
        /// </remarks>
        public async Task <ObixResult <byte[]> > ReadUriAsync(Uri uri)
        {
            byte[] data = null;

            if (WebClient == null)
            {
                return(ErrorStack.PushWithObject <byte[]>(this.GetType(), ObixResult.kObixClientNotConnectedError, (byte[])null));
            }

            try {
                data = await WebClient.GetByteArrayAsync(uri.ToString());
            } catch (Exception ex) {
                return(ErrorStack.PushWithObject <byte[]>(this.GetType(), ex, null));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, data));
        }
Esempio n. 22
0
        public ActionResult Index(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return(RedirectToAction("Index", "Project"));
            }

            ErrorStack errorStack = _repository.GetById(id);

            if (errorStack == null || !User.CanAccessOrganization(errorStack.OrganizationId))
            {
                return(HttpNotFound("An error stack with this id was not found."));
            }

            RouteData.SetOrganizationId(errorStack.OrganizationId);
            return(View(errorStack));
        }
Esempio n. 23
0
        private PlanPagedResult <ErrorStackResult> Frequent(List <ErrorStackResult> result, long totalLimitedByPlan, int page = 1, int pageSize = 10)
        {
            int skip = (page - 1) * pageSize;

            if (skip < 0)
            {
                skip = 0;
            }

            if (pageSize < 1)
            {
                pageSize = 10;
            }

            var ers = new PlanPagedResult <ErrorStackResult>(result.Skip(skip).Take(pageSize).ToList(), totalLimitedByPlan);
            IQueryable <ErrorStack> errorStacks = _errorStackRepository.GetByIds(ers.Results.Select(s => s.Id));

            foreach (ErrorStackResult stats in ers.Results.ToList())
            {
                ErrorStack stack = errorStacks.SingleOrDefault(s => s.Id == stats.Id);
                if (stack == null)
                {
                    ers.Results.RemoveAll(r => r.Id == stats.Id);
                    continue;
                }

                // Stat's Id and Total properties are already calculated in the Results.
                stats.Type   = stack.SignatureInfo.ContainsKey("ExceptionType") ? stack.SignatureInfo["ExceptionType"] : null;
                stats.Method = stack.SignatureInfo.ContainsKey("Method") ? stack.SignatureInfo["Method"] : null;
                stats.Path   = stack.SignatureInfo.ContainsKey("Path") ? stack.SignatureInfo["Path"] : null;
                stats.Is404  = stack.SignatureInfo.ContainsKey("Path");

                stats.Title = stack.Title;
                stats.First = stack.FirstOccurrence;
                stats.Last  = stack.LastOccurrence;
            }

            ers.TotalLimitedByPlan = ers.Results.Count != pageSize ? totalLimitedByPlan : 0;
            ers.TotalCount         = result.Count + totalLimitedByPlan;
            ers.Page     = page > 1 ? page : 1;
            ers.PageSize = pageSize >= 1 ? pageSize : 10;

            return(ers);
        }
Esempio n. 24
0
        /// <summary>
        /// Processes content of current error stack in Report content and resets error stack after
        /// </summary>
        /// <returns></returns>
        public static void ProcessErrorStack()
        {
            // Add ErrorStack content into Report content
            if (ErrorStack.Count > 0)
            {
                Write(Title);

                foreach (string error in ErrorStack)
                {
                    Write("[ERROR]  " + error + Environment.NewLine);
                }
                ;

                ErrorCount += ErrorStack.Count;
            }

            // Reset ErrorStack
            ErrorStack.Clear();
        }
Esempio n. 25
0
        /// <summary>
        /// check to make sure all the nodes on this block have valid connection points.
        /// </summary>
        /// <param name="currentNB"></param>
        /// <returns></returns>
        public override bool OnStartNodeBlockExecution(ref BaseNodeBlock currentNB)
        {
            bool temp = true;
            int  i    = 0;

            this.ActiveStatus = EActiveStatus.Active;
            foreach (ConnectionNode cn in InputNodes)
            {
                if (!(cn.ConnectedNodes.Count > 0))
                {
                    if (InputNodes.Count - 1 == i && (!NewValConnected && NewValue_Constant != ""))
                    {
                        continue;
                    }
                    temp = false;
                    ErrorStack.Push(new InputNodeConnectionException(i, this.GetType().Name));
                }
                i++;
            }

            i = 0;
            foreach (ConnectionNode cn in OutputNodes)
            {
                if (!(cn.ConnectedNodes.Count > 0))
                {
                    temp = false;
                    ErrorStack.Push(new OutputNodeConnectionException(i, this.GetType().Name));
                }
                i++;
            }

            if (!(EntryNode.ConnectedNodes.Count > 0))
            {
                temp = false;
                ErrorStack.Push(new EntryNodeConnectionException(this.GetType().Name));
            }

            if (!temp)
            {
                this.ActiveStatus = EActiveStatus.Error;
            }
            return(temp);
        }
Esempio n. 26
0
        /// <summary>
        /// Asynchronously gets data from the oBIX server specified by <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The URI of the oBIX data point to read</param>
        /// <returns>kObixClientResultSuccess with an XElement representing the
        /// oBIX XML object on success, another value otherwise.</returns>
        public async Task <ObixResult <XElement> > ReadUriXmlAsync(Uri uri)
        {
            ObixResult <byte[]> data = null;
            XDocument           doc  = null;
            MemoryStream        ms   = null;

            if (WebClient == null)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientNotConnectedError, (XElement)null));
            }

            data = await ReadUriAsync(uri);

            if (data.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError,
                                                 "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null));
            }

            ms = new MemoryStream(data.Result);
            try {
                doc = await Task.Factory.StartNew <XDocument>(() => XDocument.Load(ms));
            } catch (Exception ex) {
                return(ErrorStack.PushWithObject(this.GetType(), ex, (XElement)null));
            }

            ms.Dispose();
            ms = null;

            if (doc == null || doc.Root == null)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError,
                                                 "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null));
            }

            if (doc.Root.IsObixErrorContract())
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, doc.Root));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, doc.Root));
        }
Esempio n. 27
0
        /// <summary>
        /// make sure there are connections
        /// </summary>
        /// <returns></returns>
        public override bool OnStartEvaluateInternalData()
        {
            bool temp = true;
            int  i    = 0;

            this.ActiveStatus = EActiveStatus.Active;
            foreach (ConnectionNode cn in InputNodes)
            {
                if (!(cn.ConnectedNodes.Count > 0))
                {
                    temp = false;
                    ErrorStack.Push(new InputNodeConnectionException(i, this.GetType().Name));
                }
                i++;
            }

            if (!temp)
            {
                this.ActiveStatus = EActiveStatus.Error;
                return(temp);
            }
            else
            {
                //no error found we can evaluate
                foreach (ConnectionNode cn in this.InputNodes)
                {
                    temp &= EvaluateInternalData(cn.ConnectedNodes[0].ParentBlock);
                }

                if (!temp)
                {
                    this.ActiveStatus = EActiveStatus.Error;
                    return(temp);
                }
                else
                {
                    temp &= OnEndEvaluateInternalData();
                }
            }
            return(temp);
        }
Esempio n. 28
0
    public virtual void WriteToErrorLog(ArrayList list)
    {
        ErrorLoggingDataContext logger = new ErrorLoggingDataContext();
        ErrorStack tblError            = new ErrorStack();

        tblError.CreatedDate = DateTime.Now;
        if (!string.IsNullOrEmpty(list[2].ToString()))
        {
            tblError.RequestorIp = list[2].ToString();
        }
        if (!string.IsNullOrEmpty(list[3].ToString()))
        {
            tblError.StackTrace = list[3].ToString();
        }
        if (!string.IsNullOrEmpty(list[1].ToString()))
        {
            tblError.newId = Guid.Parse(list[1].ToString());
        }
        logger.ErrorStacks.InsertOnSubmit(tblError);
        logger.SubmitChanges();
    }
Esempio n. 29
0
        public ActionResult StopNotifications(string id)
        {
            // TODO: We should probably be setting error notifications when the stack is not found.
            if (String.IsNullOrEmpty(id))
            {
                return(RedirectToAction("Index", "Project"));
            }

            ErrorStack errorStack = _repository.GetById(id);

            if (errorStack == null || !User.CanAccessOrganization(errorStack.OrganizationId))
            {
                return(RedirectToAction("Index", "Project"));
            }

            errorStack.DisableNotifications = true;
            // TODO: Add a log entry.
            _repository.Update(errorStack);

            return(RedirectToAction("Index", "Stack", new { id = errorStack.Id, notification = "stop-notifications" }));
        }
Esempio n. 30
0
        /// <summary>
        /// Gets data from the oBIX server specified by <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The URI of the oBIX data point to read</param>
        /// <returns>kObixClientResultSuccess with an XElement representing the
        /// oBIX XML object on success, another value otherwise.</returns>
        public ObixResult <XElement> ReadUriXml(Uri uri)
        {
            ObixResult <byte[]> data = null;
            XDocument           doc  = null;
            MemoryStream        ms   = null;

            if (WebClient == null)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientNotConnectedError, (XElement)null));
            }

            data = ReadUri(uri);
            if (data.ResultSucceeded == false)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError,
                                                 "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null));
            }

            using (ms = new MemoryStream(data.Result)) {
                ms.Position = 0;
                try {
                    doc = XDocument.Load(ms);
                } catch (Exception ex) {
                    return(ErrorStack.PushWithObject(this.GetType(), ex, (XElement)null));
                }
            }

            if (doc == null || doc.Root == null)
            {
                return(ErrorStack.PushWithObject(this.GetType(), ObixResult.kObixClientXMLParseError,
                                                 "ReadUriXml could not understand the downloaded document at URI " + uri.ToString(), (XElement)null));
            }

            if (doc.Root.IsObixErrorContract())
            {
                return(ErrorStack.PushWithObject(GetType(), ObixResult.kObixServerError, doc.Root));
            }

            return(ObixResult.FromResult(ObixResult.kObixClientSuccess, doc.Root));
        }