Ejemplo n.º 1
0
        public override void StartListening()
        {
            _foregroundDispatcher.AssertForegroundThread();

            if (_fileChangeUnadviseTask?.IsCompleted == false)
            {
                // An unadvise operation is still processing, block the foreground thread until it completes.
                _fileChangeUnadviseTask.Join();
            }

            if (_fileChangeAdviseTask != null)
            {
                // Already listening
                return;
            }

            _fileChangeAdviseTask = _joinableTaskFactory.RunAsync(async() =>
            {
                try
                {
                    return(await _fileChangeService.AdviseFileChangeAsync(FilePath, FileChangeFlags, this));
                }
                catch (PathTooLongException)
                {
                    // Don't report PathTooLongExceptions but don't fault either.
                }
                catch (Exception exception)
                {
                    _errorReporter.ReportError(exception);
                }

                return(VSConstants.VSCOOKIE_NIL);
            });
        }
Ejemplo n.º 2
0
        private async Task Timer_TickAsync()
        {
            try
            {
                _timer?.Change(Timeout.Infinite, Timeout.Infinite);

                OnStartingBackgroundWork();

                KeyValuePair <string, BatchableWorkItem>[] work;
                lock (_work)
                {
                    work = _work.ToArray();
                    _work.Clear();
                }

                OnBackgroundCapturedWorkload();

                for (var i = 0; i < work.Length; i++)
                {
                    var workItem = work[i].Value;
                    try
                    {
                        await workItem.ProcessAsync(_disposalCts.Token).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when(_disposalCts.IsCancellationRequested)
                    {
                        // Expected shutdown case, lets not log an error.
                    }
                    catch (Exception ex)
                    {
                        // Work item failed to process, allow the other process events to continue.
                        _errorReporter.ReportError(ex);
                    }
                }

                OnCompletingBackgroundWork();

                lock (_work)
                {
                    // Resetting the timer allows another batch of work to start.
                    _timer?.Dispose();
                    _timer = null;

                    // If more work came in while we were running start the worker again if we're still alive
                    if (_work.Count > 0 && !_disposed)
                    {
                        StartWorker();
                    }
                }

                OnCompletedBackgroundWork();
            }
            catch (Exception ex)
            {
                // This is something totally unexpected
                Debug.Fail("Batching work queue failed unexpectedly");
                _errorReporter.ReportError(ex);
            }
        }
Ejemplo n.º 3
0
        public override void ReportError(Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            _errorReporter.ReportError(exception);
        }
Ejemplo n.º 4
0
        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                var       context = ErrorLogging.GetApplicationContext(User);
                Exception ex      = HttpContext.Current.Server.GetLastError();
                try
                {
                    if (ex is HttpException)
                    {
                        if (((HttpException)ex).GetHttpCode() == 404)
                        {
                            //Here I can handle a 404 Error with redirects, using Error404Handner.StaticHandler or a managed pool of handlers for different ClientID's.
                            bool blnRedirected = Error404Handler.StaticHandler.Handle404(HttpContext.Current);
                            return; //Don't continue to process like a normal error
                        }
                    }
                }
                catch (Exception ex404)
                {
                    ErrorReporter.ReportError(ex404, context);
                }

                //if (General.Environment.Current.AmILive()) //I can optionally put a condition here to only record the error in specific environments using the General.Environment library.
                ErrorReporter.ReportError(ex, context);
            }
            catch { }
        }
Ejemplo n.º 5
0
        public async Task TestError()
        {
            var response1 = await ErrorReporter.ReportError("error");

            Assert.IsNotNull(response1);
            Assert.IsTrue(response1.Success);
            Assert.IsFalse(String.IsNullOrWhiteSpace(response1.IncidentCode) || response1.IncidentCode == "0");


            try
            {
                long  intTest = 42424242242423342;
                short test    = Convert.ToInt16(intTest);
            }
            catch (Exception ex)
            {
                ApplicationContext context = new ApplicationContext();
                context.ClientID = "client4";
                context.Custom1  = "cus1";
                context.Custom2  = "cus2";
                context.Custom3  = "cus3";
                context.CustomID = 9876;
                context.UserID   = "user4";
                context.UserType = "utype4";

                var response2 = await ErrorReporter.ReportError(ex, "My Error Name", context : context, intSeverity : 99, strDetails : "these are more details");

                Assert.IsNotNull(response2);
                Assert.IsTrue(response2.Success);
                Assert.IsFalse(String.IsNullOrWhiteSpace(response2.IncidentCode) || response2.IncidentCode == "0");
            }
        }
Ejemplo n.º 6
0
        protected virtual async Task <TagHelperResolutionResult> ResolveTagHelpersOutOfProcessAsync(IProjectEngineFactory factory, Project workspaceProject, ProjectSnapshot projectSnapshot)
        {
            // We're being overly defensive here because the OOP host can return null for the client/session/operation
            // when it's disconnected (user stops the process).
            //
            // This will change in the future to an easier to consume API but for VS RTM this is what we have.
            try
            {
                var remoteClient = await RazorRemoteHostClient.CreateAsync(_workspace, CancellationToken.None);

                var args = new object[]
                {
                    projectSnapshot,
                    factory?.GetType().AssemblyQualifiedName,
                };

                var result = await remoteClient.TryRunRemoteAsync <TagHelperResolutionResult>(
                    "GetTagHelpersAsync",
                    workspaceProject.Solution,
                    args,
                    CancellationToken.None).ConfigureAwait(false);

                return(result.HasValue ? result.Value : null);
            }
            catch (Exception ex)
            {
                // We silence exceptions from the OOP host because we don't want to bring down VS for an OOP failure.
                // We will retry all failures in process anyway, so if there's a real problem that isn't unique to OOP
                // then it will report a crash in VS.
                _errorReporter.ReportError(ex, projectSnapshot);
            }

            return(null);
        }
        protected void SendNotifications()
        {
            var pendingTriggers = General.ErrorLogging.Data.ErrorOtherLogTrigger.GetPendingTriggers();

            foreach (var trigger in pendingTriggers)
            {
                try
                {
                    var result = NotifyByTrigger(trigger);
                    if (result.Success || result.SMSSent || result.EmailSent)
                    {
                        General.ErrorLogging.Data.ErrorOtherLogTrigger.MarkAsProcessed(trigger.ID, result.Success, result.SMSSent, result.EmailSent, result.Detail);
                    }
                }
                catch (Exception ex)
                {
                    ApplicationContext context;
                    try
                    {
                        context = ErrorLogging.GetApplicationContext();
                    }
                    catch { context = new ApplicationContext(); }

                    if (trigger.Event.AppID > 0) //Don't report errors on yourself, it could create a loop of errors.
                    {
                        ErrorReporter.ReportError(ex, context);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void TestErrorSynchronous()
        {
            var response1 = ErrorReporter.ReportError("error").Result;

            Assert.IsNotNull(response1);
            Assert.IsTrue(response1.Success);
            Assert.IsFalse(String.IsNullOrWhiteSpace(response1.IncidentCode) || response1.IncidentCode == "0");
        }
Ejemplo n.º 9
0
        public async Task <TagHelperResolutionResult> GetTagHelpersAsync(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            try
            {
                TagHelperResolutionResult result;

                // We're being overly defensive here because the OOP host can return null for the client/session/operation
                // when it's disconnected (user stops the process).
                //
                // This will change in the future to an easier to consume API but for VS RTM this is what we have.
                var client = await RazorLanguageServiceClientFactory.CreateAsync(_workspace, CancellationToken.None);

                if (client != null)
                {
                    using (var session = await client.CreateSessionAsync(project.Solution))
                    {
                        if (session != null)
                        {
                            var jsonObject = await session.InvokeAsync <JObject>(
                                "GetTagHelpersAsync",
                                new object[] { project.Id.Id, "Foo", },
                                CancellationToken.None).ConfigureAwait(false);

                            result = GetTagHelperResolutionResult(jsonObject);

                            if (result != null)
                            {
                                return(result);
                            }
                        }
                    }
                }

                // The OOP host is turned off, so let's do this in process.
                var compilation = await project.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false);

                result = GetTagHelpers(compilation);
                return(result);
            }
            catch (Exception exception)
            {
                _errorReporter.ReportError(exception, project);

                throw new InvalidOperationException(
                          Resources.FormatUnexpectedException(
                              typeof(DefaultTagHelperResolver).FullName,
                              nameof(GetTagHelpersAsync)),
                          exception);
            }
        }
Ejemplo n.º 10
0
        public override void StartListening()
        {
            _projectSnapshotManagerDispatcher.AssertDispatcherThread();

            if (_fileChangeAdviseTask != null)
            {
                // Already listening
                return;
            }

            if (_fileChangeUnadviseTask is not {
                IsCompleted : false
            } fileChangeUnadviseTaskToJoin)
            {
                fileChangeUnadviseTaskToJoin = null;
            }

            _fileChangeAdviseTask = _joinableTaskContext.Factory.RunAsync(async() =>
            {
                try
                {
                    // If an unadvise operation is still processing, we don't start listening until it completes.
                    if (fileChangeUnadviseTaskToJoin is not null)
                    {
                        await fileChangeUnadviseTaskToJoin.JoinAsync().ConfigureAwait(true);
                    }

                    return(await _fileChangeService.AdviseFileChangeAsync(FilePath, FileChangeFlags, this).ConfigureAwait(true));
                }
                catch (PathTooLongException)
                {
                    // Don't report PathTooLongExceptions but don't fault either.
                }
                catch (Exception exception)
                {
                    // Don't explode on actual exceptions, just report gracefully.
                    _errorReporter.ReportError(exception);
                }

                return(VSConstants.VSCOOKIE_NIL);
            });
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Button delegate. Do not call externally.
 /// </summary>
 public void SaveOnClick()
 {
     if (mmc.TryGetComponent(out GameplayManager gm))
     {
         gm.WriteData();
     }
     else
     {
         errorReporter.ReportError("Unable to save.", "GameplayManager not attatched to master miscellaneous controller.", ErrorReporter.ActionType.ok);
     }
 }
Ejemplo n.º 12
0
        private static void BuildIfOutOfDate(bool runBuildsAsync, ReferencedFileSave rfs)
        {
            if (rfs.GetIsBuiltFileOutOfDate())
            {
                string error = rfs.PerformExternalBuild(runAsync: runBuildsAsync);

                if (!string.IsNullOrEmpty(error))
                {
                    ErrorReporter.ReportError(ProjectManager.MakeAbsolute(rfs.Name, true), error, false);
                }
            }
        }
Ejemplo n.º 13
0
        public override void StartListening()
        {
            _foregroundDispatcher.AssertForegroundThread();

            try
            {
                if (_fileChangeCookie == VSConstants.VSCOOKIE_NIL)
                {
                    var hr = _fileChangeService.AdviseFileChange(
                        FilePath,
                        FileChangeFlags,
                        this,
                        out _fileChangeCookie);

                    Marshal.ThrowExceptionForHR(hr);
                }
            }
            catch (Exception exception)
            {
                _errorReporter.ReportError(exception);
            }
        }
        public override void StartListening()
        {
            _foregroundDispatcher.AssertForegroundThread();

            if (_fileChangeUnadviseTask?.IsCompleted == false)
            {
                // An unadvise operation is still processing, block the foreground thread until it completes.
                _fileChangeUnadviseTask.Join();
            }

            if (_fileChangeAdviseTask != null)
            {
                // Already listening
                return;
            }

            _fileChangeAdviseTask = _joinableTaskFactory.RunAsync(async() =>
            {
                try
                {
                    return(await _fileChangeService.AdviseFileChangeAsync(FilePath, FileChangeFlags, this).ConfigureAwait(true));
                }
                catch (PathTooLongException)
                {
                    // Don't report PathTooLongExceptions but don't fault either.
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception exception)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    // Don't explode on actual exceptions, just report gracefully.
                    _errorReporter.ReportError(exception);
                }

                return(VSConstants.VSCOOKIE_NIL);
            });
        }
Ejemplo n.º 15
0
 private void btnError_Click(object sender, EventArgs e)
 {
     try
     {
         long  intTest = 42424242242423342;
         short test    = Convert.ToInt16(intTest);
     }
     catch (Exception ex)
     {
         ErrorReporter.ReportError(ex, "Form Test Error 1", strDetails: "these are more details").ContinueWith((task) =>
         {
             Console.WriteLine(task.Result.IncidentCode);
         });
         lblErrorIC.Text = "fire and forget";
     }
 }
 private static void SeparateThreadCallback()
 {
     try
     {
         Job objJob = (Job)_objThreadData[Thread.CurrentThread.Name];
         objJob.Callback(Thread.CurrentThread.Name); //SessionID
     }
     catch (Exception ex)
     {
         ErrorReporter.ReportError(ex);
     }
     finally
     {
         _objThreadData.Remove(Thread.CurrentThread.Name);
         Thread.CurrentThread.Abort();
     }
 }
Ejemplo n.º 17
0
        public async Task TestCode()
        {
            var context = new ApplicationContext(strClientID: "Organization ID/Name", strUserType: "UserType", strUserID: "UserID");

            await ErrorReporter.ReportError("Error 1", context, intSeverity : 8, intDuration : 1234);

            await ErrorReporter.ReportError("Error 2");

            await ErrorReporter.ReportAudit("Audit 1", context, strDetails : "This is what happened in detail", intDuration : 3333);

            await ErrorReporter.ReportAudit("Audit 2");

            await ErrorReporter.ReportTrace("Trace 1", context, strDetails : "Details", strMethodName : System.Reflection.MethodBase.GetCurrentMethod().Name, intDuration : 2222);

            await ErrorReporter.ReportTrace("Trace 2");

            await ErrorReporter.ReportWarning("Warning 1", context, strDetails : "A file couldn't be loaded, restoring from cache", strFileName : "File.jpg", intDuration : 1111);

            await ErrorReporter.ReportWarning("Warning 2");
        }
Ejemplo n.º 18
0
        protected virtual async Task <TagHelperResolutionResult> ResolveTagHelpersOutOfProcessAsync(IProjectEngineFactory factory, ProjectSnapshot project)
        {
            // We're being overly defensive here because the OOP host can return null for the client/session/operation
            // when it's disconnected (user stops the process).
            //
            // This will change in the future to an easier to consume API but for VS RTM this is what we have.
            try
            {
                var client = await RazorLanguageServiceClientFactory.CreateAsync(_workspace, CancellationToken.None);

                if (client != null)
                {
                    using (var session = await client.CreateSessionAsync(project.WorkspaceProject.Solution))
                    {
                        if (session != null)
                        {
                            var args = new object[]
                            {
                                Serialize(project),
                                factory == null ? null : factory.GetType().AssemblyQualifiedName,
                            };

                            var json = await session.InvokeAsync <JObject>("GetTagHelpersAsync", args, CancellationToken.None).ConfigureAwait(false);

                            return(Deserialize(json));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // We silence exceptions from the OOP host because we don't want to bring down VS for an OOP failure.
                // We will retry all failures in process anyway, so if there's a real problem that isn't unique to OOP
                // then it will report a crash in VS.
                _errorReporter.ReportError(ex, project);
            }

            return(null);
        }
Ejemplo n.º 19
0
        private async void btnErrorAwait_Click(object sender, EventArgs e)
        {
            try
            {
                long  intTest = 42424242242423342;
                short test    = Convert.ToInt16(intTest);
            }
            catch (Exception ex)
            {
                lblErrorIC.Text = "logging...";
                var response = await ErrorReporter.ReportError(ex, "Form Test Error 2", strDetails : "these are more details");

                if (response.Success)
                {
                    lblErrorIC.Text = response.IncidentCode;
                }
                else
                {
                    lblErrorIC.Text = response.Message;
                }
            }
        }
Ejemplo n.º 20
0
        public void ReportError_AfterErrorReported_AddsError()
        {
            // Arrange
            var node = YamlUtils.CreateYamlNode("name: promitor");

            // Act
            _errorReporter.ReportError(node, "Test error message");

            // Assert
            Assert.Collection(_errorReporter.Messages,
                              m =>
            {
                Assert.Equal(node, m.Node);
                Assert.Equal(MessageType.Error, m.MessageType);
                Assert.Equal("Test error message", m.Message);
            });
        }
Ejemplo n.º 21
0
 public override void ReportError(Exception exception)
 {
     _errorReporter.ReportError(exception);
 }
Ejemplo n.º 22
0
        private void RefreshSourceFileCache()
        {
            List <string> errors = new List <string>();


            // parallelizing this seems to screw things up when a plugin tries to do something on the UI thread
            //Parallel.ForEach(ProjectManager.GlueProjectSave.Screens, (screen) =>
            foreach (ScreenSave screen in ProjectManager.GlueProjectSave.Screens)
            {
                foreach (ReferencedFileSave rfs in screen.ReferencedFiles)
                {
                    string error;
                    rfs.RefreshSourceFileCache(true, out error);

                    if (!string.IsNullOrEmpty(error))
                    {
                        lock (errors)
                        {
                            errors.Add(error + " in " + screen.ToString());
                        }
                    }
                }
            }
            //);


            //Parallel.ForEach(ProjectManager.GlueProjectSave.Entities, (entitySave) =>
            foreach (EntitySave entitySave in ProjectManager.GlueProjectSave.Entities)
            {
                foreach (ReferencedFileSave rfs in entitySave.ReferencedFiles)
                {
                    string error;
                    rfs.RefreshSourceFileCache(true, out error);
                    if (!string.IsNullOrEmpty(error))
                    {
                        lock (errors)
                        {
                            errors.Add(error + " in " + entitySave.ToString());
                        }
                    }
                }
            }
            //);

            //Parallel.ForEach(ProjectManager.GlueProjectSave.GlobalFiles, (rfs) =>
            foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            {
                string error;
                rfs.RefreshSourceFileCache(true, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    lock (errors)
                    {
                        errors.Add(error + " in Global Content Files");
                    }
                }
            }
            //);


            foreach (var error in errors)
            {
                ErrorReporter.ReportError("", error, true);
            }
        }
Ejemplo n.º 23
0
        public ReferencedFileSave CreateReferencedFileSaveForExistingFile(IElement containerForFile, string directoryInsideContainer, string absoluteFileName,
                                                                          PromptHandleEnum unknownTypeHandle, AssetTypeInfo ati, out string creationReport, out string errorMessage)
        {
            creationReport = "";
            errorMessage   = null;

            ReferencedFileSave referencedFileSaveToReturn = null;

            string whyItIsntValid;
            // Let's see if there is already an Entity with the same name
            string fileWithoutPath = FileManager.RemovePath(FileManager.RemoveExtension(absoluteFileName));

            bool isValid =
                NameVerifier.IsReferencedFileNameValid(fileWithoutPath, ati, referencedFileSaveToReturn, containerForFile, out whyItIsntValid);

            if (!isValid)
            {
                errorMessage = "Invalid file name:\n" + fileWithoutPath + "\n" + whyItIsntValid;
            }
            else
            {
                Zipper.UnzipAndModifyFileIfZip(ref absoluteFileName);
                string extension = FileManager.GetExtension(absoluteFileName);

                bool isValidExtensionOrIsConfirmedByUser;
                bool isUnknownType;
                FlatRedBall.Glue.Plugins.ExportedImplementations.CommandInterfaces.ElementCommands.CheckAndWarnAboutUnknownFileTypes(unknownTypeHandle, extension, out isValidExtensionOrIsConfirmedByUser, out isUnknownType);

                string fileToAdd = null;
                if (isValidExtensionOrIsConfirmedByUser)
                {
                    string directoryThatFileShouldBeRelativeTo =
                        FlatRedBall.Glue.Plugins.ExportedImplementations.CommandInterfaces.ElementCommands.GetFullPathContentDirectory(containerForFile, directoryInsideContainer);

                    string projectDirectory = ProjectManager.ContentProject.GetAbsoluteContentFolder();

                    bool needsToCopy = !FileManager.IsRelativeTo(absoluteFileName, projectDirectory);


                    if (needsToCopy)
                    {
                        fileToAdd = directoryThatFileShouldBeRelativeTo + FileManager.RemovePath(absoluteFileName);
                        fileToAdd = FileManager.MakeRelative(fileToAdd, ProjectManager.ContentProject.GetAbsoluteContentFolder());

                        try
                        {
                            FileHelper.RecursivelyCopyContentTo(absoluteFileName,
                                                                FileManager.GetDirectory(absoluteFileName),
                                                                directoryThatFileShouldBeRelativeTo);
                        }
                        catch (System.IO.FileNotFoundException fnfe)
                        {
                            errorMessage = "Could not copy the files because of a missing file: " + fnfe.Message;
                        }
                    }
                    else
                    {
                        fileToAdd =
                            FlatRedBall.Glue.Plugins.ExportedImplementations.CommandInterfaces.ElementCommands.GetNameOfFileRelativeToContentFolder(absoluteFileName, directoryThatFileShouldBeRelativeTo, projectDirectory);
                    }
                }

                if (string.IsNullOrEmpty(errorMessage))
                {
                    BuildToolAssociation bta = null;

                    if (ati != null && !string.IsNullOrEmpty(ati.CustomBuildToolName))
                    {
                        bta =
                            BuildToolAssociationManager.Self.GetBuilderToolAssociationByName(ati.CustomBuildToolName);
                    }

                    if (containerForFile != null)
                    {
                        referencedFileSaveToReturn = containerForFile.AddReferencedFile(fileToAdd, ati, bta);
                    }
                    else
                    {
                        bool useFullPathAsName = false;
                        // todo - support built files here
                        referencedFileSaveToReturn = AddReferencedFileToGlobalContent(fileToAdd, useFullPathAsName);
                    }



                    // This will be null if there was an error above in creating this file
                    if (referencedFileSaveToReturn != null)
                    {
                        if (containerForFile != null)
                        {
                            containerForFile.HasChanged = true;
                        }

                        if (fileToAdd.EndsWith(".csv"))
                        {
                            string fileToAddAbsolute = ProjectManager.MakeAbsolute(fileToAdd);
                            CsvCodeGenerator.GenerateAndSaveDataClass(referencedFileSaveToReturn, referencedFileSaveToReturn.CsvDelimiter);
                        }
                        if (isUnknownType)
                        {
                            referencedFileSaveToReturn.LoadedAtRuntime = false;
                        }

                        string error;
                        referencedFileSaveToReturn.RefreshSourceFileCache(false, out error);

                        if (!string.IsNullOrEmpty(error))
                        {
                            ErrorReporter.ReportError(referencedFileSaveToReturn.Name, error, false);
                        }
                    }
                }
            }

            return(referencedFileSaveToReturn);
        }
Ejemplo n.º 24
0
    private void Report404(HttpContext context, string strPageRequested, string strQueryString)
    {
        context.Response.StatusCode = 404;
        context.Response.Status     = "404 Not Found";

        string strPageLowerCase = strPageRequested.ToLower();

        #region Ignore These
        if (strPageLowerCase.EndsWith("404.aspx"))
        {
            return;
        }
        //if (strPageLowerCase.EndsWith(".jpg"))
        //    return;
        //if (strPageLowerCase.EndsWith(".png"))
        //    return;
        //if (strPageLowerCase.EndsWith(".gif"))
        //    return;
        if (strPageLowerCase.Contains("sitemap.xml"))
        {
            return;
        }
        if (strPageLowerCase.Contains("favicon.ico"))
        {
            return;
        }
        if (strPageLowerCase.Contains("favicon.gif"))
        {
            return;
        }
        if (strPageLowerCase.Contains("robots.txt"))
        {
            return;
        }
        if (strPageLowerCase.Contains("__utm.gif"))
        {
            return;
        }
        if (strPageLowerCase.Contains("scriptresource.axd"))
        {
            return;
        }
        if (strPageLowerCase.Contains("webresource.axd"))
        {
            return;
        }
        if (strPageLowerCase.Contains("expressInstall.swf"))
        {
            return;
        }
        if (strPageLowerCase.Contains("apple-touch-icon"))
        {
            return;
        }
        #endregion

        #region Other Info
        string strOtherInfo             = String.Empty;
        string strUserAgent             = String.Empty;
        string strOriginalPageRequested = General.Web.WebTools.GetRequestedPageWithQueryString();
        try
        {
            strUserAgent = context.Request.UserAgent;
            if (!strUserAgent.ToLower().Contains("bot") && !strUserAgent.ToLower().Contains("spider") && !strUserAgent.ToLower().Contains("crawl"))
            {
                strUserAgent = context.Request.Browser.Browser;
            }

            strOtherInfo += "Referrer = " + General.Web.WebTools.GetReferrer() + "\r\n";
            strOtherInfo += "HostAddress = " + context.Request.UserHostAddress + "\r\n";
            strOtherInfo += "LocalPath = " + context.Server.MapPath("/" + strPageRequested) + "\r\n";
            strOtherInfo += "UserAgent = " + context.Request.UserAgent + "\r\n";
        }
        catch { }
        #endregion

        try
        {
            General.ErrorLogging.Data.Error404.RecordError404(AppID, General.Environment.Current.WhereAmI(), ClientID, strPageRequested, strUserAgent, strOtherInfo);
        }
        catch (Exception ex)
        {
            #region Last Resort - Report an Error
            try
            {
                ErrorReporter.ReportError(ex, new ApplicationContext());
            }
            catch { }
            #endregion
        }
    }
Ejemplo n.º 25
0
        public ReferencedFileSave CreateReferencedFileSaveForExistingFile(IElement containerForFile, string directoryInsideContainer, string absoluteFileName,
                                                                          PromptHandleEnum unknownTypeHandle, AssetTypeInfo ati, out string creationReport, out string errorMessage)
        {
            creationReport = "";
            errorMessage   = null;

            ReferencedFileSave referencedFileSaveToReturn = null;

            string whyItIsntValid;
            // Let's see if there is already an Entity with the same name
            string fileWithoutPath = FileManager.RemovePath(FileManager.RemoveExtension(absoluteFileName));

            bool isValid =
                NameVerifier.IsReferencedFileNameValid(fileWithoutPath, ati, referencedFileSaveToReturn, containerForFile, out whyItIsntValid);

            if (!isValid)
            {
                errorMessage = "Invalid file name:\n" + fileWithoutPath + "\n" + whyItIsntValid;
            }
            else
            {
                Zipper.UnzipAndModifyFileIfZip(ref absoluteFileName);
                string extension = FileManager.GetExtension(absoluteFileName);

                bool isValidExtensionOrIsConfirmedByUser;
                bool isUnknownType;
                CheckAndWarnAboutUnknownFileTypes(unknownTypeHandle, extension, out isValidExtensionOrIsConfirmedByUser, out isUnknownType);

                if (isValidExtensionOrIsConfirmedByUser)
                {
                    string directoryThatFileShouldBeRelativeTo = GetFullPathContentDirectory(containerForFile, directoryInsideContainer);

                    string projectDirectory = ProjectManager.ContentProject.GetAbsoluteContentFolder();

                    string fileToAdd = GetNameOfFileRelativeToContentFolder(absoluteFileName, directoryThatFileShouldBeRelativeTo, projectDirectory);

                    BuildToolAssociation bta = null;

                    if (ati != null && !string.IsNullOrEmpty(ati.CustomBuildToolName))
                    {
                        bta =
                            BuildToolAssociationManager.Self.GetBuilderToolAssociationByName(ati.CustomBuildToolName);
                    }

                    if (containerForFile != null)
                    {
                        referencedFileSaveToReturn = containerForFile.AddReferencedFile(fileToAdd, ati, bta);
                    }
                    else
                    {
                        bool useFullPathAsName = false;
                        // todo - support built files here
                        referencedFileSaveToReturn = AddReferencedFileToGlobalContent(fileToAdd, useFullPathAsName);
                    }



                    // This will be null if there was an error above in creating this file
                    if (referencedFileSaveToReturn != null)
                    {
                        if (containerForFile != null)
                        {
                            containerForFile.HasChanged = true;
                        }

                        if (fileToAdd.EndsWith(".csv"))
                        {
                            string fileToAddAbsolute = ProjectManager.MakeAbsolute(fileToAdd);
                            CsvCodeGenerator.GenerateAndSaveDataClass(referencedFileSaveToReturn, referencedFileSaveToReturn.CsvDelimiter);
                        }
                        if (isUnknownType)
                        {
                            referencedFileSaveToReturn.LoadedAtRuntime = false;
                        }

                        ProjectManager.UpdateFileMembershipInProject(referencedFileSaveToReturn);

                        PluginManager.ReactToNewFile(referencedFileSaveToReturn);
                        GluxCommands.Self.SaveGlux();
                        ProjectManager.SaveProjects();
                        UnreferencedFilesManager.Self.RefreshUnreferencedFiles(false);

                        string error;
                        referencedFileSaveToReturn.RefreshSourceFileCache(false, out error);

                        if (!string.IsNullOrEmpty(error))
                        {
                            ErrorReporter.ReportError(referencedFileSaveToReturn.Name, error, false);
                        }
                    }
                }
            }

            return(referencedFileSaveToReturn);
        }
Ejemplo n.º 26
0
 private static void HandleJobError(Exception ex)
 {
     ErrorReporter.ReportError(ex, "Bkgnd Task");
 }
Ejemplo n.º 27
0
 void ReportError(string message, Terminal spellingNode, AbstractSyntaxTree positionNode)
 {
     _errorReporter.ReportError(message, spellingNode.Spelling, positionNode.Position);
 }
Ejemplo n.º 28
0
 public override void LogException(Exception ex) => _errorReporter.ReportError(ex);
Ejemplo n.º 29
0
        public static bool UpdateFile(string changedFile)
        {
            bool shouldSave = false;
            bool handled    = false;

            lock (mUpdateFileLock)
            {
                if (ProjectManager.ProjectBase != null)
                {
                    handled = TryHandleProjectFileChanges(changedFile);

                    string projectFileName = ProjectManager.ProjectBase.FullFileName;

                    var standardizedGlux = FileManager.RemoveExtension(FileManager.Standardize(projectFileName).ToLower()) + ".glux";
                    var partialGlux      = FileManager.RemoveExtension(FileManager.Standardize(projectFileName).ToLower()) + @"\..*\.generated\.glux";
                    var partialGluxRegex = new Regex(partialGlux);
                    if (!handled && ((changedFile.ToLower() == standardizedGlux) || partialGluxRegex.IsMatch(changedFile.ToLower())))
                    {
                        TaskManager.Self.OnUiThread(ReloadGlux);
                        handled = true;
                    }

                    if (ProjectManager.IsContent(changedFile))
                    {
                        PluginManager.ReactToChangedFile(changedFile);
                    }

                    #region If it's a CSV, then re-generate the code for the objects

                    string extension = FileManager.GetExtension(changedFile);

                    if (extension == "csv" ||
                        extension == "txt")
                    {
                        ReferencedFileSave rfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(changedFile);

                        bool shouldGenerate = rfs != null &&
                                              (extension == "csv" || rfs.TreatAsCsv) &&
                                              rfs.IsDatabaseForLocalizing == false;

                        if (shouldGenerate)
                        {
                            try
                            {
                                CsvCodeGenerator.GenerateAndSaveDataClass(rfs, rfs.CsvDelimiter);

                                shouldSave = true;
                            }
                            catch (Exception e)
                            {
                                GlueCommands.Self.PrintError("Error saving Class from CSV " + rfs.Name +
                                                             "\n" + e.ToString());
                            }
                        }
                    }


                    #endregion

                    #region If it's a file that references other content we may need to update the project

                    if (FileHelper.DoesFileReferenceContent(changedFile))
                    {
                        ReferencedFileSave rfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(changedFile);


                        if (rfs != null)
                        {
                            string error;
                            rfs.RefreshSourceFileCache(false, out error);

                            if (!string.IsNullOrEmpty(error))
                            {
                                ErrorReporter.ReportError(rfs.Name, error, false);
                            }
                            else
                            {
                                handled = true;
                            }

                            handled   |= GlueCommands.Self.ProjectCommands.UpdateFileMembershipInProject(rfs);
                            shouldSave = true;

                            MainGlueWindow.Self.Invoke((MethodInvoker) delegate
                            {
                                if (rfs.GetContainerType() == ContainerType.Entity)
                                {
                                    if (EditorLogic.CurrentEntityTreeNode != null)
                                    {
                                        if (EditorLogic.CurrentEntitySave == rfs.GetContainer())
                                        {
                                            PluginManager.RefreshCurrentElement();
                                        }
                                    }
                                }
                                else if (rfs.GetContainerType() == ContainerType.Screen)
                                {
                                    if (EditorLogic.CurrentScreenTreeNode != null)
                                    {
                                        if (EditorLogic.CurrentScreenSave == rfs.GetContainer())
                                        {
                                            PluginManager.RefreshCurrentElement();
                                        }
                                    }
                                }
                            });
                        }
                        else
                        {
                            // There may not be a RFS for this in Glue, but even if there's not,
                            // this file may be referenced by other RFS's.  I don't want to do a full
                            // project scan, so we'll just see if this file is part of Visual Studio.  If so
                            // then let's add its children

                            if (ProjectManager.ContentProject.IsFilePartOfProject(changedFile))
                            {
                                string relativePath = ProjectManager.MakeRelativeContent(changedFile);

                                shouldSave |= GlueCommands.Self.ProjectCommands.UpdateFileMembershipInProject(
                                    ProjectManager.ProjectBase, relativePath, false, false);
                                handled |= shouldSave;
                            }
                        }
                    }

                    #endregion

                    #region If it's a .cs file, we should see if we've added a new .cs file, and if so refresh the Element for it
                    if (extension == "cs")
                    {
                        TaskManager.Self.OnUiThread(() => ReactToChangedCodeFile(changedFile));
                    }


                    #endregion

                    #region Maybe it's a directory that was added or removed

                    if (FileManager.GetExtension(changedFile) == "")
                    {
                        ElementViewWindow.Invoke((MethodInvoker) delegate
                        {
                            try
                            {
                                // It's a directory, so let's just rebuild our directory TreeNodes
                                ElementViewWindow.AddDirectoryNodes();
                            }
                            catch (System.IO.IOException)
                            {
                                // this could be because something else is accessing the directory, so sleep, try again
                                System.Threading.Thread.Sleep(100);
                                ElementViewWindow.AddDirectoryNodes();
                            }
                        });
                    }

                    #endregion


                    #region Check for broken references to objects in file - like an Entity may reference an object in a file but it may have been removed

                    if (ObjectFinder.Self.GetReferencedFileSaveFromFile(changedFile) != null)
                    {
                        // This is a file that is part of the project, so let's see if any named objects are missing references
                        CheckForBrokenReferencesToObjectsInFile(changedFile);
                    }

                    #endregion

                    // This could be an externally built file:

                    ProjectManager.UpdateExternallyBuiltFile(changedFile);

                    if (handled)
                    {
                        PluginManager.ReceiveOutput("Handled changed file: " + changedFile);
                    }

                    if (shouldSave)
                    {
                        ProjectManager.SaveProjects();
                    }
                }
            }

            return(handled);
        }
Ejemplo n.º 30
0
 public ErrorAlert(string message, Exception error) : base(message, $"Message: {error.Message}\r\n{JsonConvert.SerializeObject(error)}", "OK")
 {
     ErrorReporter.ReportError(message, error);
 }