Пример #1
0
 /// <summary>
 /// 
 /// </summary>
 public static void LogDeviceInfo()
 {
     using (var service = new LoggingService(ApplicationName))
     {
         service.Enable();
         service.WriteDiagnostics();
         service.Dispose();
     }
 }
Пример #2
0
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
               // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {

                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            // log the error by using your own method
            string message = string.Format("Controller Name : {0}, Action Method: {1}, Error Message :{2}", controllerName, actionName, filterContext.Exception.Message);
            ILogger logService = new LoggingService();
            logService.Error(message, filterContext.Exception);
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
 public void WritingAnErrorMessageToTheDatabaseShouldStoreAnErrorMessage()
 {
     using (var source = new TestLoggingSource())
     {
         var before = source.ErrorLogQuery().Count();
         var loggingService = new LoggingService(source);
         loggingService.Log("Test", LogLevel.Error);
         var after = source.ErrorLogQuery().Count();
         Assert.IsTrue(after == before + 1);
     }
 }
 public void WritingAnAuditMessageToTheDatabaseShouldStoreAnAuditMessage()
 {
     using (var source = new TestLoggingSource())
     {
         var before = source.AuditLogQuery().Count();
         var loggingService = new LoggingService(source);
         loggingService.LogToAudit("Test", "AuditTest");
         var after = source.AuditLogQuery().Count();
         Assert.IsTrue(after == before + 1);
     }
 }
Пример #5
0
 /// <summary>
 /// 记录错误日志
 /// </summary>
 /// <param name="message"></param>
 /// <param name="e"></param>
 /// <param name="isWriteDebug"></param>
 public static void Log(string message, Exception e, bool isWriteDebug)
 {
     using (var service = new LoggingService(ApplicationName))
     {
         service.Enable();
         service.Write(e.Message);
         service.Dispose();
     }
     if (isWriteDebug)
     {
         WriteDebug(message);
     }
 }
		static void RegisterLoggingService(SPFeatureReceiverProperties properties)
		{
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPFarm farm = properties.Definition.Farm;

                if (farm != null)
                {
                    LoggingService service = LoggingService.Local;

                    if (service == null)
                    {
                        service = new LoggingService();
                        service.Update();

                        if (service.Status != SPObjectStatus.Online)
                            service.Provision();
                    }
                    //foreach (SPServer server in farm.Servers)
                    //{
                    //    RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, server.Address);

                    //    if (baseKey != null)
                    //    {
                    //        RegistryKey eventLogKey = baseKey.OpenSubKey(EventLogApplicationRegistryKeyPath, true);

                    //        if (eventLogKey != null)
                    //        {
                    //            RegistryKey loggingServiceKey = eventLogKey.OpenSubKey(LoggingService.AreaName);

                    //            if (loggingServiceKey == null)
                    //            {
                    //                loggingServiceKey = eventLogKey.CreateSubKey(LoggingService.AreaName, RegistryKeyPermissionCheck.ReadWriteSubTree);
                    //                loggingServiceKey.SetValue("EventMessageFile", @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll", RegistryValueKind.String);
                    //            }
                    //        }
                    //    }
                    //}
                }
            });
		}
        internal void DoReSmartIndent(int cursor)
        {
            SafeUpdateIndentEngine(cursor);
            if (stateTracker.LineBeganInsideVerbatimString || stateTracker.LineBeganInsideMultiLineComment || stateTracker.IsInsidePreprocessorDirective)
            {
                return;
            }
            if (DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto)
            {
                Editor.FixVirtualIndentation();
                return;
            }
            var line = Editor.GetLineByOffset(cursor);

            // Get context to the end of the line w/o changing the main engine's state
            var curTracker = stateTracker.Clone();

            try {
                for (int max = cursor; max < line.EndOffset; max++)
                {
                    curTracker.Push(Editor.GetCharAt(max));
                }
            } catch (Exception e) {
                LoggingService.LogError("Exception during indentation", e);
            }

            int    pos       = line.Offset;
            string curIndent = line.GetIndentation(Editor);
            int    nlwsp     = curIndent.Length;
            int    offset    = cursor > pos + nlwsp ? cursor - (pos + nlwsp) : 0;

            if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < line.LengthIncludingDelimiter && Editor.GetCharAt(line.Offset + nlwsp) == '*'))
            {
                // Possibly replace the indent
                string newIndent       = curTracker.ThisLineIndent;
                int    newIndentLength = newIndent.Length;
                if (newIndent != curIndent)
                {
                    if (CompletionWindowManager.IsVisible)
                    {
                        if (pos < CompletionWindowManager.CodeCompletionContext.TriggerOffset)
                        {
                            CompletionWindowManager.CodeCompletionContext.TriggerOffset -= nlwsp;
                        }
                    }
                    newIndentLength = newIndent.Length;
                    Editor.ReplaceText(pos, nlwsp, newIndent);
                    //textEditorData.CommitLineUpdate (textEditorData.CaretLine);
                    CompletionWindowManager.HideWindow();
                }
                pos += newIndentLength;
            }
            else
            {
                pos += curIndent.Length;
            }

            pos += offset;

            Editor.FixVirtualIndentation();
        }
Пример #8
0
 public AuthenticodeSigner(X509Certificate2 certificate, LoggingService log)
 {
     Certificate = certificate;
     _loggingService = log;
 }
Пример #9
0
        internal static void SearchReplace(string findPattern, string replacePattern, Scope scope, FilterOptions options, System.Action UpdateStopButton)
        {
            if (find != null && find.IsRunning)
            {
                if (!MessageService.Confirm(GettextCatalog.GetString("There is a search already in progress. Do you want to stop it?"), AlertButton.Stop))
                {
                    return;
                }
            }
            searchTokenSource.Cancel();

            if (scope == null)
            {
                return;
            }

            find = new FindReplace();

            string pattern = findPattern;

            if (String.IsNullOrEmpty(pattern))
            {
                return;
            }
            if (!find.ValidatePattern(options, pattern))
            {
                MessageService.ShowError(GettextCatalog.GetString("Search pattern is invalid"));
                return;
            }

            if (replacePattern != null && !find.ValidatePattern(options, replacePattern))
            {
                MessageService.ShowError(GettextCatalog.GetString("Replace pattern is invalid"));
                return;
            }
            var cancelSource = new CancellationTokenSource();

            searchTokenSource = cancelSource;
            var token = cancelSource.Token;

            currentTask = Task.Run(delegate {
                using (SearchProgressMonitor searchMonitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, cancellationTokenSource: cancelSource)) {
                    searchMonitor.PathMode = scope.PathMode;

                    searchMonitor.ReportStatus(scope.GetDescription(options, pattern, null));
                    if (UpdateStopButton != null)
                    {
                        Application.Invoke(delegate {
                            UpdateStopButton();
                        });
                    }

                    DateTime timer      = DateTime.Now;
                    string errorMessage = null;

                    try {
                        var results = new List <SearchResult> ();
                        foreach (SearchResult result in find.FindAll(scope, searchMonitor, pattern, replacePattern, options, token))
                        {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            results.Add(result);
                        }
                        searchMonitor.ReportResults(results);
                    } catch (Exception ex) {
                        errorMessage = ex.Message;
                        LoggingService.LogError("Error while search", ex);
                    }

                    string message;
                    if (errorMessage != null)
                    {
                        message = GettextCatalog.GetString("The search could not be finished: {0}", errorMessage);
                        searchMonitor.ReportError(message, null);
                    }
                    else if (searchMonitor.CancellationToken.IsCancellationRequested)
                    {
                        message = GettextCatalog.GetString("Search cancelled.");
                        searchMonitor.ReportWarning(message);
                    }
                    else
                    {
                        string matches = string.Format(GettextCatalog.GetPluralString("{0} match found", "{0} matches found", find.FoundMatchesCount), find.FoundMatchesCount);
                        string files   = string.Format(GettextCatalog.GetPluralString("in {0} file.", "in {0} files.", find.SearchedFilesCount), find.SearchedFilesCount);
                        message        = GettextCatalog.GetString("Search completed.") + Environment.NewLine + matches + " " + files;
                        searchMonitor.ReportSuccess(message);
                    }
                    searchMonitor.ReportStatus(message);
                    searchMonitor.Log.WriteLine(GettextCatalog.GetString("Search time: {0} seconds."), (DateTime.Now - timer).TotalSeconds);
                }
                if (UpdateStopButton != null)
                {
                    Application.Invoke(delegate {
                        UpdateStopButton();
                    });
                }
            });
        }
Пример #10
0
 public ServiceBase(IServiceProvider provider)
 {
     _log = provider.GetRequiredService <LoggingService>();
     _log.Log($"{ this.GetType().Name } created");
 }
Пример #11
0
 public ToolboxService()
 {
     LoggingService.Info("Create Tolboxservice");
 }
Пример #12
0
        public ActionResult Show(string slug, int?p)
        {
            // Set the page index
            var pageIndex = p ?? 1;

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Get the topic
                var topic = _topicService.GetTopicBySlug(slug);

                if (topic != null)
                {
                    // Note: Don't use topic.Posts as its not a very efficient SQL statement
                    // Use the post service to get them as it includes other used entities in one
                    // statement rather than loads of sql selects

                    var sortQuerystring = Request.QueryString[AppConstants.PostOrderBy];
                    var orderBy         = !string.IsNullOrEmpty(sortQuerystring) ?
                                          EnumUtils.ReturnEnumValueFromString <PostOrderBy>(sortQuerystring) : PostOrderBy.Standard;

                    // Store the amount per page
                    var amountPerPage = SettingsService.GetSettings().PostsPerPage;

                    if (sortQuerystring == AppConstants.AllPosts)
                    {
                        // Overide to show all posts
                        amountPerPage = int.MaxValue;
                    }

                    // Get the posts
                    var posts = _postService.GetPagedPostsByTopic(pageIndex,
                                                                  amountPerPage,
                                                                  int.MaxValue,
                                                                  topic.Id,
                                                                  orderBy);

                    // Get the topic starter post
                    var topicStarter = _postService.GetTopicStarterPost(topic.Id);

                    // Get the permissions for the category that this topic is in
                    var permissions = RoleService.GetPermissions(topic.Category, UsersRole);

                    // If this user doesn't have access to this topic then
                    // redirect with message
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked)
                    {
                        return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                    }

                    // See if the user has subscribed to this topic or not
                    var isSubscribed = UserIsAuthenticated && (_topicNotificationService.GetByUserAndTopic(LoggedOnUser, topic).Any());

                    // Populate the view model for this page
                    var viewModel = new ShowTopicViewModel
                    {
                        Topic        = topic,
                        Posts        = posts,
                        PageIndex    = posts.PageIndex,
                        TotalCount   = posts.TotalCount,
                        Permissions  = permissions,
                        User         = LoggedOnUser,
                        IsSubscribed = isSubscribed,
                        UserHasAlreadyVotedInPoll = false,
                        TopicStarterPost          = topicStarter
                    };

                    // If there is a quote querystring
                    var quote = Request["quote"];
                    if (!string.IsNullOrEmpty(quote))
                    {
                        try
                        {
                            // Got a quote
                            var postToQuote = _postService.Get(new Guid(quote));
                            viewModel.PostContent = postToQuote.PostContent;
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Error(ex);
                        }
                    }

                    // See if the topic has a poll, and if so see if this user viewing has already voted
                    if (topic.Poll != null)
                    {
                        // There is a poll and a user
                        // see if the user has voted or not
                        var votes = topic.Poll.PollAnswers.SelectMany(x => x.PollVotes).ToList();
                        if (UserIsAuthenticated)
                        {
                            viewModel.UserHasAlreadyVotedInPoll = (votes.Count(x => x.User.Id == LoggedOnUser.Id) > 0);
                        }
                        viewModel.TotalVotesInPoll = votes.Count();
                    }

                    // User has permission lets update the topic view count
                    // but only if this topic doesn't belong to the user looking at it
                    var addView = !(UserIsAuthenticated && LoggedOnUser.Id == topic.User.Id);

                    if (!BotUtils.UserIsBot() && addView)
                    {
                        // Cool, user doesn't own this topic
                        topic.Views = (topic.Views + 1);
                        try
                        {
                            unitOfWork.Commit();
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Error(ex);
                        }
                    }

                    return(View(viewModel));
                }
            }
            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
        }
Пример #13
0
 void ReportExtensionError(Exception ex)
 {
     LoggingService.LogInternalError("Error in text editor extension chain", ex);
 }
Пример #14
0
        public static TargetFramework FromFrameworkDirectory(TargetFrameworkMoniker moniker, FilePath dir)
        {
            var fxList = dir.Combine("RedistList", "FrameworkList.xml");

            if (!File.Exists(fxList))
            {
                return(null);
            }

            var fx = new TargetFramework(moniker);

            using (var reader = System.Xml.XmlReader.Create(fxList)) {
                if (!reader.ReadToDescendant("FileList"))
                {
                    throw new Exception("Missing FileList element");
                }

                //not sure what this is for
                //if (reader.MoveToAttribute ("Redist") && reader.ReadAttributeValue ())
                //	redist = reader.ReadContentAsString ();

                if (reader.MoveToAttribute("Name") && reader.ReadAttributeValue())
                {
                    fx.name = reader.ReadContentAsString();
                }

                if (reader.MoveToAttribute("RuntimeVersion") && reader.ReadAttributeValue())
                {
                    string runtimeVersion = reader.ReadContentAsString();
                    switch (runtimeVersion)
                    {
                    case "2.0":
                        fx.clrVersion = ClrVersion.Net_2_0;
                        break;

                    case "4.0":
                        fx.clrVersion = ClrVersion.Net_4_0;
                        break;

                    //The concept of "ClrVersion" breaks down hard after 4.5 and is essentially meaningless
                    default:
                        fx.clrVersion = ClrVersion.Net_4_5;
                        break;
                    }
                }

                if (reader.MoveToAttribute("ToolsVersion") && reader.ReadAttributeValue())
                {
                    string toolsVersion = reader.ReadContentAsString();
                    switch (toolsVersion)
                    {
                    case "2.0":
                        fx.toolsVersion = TargetFrameworkToolsVersion.V2_0;
                        break;

                    case "3.5":
                        fx.toolsVersion = TargetFrameworkToolsVersion.V3_5;
                        break;

                    case "4.0":
                        fx.toolsVersion = TargetFrameworkToolsVersion.V4_0;
                        break;

                    case "4.5":
                        fx.toolsVersion = TargetFrameworkToolsVersion.V4_5;
                        break;

                    default:
                        LoggingService.LogInfo("Framework {0} has unknown ToolsVersion {1}", moniker, toolsVersion);
                        return(null);
                    }
                }

                if (reader.MoveToAttribute("IncludeFramework") && reader.ReadAttributeValue())
                {
                    string include = reader.ReadContentAsString();
                    if (!string.IsNullOrEmpty(include))
                    {
                        fx.includesFramework = include;
                    }
                }

                //this is a Mono-specific extension
                if (reader.MoveToAttribute("TargetFrameworkDirectory") && reader.ReadAttributeValue())
                {
                    string targetDir = reader.ReadContentAsString();
                    if (!string.IsNullOrEmpty(targetDir))
                    {
                        targetDir = targetDir.Replace('\\', System.IO.Path.DirectorySeparatorChar);
                        dir       = fxList.ParentDirectory.Combine(targetDir).FullPath;
                    }
                }

                var assemblies = new List <AssemblyInfo> ();
                if (reader.ReadToFollowing("File"))
                {
                    do
                    {
                        var ainfo = new AssemblyInfo();
                        assemblies.Add(ainfo);
                        if (reader.MoveToAttribute("AssemblyName") && reader.ReadAttributeValue())
                        {
                            ainfo.Name = reader.ReadContentAsString();
                        }
                        if (string.IsNullOrEmpty(ainfo.Name))
                        {
                            throw new Exception("Missing AssemblyName attribute");
                        }
                        if (reader.MoveToAttribute("Version") && reader.ReadAttributeValue())
                        {
                            ainfo.Version = reader.ReadContentAsString();
                        }
                        if (reader.MoveToAttribute("PublicKeyToken") && reader.ReadAttributeValue())
                        {
                            ainfo.PublicKeyToken = reader.ReadContentAsString();
                        }
                        if (reader.MoveToAttribute("Culture") && reader.ReadAttributeValue())
                        {
                            ainfo.Culture = reader.ReadContentAsString();
                        }
                        if (reader.MoveToAttribute("ProcessorArchitecture") && reader.ReadAttributeValue())
                        {
                            ainfo.ProcessorArchitecture = (ProcessorArchitecture)
                                                          Enum.Parse(typeof(ProcessorArchitecture), reader.ReadContentAsString(), true);
                        }
                        if (reader.MoveToAttribute("InGac") && reader.ReadAttributeValue())
                        {
                            ainfo.InGac = reader.ReadContentAsBoolean();
                        }
                    } while (reader.ReadToFollowing("File"));
                }
                else if (Directory.Exists(dir))
                {
                    foreach (var f in Directory.EnumerateFiles(dir, "*.dll"))
                    {
                        try {
                            var an    = SystemAssemblyService.GetAssemblyNameObj(dir.Combine(f));
                            var ainfo = new AssemblyInfo();
                            ainfo.Update(an);
                            assemblies.Add(ainfo);
                        } catch (BadImageFormatException ex) {
                            LoggingService.LogError("Invalid assembly in framework '{0}': {1}{2}{3}", fx.Id, f, Environment.NewLine, ex.ToString());
                        } catch (Exception ex) {
                            LoggingService.LogError("Error reading assembly '{0}' in framework '{1}':{2}{3}",
                                                    f, fx.Id, Environment.NewLine, ex.ToString());
                        }
                    }
                }

                fx.Assemblies = assemblies.ToArray();
            }

            var supportedFrameworksDir = dir.Combine("SupportedFrameworks");

            if (Directory.Exists(supportedFrameworksDir))
            {
                foreach (var sfx in Directory.GetFiles(supportedFrameworksDir))
                {
                    fx.SupportedFrameworks.Add(SupportedFramework.Load(fx, sfx));
                }
            }

            return(fx);
        }
Пример #15
0
 public void LogError(string message, Exception ex)
 {
     LoggingService.LogError(message, ex);
 }
Пример #16
0
 /// <summary>
 /// Initialize function called when this plugin is first loaded.
 /// </summary>
 /// <param name="logService"></param>
 /// <returns></returns>
 public override bool Initialize(LoggingService logService)
 {
     this.m_LoggingService = logService;
     return(true);
 }
        internal static async Task UpdateFoldings(TextEditor Editor, ParsedDocument parsedDocument, DocumentLocation caretLocation, bool firstTime = false, CancellationToken token = default(CancellationToken))
        {
            if (parsedDocument == null || !Editor.Options.ShowFoldMargin)
            {
                return;
            }
            // don't update parsed documents that contain errors - the foldings from there may be invalid.
            if (await parsedDocument.HasErrorsAsync(token))
            {
                return;
            }

            try {
                var foldSegments = new List <IFoldSegment> ();

                foreach (FoldingRegion region in await parsedDocument.GetFoldingsAsync(token))
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    var  type      = FoldingType.Unknown;
                    bool setFolded = false;
                    bool folded    = false;
                    //decide whether the regions should be folded by default
                    switch (region.Type)
                    {
                    case FoldType.Member:
                        type = FoldingType.TypeMember;
                        break;

                    case FoldType.Type:
                        type = FoldingType.TypeDefinition;
                        break;

                    case FoldType.UserRegion:
                        type      = FoldingType.Region;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultRegionsFolding;
                        folded    = true;
                        break;

                    case FoldType.Comment:
                        type      = FoldingType.Comment;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
                        folded    = true;
                        break;

                    case FoldType.CommentInsideMember:
                        type      = FoldingType.Comment;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
                        folded    = false;
                        break;

                    case FoldType.Undefined:
                        setFolded = true;
                        folded    = region.IsFoldedByDefault;
                        break;
                    }
                    var start  = Editor.LocationToOffset(region.Region.Begin);
                    var end    = Editor.LocationToOffset(region.Region.End);
                    var marker = Editor.CreateFoldSegment(start, end - start);
                    foldSegments.Add(marker);
                    marker.CollapsedText = region.Name;
                    marker.FoldingType   = type;
                    //and, if necessary, set its fold state
                    if (marker != null && setFolded && firstTime)
                    {
                        // only fold on document open, later added folds are NOT folded by default.
                        marker.IsCollapsed = folded;
                        continue;
                    }
                    if (marker != null && region.Region.Contains(caretLocation.Line, caretLocation.Column))
                    {
                        marker.IsCollapsed = false;
                    }
                }
                if (firstTime)
                {
                    Editor.SetFoldings(foldSegments);
                }
                else
                {
                    Application.Invoke(delegate {
                        if (!token.IsCancellationRequested)
                        {
                            Editor.SetFoldings(foldSegments);
                        }
                    });
                }
            } catch (OperationCanceledException) {
            } catch (Exception ex) {
                LoggingService.LogError("Unhandled exception in ParseInformationUpdaterWorkerThread", ex);
            }
        }
Пример #18
0
 public void ReportError(string message, System.Exception ex)
 {
     LoggingService.LogError(message, ex);
 }
Пример #19
0
        public async Task <bool> Execute(ProgressMonitor monitor, WorkspaceObject entry, ExecutionContext context,
                                         ConfigurationSelector configuration)
        {
            ProcessExecutionCommand cmd = CreateExecutionCommand(entry, configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1}", cmd.Command, cmd.Arguments));

            if (!Directory.Exists(cmd.WorkingDirectory))
            {
                monitor.ReportError(GettextCatalog.GetString("Custom command working directory does not exist"), null);
                return(false);
            }

            ProcessAsyncOperation oper    = null;
            OperationConsole      console = null;
            var result = true;

            try {
                if (context != null)
                {
                    if (externalConsole)
                    {
                        console = context.ExternalConsoleFactory.CreateConsole(!pauseExternalConsole, monitor.CancellationToken);
                    }
                    else
                    {
                        console = context.ConsoleFactory.CreateConsole(monitor.CancellationToken);
                    }
                    oper = context.ExecutionHandler.Execute(cmd, console);
                }
                else
                {
                    if (externalConsole)
                    {
                        console = context.ExternalConsoleFactory.CreateConsole(!pauseExternalConsole, monitor.CancellationToken);
                        oper    = Runtime.ProcessService.StartConsoleProcess(cmd.Command, cmd.Arguments,
                                                                             cmd.WorkingDirectory, console, null);
                    }
                    else
                    {
                        oper = Runtime.ProcessService.StartProcess(cmd.Command, cmd.Arguments,
                                                                   cmd.WorkingDirectory, monitor.Log, monitor.Log, null, false).ProcessAsyncOperation;
                    }
                }

                var stopper = monitor.CancellationToken.Register(oper.Cancel);

                await oper.Task;

                stopper.Dispose();

                if (oper.ExitCode != 0)
                {
                    monitor.ReportError("Custom command failed (exit code: " + oper.ExitCode + ")", null);
                }
            } catch (Win32Exception w32ex) {
                monitor.ReportError(GettextCatalog.GetString("Failed to execute custom command '{0}': {1}",
                                                             cmd.Command, w32ex.Message), null);
                return(false);
            } catch (Exception ex) {
                LoggingService.LogError("Command execution failed", ex);
                throw new UserException(GettextCatalog.GetString("Command execution failed: {0}", ex.Message));
            } finally {
                result = oper != null && oper.ExitCode == 0;
                if (console != null)
                {
                    console.Dispose();
                }
            }
            return(result);
        }
Пример #20
0
        public ActionResult Create(CreateEditTopicViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var cats = _categoryService.GetAllowedEditCategories(UsersRole);
                if (cats.Count > 0)
                {
                    if (ModelState.IsValid)
                    {
                        if (CheckCats(viewModel.Category, cats))
                        {
                            var topic = new Topic();
                            var post  = new Post();

                            topic.Name              = viewModel.Name;
                            topic.Category_Id       = viewModel.Category;
                            topic.IsLocked          = viewModel.IsLocked;
                            topic.IsSticky          = viewModel.IsSticky;
                            topic.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            topic.Id = post.Id;

                            post.PostContent       = viewModel.Content;
                            post.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            post.Topic_Id          = topic.Id;
                            post.IsTopicStarter    = true;



                            try
                            {
                                _topicServic.Add(topic);
                                _postSevice.Add(post);



                                unitOfWork.Commit();
                            }
                            catch (Exception ex)
                            {
                                LoggingService.Error(ex.Message);
                                unitOfWork.Rollback();
                            }
                        }
                        else
                        {
                            //viewModel.Category = null;
                            //No permission to create a Poll so show a message but create the topic
                            //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            //{
                            //    Message = LocalizationService.GetResourceString("Errors.NoPermissionCatergory"),
                            //    MessageType = GenericMessages.info
                            //};
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.CatergoryMessage"));
                        }
                    }
                    viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats);
                    return(View(viewModel));
                }
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
            }
        }
Пример #21
0
        private void saveCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            IUser user          = this.GetBinding <IUser>(BindingNames.User);
            var   userFormLogin = GetBinding <IUserFormLogin>(BindingNames.UserFormLogin);

            var userFormLoginFromDatabase = user.GetUserFormLogin();

            bool userValidated = true;

            ValidationResults validationResults = ValidationFacade.Validate(user);

            foreach (ValidationResult result in validationResults)
            {
                this.ShowFieldMessage($"{BindingNames.User}.{result.Key}", result.Message);
                userValidated = false;
            }


            List <CultureInfo> newActiveLocales     = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList();
            List <CultureInfo> currentActiveLocales = UserSettings.GetActiveLocaleCultureInfos(user.Username, false).ToList();

            string selectedActiveLocaleName = this.GetBinding <string>("ActiveLocaleName");

            CultureInfo selectedActiveLocale = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName);

            string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken);

            List <Guid>   newUserGroupIds            = UserGroupsFormsHelper.GetSelectedUserGroupIds(this.Bindings);
            List <string> newSerializedEnitityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList();


            if (string.Compare(user.Username, UserSettings.Username, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                // Current user shouldn't be able to lock itself
                if (userFormLogin.IsLocked)
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_LockingOwnUserAccount);

                    userValidated = false;
                }

                // Current user shouldn't be able to remove its own access to "System" perspective
                var groupsWithAccessToSystemPerspective = new HashSet <Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken));

                if (!newSerializedEnitityTokens.Contains(systemPerspectiveEntityToken) &&
                    !newUserGroupIds.Any(groupsWithAccessToSystemPerspective.Contains))
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_EditOwnAccessToSystemPerspective);

                    userValidated = false;
                }
            }

            string newPassword = this.GetBinding <string>(BindingNames.NewPassword);

            if (newPassword == NotPassword || UserFormLoginManager.ValidatePassword(userFormLoginFromDatabase, newPassword))
            {
                newPassword = null;
            }
            else
            {
                IList <string> validationMessages;
                if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out validationMessages))
                {
                    foreach (var message in validationMessages)
                    {
                        this.ShowFieldMessage(BindingNames.NewPassword, message);
                    }

                    userValidated = false;
                }
            }

            if (!userValidated)
            {
                return;
            }

            if (!userFormLogin.IsLocked)
            {
                userFormLogin.LockoutReason = (int)UserLockoutReason.Undefined;
            }
            else
            {
                bool wasLockedBefore = userFormLoginFromDatabase.IsLocked;

                if (!wasLockedBefore)
                {
                    userFormLoginFromDatabase.LockoutReason = (int)UserLockoutReason.LockedByAdministrator;
                }
            }

            UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken);

            bool reloadUsersConsoles = false;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                DataFacade.Update(user);

                userFormLoginFromDatabase.Folder   = userFormLogin.Folder;
                userFormLoginFromDatabase.IsLocked = userFormLogin.IsLocked;
                DataFacade.Update(userFormLoginFromDatabase);

                if (newPassword != null)
                {
                    UserFormLoginManager.SetPassword(userFormLoginFromDatabase, newPassword);
                }

                string cultureName             = this.GetBinding <string>("CultureName");
                string c1ConsoleUiLanguageName = this.GetBinding <string>("C1ConsoleUiLanguageName");

                UserSettings.SetUserCultureInfo(user.Username, CultureInfo.CreateSpecificCulture(cultureName));
                UserSettings.SetUserC1ConsoleUiLanguage(user.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName));

                List <string> existingSerializedEntityTokens = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList();

                int intersectCount = existingSerializedEntityTokens.Intersect(newSerializedEnitityTokens).Count();
                if ((intersectCount != newSerializedEnitityTokens.Count) ||
                    (intersectCount != existingSerializedEntityTokens.Count))
                {
                    UserPerspectiveFacade.SetSerializedEntityTokens(user.Username, newSerializedEnitityTokens);

                    if (UserSettings.Username == user.Username)
                    {
                        reloadUsersConsoles = true;
                    }
                }

                if (DataLocalizationFacade.ActiveLocalizationCultures.Any())
                {
                    foreach (CultureInfo cultureInfo in newActiveLocales)
                    {
                        if (!currentActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.AddActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    foreach (CultureInfo cultureInfo in currentActiveLocales)
                    {
                        if (!newActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.RemoveActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    if (selectedActiveLocale != null)
                    {
                        if (!selectedActiveLocale.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username)))
                        {
                            reloadUsersConsoles = true;
                        }

                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, selectedActiveLocale);
                    }
                    else if (UserSettings.GetActiveLocaleCultureInfos(user.Username).Any())
                    {
                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, UserSettings.GetActiveLocaleCultureInfos(user.Username).First());
                    }
                }


                List <IUserUserGroupRelation> oldRelations = DataFacade.GetData <IUserUserGroupRelation>(f => f.UserId == user.Id).ToList();

                IEnumerable <IUserUserGroupRelation> deleteRelations =
                    from r in oldRelations
                    where !newUserGroupIds.Contains(r.UserGroupId)
                    select r;

                DataFacade.Delete(deleteRelations);


                foreach (Guid newUserGroupId in newUserGroupIds)
                {
                    Guid groupId = newUserGroupId;
                    if (oldRelations.Any(f => f.UserGroupId == groupId))
                    {
                        continue;
                    }

                    var userUserGroupRelation = DataFacade.BuildNew <IUserUserGroupRelation>();
                    userUserGroupRelation.UserId      = user.Id;
                    userUserGroupRelation.UserGroupId = newUserGroupId;

                    DataFacade.AddNew(userUserGroupRelation);
                }

                LoggingService.LogEntry("UserManagement",
                                        $"C1 Console user '{user.Username}' updated by '{UserValidationFacade.GetUsername()}'.",
                                        LoggingService.Category.Audit,
                                        TraceEventType.Information);

                transactionScope.Complete();
            }

            if (UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username) == null)
            {
                this.ShowFieldMessage(BindingNames.ActiveContentLanguage, "The user doesn't have permissions to access the language you selected here. Assign permissions so the user may access this.");
                this.ShowMessage(DialogType.Warning, "User missing permissions for language", "The user doesn't have permissions to access the language you selected as 'Active content language'.");
            }
            else
            {
                if (reloadUsersConsoles)
                {
                    foreach (string consoleId in GetConsoleIdsOpenedByUser(user.Username))
                    {
                        ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), consoleId);
                    }
                }
            }

            SetSaveStatus(true);
            updateTreeRefresher.PostRefreshMesseges(user.GetDataEntityToken());
        }
Пример #22
0
 public void LogMessage(string messageFormat, params object[] args)
 {
     LoggingService.LogInfo(messageFormat, args);
 }
Пример #23
0
        public ActionResult Create(CreateTopicViewModel topicViewModel)
        {
            if (ModelState.IsValid)
            {
                // Quick check to see if user is locked out, when logged in
                if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")));
                }

                var      successfullyCreated = false;
                var      moderate            = false;
                Category category;
                var      topic = new Topic();

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Not using automapper for this one only, as a topic is a post and topic in one
                    category = _categoryService.Get(topicViewModel.Category);

                    // First check this user is allowed to create topics in this category
                    var permissions = RoleService.GetPermissions(category, UsersRole);

                    // Check this users role has permission to create a post
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked)
                    {
                        // Throw exception so Ajax caller picks it up
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.NoPermission"));
                    }
                    else
                    {
                        // We get the banned words here and pass them in, so its just one call
                        // instead of calling it several times and each call getting all the words back
                        var           bannedWordsList = _bannedWordService.GetAll();
                        List <string> bannedWords     = null;
                        if (bannedWordsList.Any())
                        {
                            bannedWords = bannedWordsList.Select(x => x.Word).ToList();
                        }

                        topic = new Topic
                        {
                            Name     = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User     = LoggedOnUser
                        };

                        // See if the user has actually added some content to the topic
                        if (!string.IsNullOrEmpty(topicViewModel.Content))
                        {
                            // Check for any banned words
                            topicViewModel.Content = _bannedWordService.SanitiseBannedWords(topicViewModel.Content, bannedWords);

                            // See if this is a poll and add it to the topic
                            if (topicViewModel.PollAnswers != null && topicViewModel.PollAnswers.Count > 0)
                            {
                                // Do they have permission to create a new poll
                                if (permissions[AppConstants.PermissionCreatePolls].IsTicked)
                                {
                                    // Create a new Poll
                                    var newPoll = new Poll
                                    {
                                        User = LoggedOnUser
                                    };

                                    // Create the poll
                                    _pollService.Add(newPoll);

                                    // Save the poll in the context so we can add answers
                                    unitOfWork.SaveChanges();

                                    // Now sort the answers
                                    var newPollAnswers = new List <PollAnswer>();
                                    foreach (var pollAnswer in topicViewModel.PollAnswers)
                                    {
                                        // Attach newly created poll to each answer
                                        pollAnswer.Poll = newPoll;
                                        _pollAnswerService.Add(pollAnswer);
                                        newPollAnswers.Add(pollAnswer);
                                    }
                                    // Attach answers to poll
                                    newPoll.PollAnswers = newPollAnswers;

                                    // Save the new answers in the context
                                    unitOfWork.SaveChanges();

                                    // Add the poll to the topic
                                    topic.Poll = newPoll;
                                }
                                else
                                {
                                    //No permission to create a Poll so show a message but create the topic
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = LocalizationService.GetResourceString("Errors.NoPermissionPolls"),
                                        MessageType = GenericMessages.info
                                    };
                                }
                            }

                            // Update the users points score for posting
                            _membershipUserPointsService.Add(new MembershipUserPoints
                            {
                                Points = SettingsService.GetSettings().PointsAddedPerPost,
                                User   = LoggedOnUser
                            });

                            // Check for moderation
                            if (category.ModerateTopics == true)
                            {
                                topic.Pending = true;
                                moderate      = true;
                            }

                            // Create the topic
                            topic = _topicService.Add(topic);

                            // Save the changes
                            unitOfWork.SaveChanges();

                            // Now create and add the post to the topic
                            _topicService.AddLastPost(topic, topicViewModel.Content);

                            // Now check its not spam
                            var akismetHelper = new AkismetHelper(SettingsService);
                            if (!akismetHelper.IsSpam(topic))
                            {
                                // Add the tags if any too
                                if (!string.IsNullOrEmpty(topicViewModel.Tags))
                                {
                                    // Sanitise the tags
                                    topicViewModel.Tags = _bannedWordService.SanitiseBannedWords(topicViewModel.Tags, bannedWords);

                                    // Now add the tags
                                    _topicTagService.Add(topicViewModel.Tags.ToLower(), topic);
                                }

                                // Subscribe the user to the topic as they have checked the checkbox
                                if (topicViewModel.SubscribeToTopic)
                                {
                                    // Create the notification
                                    var topicNotification = new TopicNotification
                                    {
                                        Topic = topic,
                                        User  = LoggedOnUser
                                    };
                                    //save
                                    _topicNotificationService.Add(topicNotification);
                                }

                                try
                                {
                                    unitOfWork.Commit();
                                    if (!moderate)
                                    {
                                        successfullyCreated = true;
                                    }


                                    // Successful, add this post to the Lucene index
                                    if (_luceneService.CheckIndexExists())
                                    {
                                        _luceneService.AddUpdate(_luceneService.MapToModel(topic));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    unitOfWork.Rollback();
                                    LoggingService.Error(ex);
                                    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                                }
                            }
                            else
                            {
                                unitOfWork.Rollback();
                                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.PossibleSpam"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        }
                    }
                }

                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    if (successfullyCreated)
                    {
                        // Success so now send the emails
                        NotifyNewTopics(category);

                        // Redirect to the newly created topic
                        return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl)));
                    }
                    if (moderate)
                    {
                        // Moderation needed
                        // Tell the user the topic is awaiting moderation
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                            MessageType = GenericMessages.info
                        };

                        return(RedirectToAction("Index", "Home"));
                    }

                    var allowedCategories = _categoryService.GetAllowedCategories(UsersRole).ToList();
                    if (allowedCategories.Any())
                    {
                        topicViewModel.Categories = allowedCategories;
                    }
                }
                return(View(topicViewModel));
            }

            return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
        }
Пример #24
0
 static void Debug(string text)
 {
     LoggingService.Debug(text);
 }
        public TaskInfo CreateTaskInfo(
            string typeName, string assemblyName, ExpressionNode assemblyFile, string assemblyFileStr,
            string declaredInFile, int declaredAtOffset,
            IMSBuildEvaluationContext evaluationContext)
        {
            //ignore this, it's redundant
            if (assemblyName != null && assemblyName.StartsWith("Microsoft.Build.Tasks.v", StringComparison.Ordinal))
            {
                return(null);
            }

            var             tasks    = GetTaskAssembly(assemblyName, assemblyFile, assemblyFileStr, declaredInFile, evaluationContext);
            IAssemblySymbol assembly = tasks?.assembly;

            if (assembly == null)
            {
                //TODO log this?
                return(null);
            }

            string asmShortName;

            if (string.IsNullOrEmpty(assemblyName))
            {
                asmShortName = Path.GetFileNameWithoutExtension(tasks.Value.path);
            }
            else
            {
                asmShortName = new AssemblyName(assemblyName).Name;
            }

            INamedTypeSymbol FindType(INamespaceSymbol ns, string name)
            {
                foreach (var m in ns.GetMembers())
                {
                    switch (m)
                    {
                    case INamedTypeSymbol ts:
                        if (ts.Name == name)
                        {
                            return(ts);
                        }
                        continue;

                    case INamespaceSymbol childNs:
                        var found = FindType(childNs, name);
                        if (found != null)
                        {
                            return(found);
                        }
                        continue;
                    }
                }
                return(null);
            }

            var type = assembly.GetTypeByMetadataName(typeName) ?? FindType(assembly.GlobalNamespace, typeName);

            if (type == null)
            {
                switch (typeName)
                {
                case "Microsoft.Build.Tasks.RequiresFramework35SP1Assembly":
                case "Microsoft.Build.Tasks.ResolveNativeReference":
                    //we don't care about these, they're not present on Mac and they're just noise
                    return(null);
                }
                LoggingService.LogWarning($"Did not resolve {typeName}");
                return(null);
            }

            var ti = new TaskInfo(
                type.Name, RoslynHelpers.GetDescription(type), type.GetFullName(),
                assemblyName, assemblyFileStr, declaredInFile, declaredAtOffset);

            PopulateTaskInfoFromType(ti, type);
            return(ti);
        }
Пример #26
0
        static void RunAsyncLoadTest()
        {
            while (true)
            {
                LoadData ld;
                lock (loadQueue) {
                    if (loadQueue.Count == 0)
                    {
                        if (!Monitor.Wait(loadQueue, 5000, true))
                        {
                            loaderRunning = false;
                            return;
                        }
                    }
                    ld = (LoadData)loadQueue.Dequeue();
                }

                try {
                    // If the information is cached in a file and it is up to date information,
                    // there is no need to parse again the assembly.

                    if (ld.TestInfoCachePath != null && File.Exists(ld.TestInfoCachePath))
                    {
                        ld.InfoCache = TestInfoCache.Read(ld.TestInfoCachePath);
                        NunitTestInfo info = ld.InfoCache.GetInfo(ld.Path);
                        if (info != null)
                        {
                            ld.Info = info;
                            ld.Callback(ld);
                            continue;
                        }
                    }
                } catch (Exception ex) {
                    LoggingService.LogError(ex.ToString());
                }

                ExternalTestRunner runner = null;

                try {
                    if (File.Exists(ld.Path))
                    {
                        runner  = (ExternalTestRunner)Runtime.ProcessService.CreateExternalProcessObject(typeof(ExternalTestRunner), false);
                        ld.Info = runner.GetTestInfo(ld.Path, ld.SupportAssemblies);
                    }
                } catch (Exception ex) {
                    Console.WriteLine(ex);
                    ld.Error = ex;
                }
                finally {
                    try {
                        if (runner != null)
                        {
                            runner.Dispose();
                        }
                    } catch {}
                }

                try {
                    ld.Callback(ld);
                } catch {
                }
            }
        }
Пример #27
0
		protected virtual async Task<ICompletionDataList> HandleCodeCompletion (
			CodeCompletionContext completionContext, bool forced, CancellationToken token)
		{
			var buf = this.Editor;

			// completionChar may be a space even if the current char isn't, when ctrl-space is fired t
			var currentLocation = new DocumentLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
			char currentChar = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 1);
			char previousChar = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 2);

			LoggingService.LogDebug ("Attempting completion for state '{0}'x{1}, previousChar='{2}'," 
				+ " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
				tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);
			
			//closing tag completion
			if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
				return ClosingTagCompletion (buf, currentLocation);
			
			// Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
			//FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
			if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/') {
				buf.InsertAtCaret (">");
				return null;
			}
			
			//entity completion
			if (currentChar == '&' && (tracker.Engine.CurrentState is XmlRootState ||
			                           tracker.Engine.CurrentState is XmlAttributeValueState))
			{
				var list = new CompletionDataList ();
				
				//TODO: need to tweak semicolon insertion
				list.Add ("apos").Description = "'";
				list.Add ("quot").Description = "\"";
				list.Add ("lt").Description = "<";
				list.Add ("gt").Description = ">";
				list.Add ("amp").Description = "&";
				
				//not sure about these "completions". they're more like
				//shortcuts than completions but they're pretty useful
				list.Add ("'").CompletionText = "apos;";
				list.Add ("\"").CompletionText = "quot;";
				list.Add ("<").CompletionText = "lt;";
				list.Add (">").CompletionText = "gt;";
				list.Add ("&").CompletionText = "amp;";
				
				var ecList = await GetEntityCompletions (token);
				list.AddRange (ecList);
				return list;
			}
			
			//doctype completion
			if (tracker.Engine.CurrentState is XmlDocTypeState) {
				if (tracker.Engine.CurrentStateLength == 1) {
					CompletionDataList list = await GetDocTypeCompletions (token);
					if (list != null && list.Count > 0)
						return list;
				}
				return null;
			}

			//attribute value completion
			//determine whether to trigger completion within attribute values quotes
			if ((Tracker.Engine.CurrentState is XmlAttributeValueState)
			    //trigger on the opening quote
			    && ((Tracker.Engine.CurrentStateLength == 1 && (currentChar == '\'' || currentChar == '"'))
			    //or trigger on first letter of value, if unforced
			    || (forced || Tracker.Engine.CurrentStateLength == 2))) {
				var att = (XAttribute)Tracker.Engine.Nodes.Peek ();

				if (att.IsNamed) {
					var attributedOb = Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
					if (attributedOb == null)
						return null;

					//if triggered by first letter of value or forced, grab those letters

					var result = await GetAttributeValueCompletions (attributedOb, att, token);
					if (result != null) {
						result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
						return result;
					}
					return null;
				}
			}
			
			//attribute name completion
			if ((forced && Tracker.Engine.Nodes.Peek () is IAttributedXObject && !tracker.Engine.Nodes.Peek ().IsEnded)
			     || ((Tracker.Engine.CurrentState is XmlNameState
			    && Tracker.Engine.CurrentState.Parent is XmlAttributeState) ||
			    Tracker.Engine.CurrentState is XmlTagState)
			    && (Tracker.Engine.CurrentStateLength == 1 || forced)) {
				IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek () as IAttributedXObject) ?? 
					Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
				if (attributedOb == null)
					return null;
				
				//attributes
				if (attributedOb.Name.IsValid && (forced ||
					(char.IsWhiteSpace (previousChar) && char.IsLetter (currentChar))))
				{
					var existingAtts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
					
					foreach (XAttribute att in attributedOb.Attributes) {
						existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
					}
					var result = await GetAttributeCompletions (attributedOb, existingAtts, token);
					if (result != null) {
						if (!forced)
							result.TriggerWordLength = 1;
						return result;
					}
					return null;
				}
			}
			
//			if (Tracker.Engine.CurrentState is XmlRootState) {
//				if (line < 3) {
//				cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
//			}

			//element completion
			if (currentChar == '<' && tracker.Engine.CurrentState is XmlRootState ||
				(tracker.Engine.CurrentState is XmlNameState && forced)) {
				var list = await GetElementCompletions (token);
				AddCloseTag (list, Tracker.Engine.Nodes);
				return list.Count > 0 ? list : null;
			}

			if (forced && Tracker.Engine.CurrentState is XmlRootState) {
				var list = new CompletionDataList ();
				MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (DocumentContext.Name, list);
				return list.Count > 0? list : null;
			}
			
			return null;
		}
Пример #28
0
 public OPCSigner(X509Certificate2 certificate, LoggingService log)
 {
     Certificate = certificate;
     _log = log;
 }
Пример #29
0
        public CommitDialog(ChangeSet changeSet)
        {
            Build();

            store                 = new ListStore(typeof(Xwt.Drawing.Image), typeof(string), typeof(string), typeof(bool), typeof(object));
            fileList.Model        = store;
            fileList.SearchColumn = -1;             // disable the interactive search
            this.changeSet        = changeSet;
            oldMessage            = changeSet.GlobalComment;

            CellRendererText crt     = new CellRendererText();
            var            crp       = new CellRendererImage();
            TreeViewColumn colStatus = new TreeViewColumn();

            colStatus.Title = GettextCatalog.GetString("Status");
            colStatus.PackStart(crp, false);
            colStatus.PackStart(crt, true);
            colStatus.Spacing = 2;
            colStatus.AddAttribute(crp, "image", 0);
            colStatus.AddAttribute(crt, "text", 1);
            CellRendererToggle cellToggle = new CellRendererToggle();

            cellToggle.Toggled += new ToggledHandler(OnCommitToggledHandler);
            TreeViewColumn colCommit = new TreeViewColumn("", cellToggle, "active", 3);
            TreeViewColumn colFile   = new TreeViewColumn(GettextCatalog.GetString("File"), new CellRendererText(), "text", 2);

            fileList.AppendColumn(colCommit);
            fileList.AppendColumn(colStatus);
            fileList.AppendColumn(colFile);

            colCommit.Visible = false;

            object[] exts = AddinManager.GetExtensionObjects("/MonoDevelop/VersionControl/CommitDialogExtensions", false);
            bool     separatorRequired = false;

            foreach (object ob in exts)
            {
                CommitDialogExtension ext = ob as CommitDialogExtension;
                if (ext == null)
                {
                    LoggingService.LogError("Commit extension type " + ob.GetType() + " must be a subclass of CommitDialogExtension");
                    continue;
                }
                if (ext.Initialize(changeSet))
                {
                    ext.CommitDialog = this;
                    var newTitle = ext.FormatDialogTitle(changeSet, Title);
                    if (newTitle != null)
                    {
                        Title = newTitle;
                    }

                    ext.CommitMessageTextViewHook(textview);
                    if (separatorRequired)
                    {
                        HSeparator sep = new HSeparator();
                        sep.Show();
                        vboxExtensions.PackEnd(sep, false, false, 0);
                    }
                    vboxExtensions.PackEnd(ext, false, false, 0);
                    extensions.Add(ext);
                    ext.AllowCommitChanged += HandleAllowCommitChanged;
                    separatorRequired       = true;
                }
                else
                {
                    ext.Destroy();
                }
            }
            HandleAllowCommitChanged(null, null);

            LoadChangeset(changeSet.Items);

            if (string.IsNullOrEmpty(changeSet.GlobalComment))
            {
                AuthorInformation   aInfo;
                CommitMessageFormat fmt = VersionControlService.GetCommitMessageFormat(changeSet, out aInfo);
                Message = changeSet.GenerateGlobalComment(fmt, aInfo);
            }
            else
            {
                Message = changeSet.GlobalComment;
            }

            textview.Buffer.Changed += OnTextChanged;
            responseSensitive        = !string.IsNullOrEmpty(Message);

            // Focus the text view and move the insert point to the beginning. Makes it easier to insert
            // a comment header.
            textview.Buffer.MoveMark(textview.Buffer.InsertMark, textview.Buffer.StartIter);
            textview.Buffer.MoveMark(textview.Buffer.SelectionBound, textview.Buffer.StartIter);
            textview.GrabFocus();
            textview.Buffer.MarkSet += OnMarkSet;

            SetResponseSensitive(ResponseType.Ok, responseSensitive);

            VersionControlService.FileStatusChanged += OnFileStatusChanged;
        }
Пример #30
0
		int Run (MonoDevelopOptions options)
		{
			LoggingService.LogInfo ("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
			LoggingService.LogInfo ("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation ());
			LoggingService.LogInfo ("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo ());

			//ensure native libs initialized before we hit anything that p/invokes
			Platform.Initialize ();
			sectionTimings ["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			GettextCatalog.Initialize ();
			sectionTimings ["GettextInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			LoggingService.LogInfo ("Operating System: {0}", SystemInformation.GetOperatingSystemDescription ());

			if (!Platform.IsWindows) {
				// The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
				// Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
				// to be too late to prevent the MEF composition and the static registrar from
				// failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
				ResolveMSBuildAssemblies ();
			}

			Counters.Initialization.BeginTiming ();

			if (options.PerfLog) {
				string logFile = Path.Combine (Environment.CurrentDirectory, "monodevelop.perf-log");
				LoggingService.LogInfo ("Logging instrumentation service data to file: " + logFile);
				InstrumentationService.StartAutoSave (logFile, 1000);
			}

			Counters.Initialization.Trace ("Initializing GTK");
			if (Platform.IsWindows && !CheckWindowsGtk ())
				return 1;
			SetupExceptionManager ();

			// explicit GLib type system initialization for GLib < 2.36 before any other type system access
			GLib.GType.Init ();

			IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer ();
			try {
				IdeApp.Customizer.Initialize ();
			} catch (UnauthorizedAccessException ua) {
				LoggingService.LogError ("Unauthorized access: " + ua.Message);
				return 1;
			}

			try {
				GLibLogging.Enabled = true;
			} catch (Exception ex) {
				LoggingService.LogError ("Error initialising GLib logging.", ex);
			}

			var args = options.RemainingArgs.ToArray ();
			IdeTheme.InitializeGtk (BrandingService.ApplicationName, ref args);

			sectionTimings["GtkInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();
			LoggingService.LogInfo ("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion ());

			// XWT initialization
			FilePath p = typeof(IdeStartup).Assembly.Location;
			Runtime.LoadAssemblyFrom (p.ParentDirectory.Combine("Xwt.Gtk.dll"));
			Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk);
			Xwt.Toolkit.CurrentEngine.RegisterBackend<IExtendedTitleBarWindowBackend,GtkExtendedTitleBarWindowBackend> ();
			Xwt.Toolkit.CurrentEngine.RegisterBackend<IExtendedTitleBarDialogBackend,GtkExtendedTitleBarDialogBackend> ();
			IdeTheme.SetupXwtTheme ();

			sectionTimings["XwtInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			//default to Windows IME on Windows
			if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16) {
				var settings = Gtk.Settings.Default;
				var val = GtkWorkarounds.GetProperty (settings, "gtk-im-module");
				if (string.IsNullOrEmpty (val.Val as string))
					GtkWorkarounds.SetProperty (settings, "gtk-im-module", new GLib.Value ("ime"));
			}
			
			string socket_filename = null;
			EndPoint ep = null;
			
			DispatchService.Initialize ();

			// Set a synchronization context for the main gtk thread
			SynchronizationContext.SetSynchronizationContext (DispatchService.SynchronizationContext);
			Runtime.MainSynchronizationContext = SynchronizationContext.Current;

			sectionTimings["DispatchInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			// Initialize Roslyn's synchronization context
			RoslynServices.RoslynService.Initialize ();

			sectionTimings["RoslynInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			AddinManager.AddinLoadError += OnAddinError;

			var startupInfo = new StartupInfo (args);

			// If a combine was specified, force --newwindow.

			if (!options.NewWindow && startupInfo.HasFiles) {
				Counters.Initialization.Trace ("Pre-Initializing Runtime to load files in existing window");
				Runtime.Initialize (true);
				foreach (var file in startupInfo.RequestedFileList) {
					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
						options.NewWindow = true;
						break;
					}
				}
			}
			
			Counters.Initialization.Trace ("Initializing Runtime");
			Runtime.Initialize (true);

			sectionTimings ["RuntimeInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			bool restartRequested = PropertyService.Get ("MonoDevelop.Core.RestartRequested", false);
			startupInfo.Restarted = restartRequested;
			PropertyService.Set ("MonoDevelop.Core.RestartRequested", false);

			IdeApp.Customizer.OnCoreInitialized ();

			Counters.Initialization.Trace ("Initializing theme");

			IdeTheme.SetupGtkTheme ();

			sectionTimings["ThemeInitialized"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor ();
			
			monitor.BeginTask (GettextCatalog.GetString ("Starting {0}", BrandingService.ApplicationName), 2);

			//make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
			Counters.Initialization.Trace ("Initializing Platform Service");
			DesktopService.Initialize ();

			sectionTimings["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			monitor.Step (1);

			if (options.IpcTcp) {
				listen_socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
				ep = new IPEndPoint (IPAddress.Loopback, ipcBasePort + HashSdbmBounded (Environment.UserName));
			} else {
				socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable ("USER") + "-socket";
				listen_socket = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
				ep = new UnixEndPoint (socket_filename);
			}
				
			// If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
			if (!options.NewWindow && startupInfo.HasFiles) {
				try {
					StringBuilder builder = new StringBuilder ();
					foreach (var file in startupInfo.RequestedFileList) {
						builder.AppendFormat ("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
					}
					listen_socket.Connect (ep);
					listen_socket.Send (Encoding.UTF8.GetBytes (builder.ToString ()));
					return 0;
				} catch {
					// Reset the socket
					if (null != socket_filename && File.Exists (socket_filename))
						File.Delete (socket_filename);
				}
			}
			
			Counters.Initialization.Trace ("Checking System");

			CheckFileWatcher ();

			sectionTimings["FileWatcherInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			Exception error = null;
			int reportedFailures = 0;

			try {
				Counters.Initialization.Trace ("Loading Icons");
				//force initialisation before the workbench so that it can register stock icons for GTK before they get requested
				ImageService.Initialize ();

				sectionTimings ["ImageInitialization"] = startupSectionTimer.ElapsedMilliseconds;
				startupSectionTimer.Restart ();

				// If we display an error dialog before the main workbench window on OS X then a second application menu is created
				// which is then replaced with a second empty Apple menu.
				// XBC #33699
				Counters.Initialization.Trace ("Initializing IdeApp");

				hideWelcomePage = startupInfo.HasFiles;
				IdeApp.Initialize (monitor, hideWelcomePage);
				sectionTimings ["AppInitialization"] = startupSectionTimer.ElapsedMilliseconds;
				startupSectionTimer.Restart ();

				if (errorsList.Count > 0) {
					using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog (errorsList.ToArray (), false)) {
						if (!dlg.Run ())
							return 1;
					}
					reportedFailures = errorsList.Count;
				}

				if (!CheckSCPlugin ())
					return 1;

				// Load requested files
				Counters.Initialization.Trace ("Opening Files");

				// load previous combine
				RecentFile openedProject = null;
				if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen) {
					openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
					if (openedProject != null) {
						var metadata = GetOpenWorkspaceOnStartupMetadata ();
						IdeApp.Workspace.OpenWorkspaceItem (openedProject.FileName, true, true, metadata).ContinueWith (t => IdeApp.OpenFiles (startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext ());
						startupInfo.OpenedRecentProject = true;
					}
				}
				if (openedProject == null) {
					IdeApp.OpenFiles (startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata ());
					startupInfo.OpenedFiles = startupInfo.HasFiles;
				}
				
				monitor.Step (1);
			
			} catch (Exception e) {
				error = e;
			} finally {
				monitor.Dispose ();
			}
			
			if (error != null) {
				string message = BrandingService.BrandApplicationName (GettextCatalog.GetString ("MonoDevelop failed to start"));
				message = message + "\n\n" + error.Message;
				MessageService.ShowFatalError (message, null, error);

				return 1;
			}

			if (errorsList.Count > reportedFailures) {
				using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog (errorsList.ToArray (), true))
					dlg.Run ();
			}
			
			errorsList = null;
			AddinManager.AddinLoadError -= OnAddinError;

			sectionTimings["BasicInitializationCompleted"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			// FIXME: we should probably track the last 'selected' one
			// and do this more cleanly
			try {
				listen_socket.Bind (ep);
				listen_socket.Listen (5);
				listen_socket.BeginAccept (new AsyncCallback (ListenCallback), listen_socket);
			} catch {
				// Socket already in use
			}

			sectionTimings["SocketInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			initialized = true;
			MessageService.RootWindow = IdeApp.Workbench.RootWindow;
			Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow (IdeApp.Workbench.RootWindow);

			sectionTimings["WindowOpened"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			Thread.CurrentThread.Name = "GUI Thread";
			Counters.Initialization.Trace ("Running IdeApp");
			Counters.Initialization.EndTiming ();
				
			AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
			StartLockupTracker ();

			// This call is important so the current event loop is run before we run the main loop.
			// On Mac, the OpenDocuments event gets handled here, so we need to get the timeout
			// it queues before the OnIdle event so we can start opening a solution before
			// we show the main window.
			DispatchService.RunPendingEvents ();

			sectionTimings ["PumpEventLoop"] = startupSectionTimer.ElapsedMilliseconds;
			startupTimer.Stop ();
			startupSectionTimer.Stop ();

			// Need to start this timer because we don't know yet if we've been asked to open a solution from the file manager.
			timeToCodeTimer.Start ();
			ttcMetadata = new TimeToCodeMetadata {
				StartupTime = startupTimer.ElapsedMilliseconds
			};

			// Start this timer to limit the time to decide if the app was opened by a file manager
			IdeApp.StartFMOpenTimer (FMOpenTimerExpired);
			IdeApp.Workspace.FirstWorkspaceItemOpened += CompleteSolutionTimeToCode;
			IdeApp.Workbench.DocumentOpened += CompleteFileTimeToCode;

			CreateStartupMetadata (startupInfo, sectionTimings);

			GLib.Idle.Add (OnIdle);
			IdeApp.Run ();

			IdeApp.Customizer.OnIdeShutdown ();
			
			// unloading services
			if (null != socket_filename)
				File.Delete (socket_filename);
			lockupCheckRunning = false;
			Runtime.Shutdown ();

			IdeApp.Customizer.OnCoreShutdown ();

			InstrumentationService.Stop ();

			MonoDevelop.Components.GtkWorkarounds.Terminate ();
			
			return 0;
		}
        private async void GetArtistImage(CancellationToken token)
        {
            var audio = AudioService.CurrentAudio;

            if (audio == null)
            {
                return;
            }

            if (audio.Artist == _lastArtist)
            {
                return;
            }

            _lastArtist = audio.Artist;
            string imageType = "big";

            try
            {
                var cachedImage = await CacheService.GetCachedImage("artists/" + CacheService.GetSafeFileName(audio.Artist + "_" + imageType + ".jpg"));

                if (cachedImage != null)
                {
                    var lastUpdateTime = FileStorage.GetFileUpdateTime("artists/" + CacheService.GetSafeFileName(audio.Artist + "_" + imageType + ".jpg"));
                    if ((DateTime.Now - lastUpdateTime).TotalDays < 14)
                    {
                        //if image was downloaded less than 2 weeks ago, show it, else download newer
                        ArtistImage = cachedImage;
                        return;
                    }
                }

                if (Settings.Instance.DownloadArtistArt)
                {
                    var imageUri = await DataService.GetArtistImage(audio.Artist, true);

                    if (imageUri != null)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        cachedImage = await CacheService.CacheImage(imageUri.OriginalString, "artists/" + CacheService.GetSafeFileName(audio.Artist + "_" + imageType + ".jpg"));

                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        ArtistImage = cachedImage;
                        return;
                    }
                }

                ArtistImage = null;
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }
 public GcLogCmdlet()
 {
     Service = new LoggingService(GetBaseClientServiceInitializer());
 }
Пример #33
0
 internal SvnClientException(SvnException ex) : base(ex.Message, ex)
 {
     this.errorCode = ex.SvnErrorCode;
     LoggingService.Debug(ex);
 }
Пример #34
0
        internal UnitTestResult RunUnitTest(UnitTest test, string suiteName, string pathName, string testName, TestContext testContext)
        {
            var runnerExe = GetCustomConsoleRunnerCommand();

            if (runnerExe != null)
            {
                return(RunWithConsoleRunner(runnerExe, test, suiteName, pathName, testName, testContext));
            }

            ExternalTestRunner runner       = (ExternalTestRunner)Runtime.ProcessService.CreateExternalProcessObject(typeof(ExternalTestRunner), testContext.ExecutionContext, UserAssemblyPaths);
            LocalTestMonitor   localMonitor = new LocalTestMonitor(testContext, test, suiteName, testName != null);

            ITestFilter filter = null;

            if (test != null)
            {
                if (test is UnitTestGroup)
                {
                    filter = new TestNameFilter(CollectTests((UnitTestGroup)test));
                }
                else
                {
                    filter = new TestNameFilter(test.TestId);
                }
            }
            else
            {
                NUnitCategoryOptions categoryOptions = (NUnitCategoryOptions)test.GetOptions(typeof(NUnitCategoryOptions));
                if (categoryOptions.EnableFilter && categoryOptions.Categories.Count > 0)
                {
                    string[] cats = new string [categoryOptions.Categories.Count];
                    categoryOptions.Categories.CopyTo(cats, 0);
                    filter = new CategoryFilter(cats);
                    if (categoryOptions.Exclude)
                    {
                        filter = new NotFilter(filter);
                    }
                }
            }

            RunData rd = new RunData();

            rd.Runner       = runner;
            rd.Test         = this;
            rd.LocalMonitor = localMonitor;
            testContext.Monitor.CancelRequested += new TestHandler(rd.Cancel);

            UnitTestResult result;

            try {
                if (string.IsNullOrEmpty(AssemblyPath))
                {
                    string msg = GettextCatalog.GetString("Could not get a valid path to the assembly. There may be a conflict in the project configurations.");
                    throw new Exception(msg);
                }
                System.Runtime.Remoting.RemotingServices.Marshal(localMonitor, null, typeof(IRemoteEventListener));

                string testRunnerAssembly, testRunnerType;
                GetCustomTestRunner(out testRunnerAssembly, out testRunnerType);

                result = runner.Run(localMonitor, filter, AssemblyPath, "", new List <string> (SupportAssemblies), testRunnerType, testRunnerAssembly);
                if (testName != null)
                {
                    result = localMonitor.SingleTestResult;
                }
            } catch (Exception ex) {
                if (!localMonitor.Canceled)
                {
                    LoggingService.LogError(ex.ToString());
                    if (localMonitor.RunningTest != null)
                    {
                        RuntimeErrorCleanup(testContext, localMonitor.RunningTest, ex);
                    }
                    else
                    {
                        testContext.Monitor.ReportRuntimeError(null, ex);
                        throw;
                    }
                    result = UnitTestResult.CreateFailure(ex);
                }
                else
                {
                    result = UnitTestResult.CreateFailure(GettextCatalog.GetString("Canceled"), null);
                }
            } finally {
                testContext.Monitor.CancelRequested -= new TestHandler(rd.Cancel);
                runner.Dispose();
                System.Runtime.Remoting.RemotingServices.Disconnect(localMonitor);
            }

            return(result);
        }
Пример #35
0
 public WidgetService(IAtomicCmsDataRepository dataContext, LoggingService log)
 {
     _dataContext = dataContext;
     _log = log;
 }
Пример #36
0
        protected virtual ICompletionDataList HandleCodeCompletion(
            CodeCompletionContext completionContext, bool forced, ref int triggerWordLength)
        {
            IEditableTextBuffer buf = this.EditableBuffer;

            // completionChar may be a space even if the current char isn't, when ctrl-space is fired t
            DomLocation currentLocation = new DomLocation(completionContext.TriggerLine, completionContext.TriggerLineOffset);
            char        currentChar     = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt(completionContext.TriggerOffset - 1);
            char        previousChar    = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt(completionContext.TriggerOffset - 2);

            LoggingService.LogDebug("Attempting completion for state '{0}'x{1}, previousChar='{2}',"
                                    + " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
                                    tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);

            //closing tag completion
            if (tracker.Engine.CurrentState is XmlFreeState && currentChar == '>')
            {
                //get name of current node in document that's being ended
                XElement el = tracker.Engine.Nodes.Peek() as XElement;
                if (el != null && el.Region.End >= currentLocation && !el.IsClosed && el.IsNamed)
                {
                    string tag = String.Concat("</", el.Name.FullName, ">");
                    if (XmlEditorOptions.AutoCompleteElements)
                    {
                        buf.BeginAtomicUndo();
                        buf.InsertText(buf.CursorPosition, tag);
                        buf.CursorPosition -= tag.Length;
                        buf.EndAtomicUndo();
                        return(null);
                    }
                    else
                    {
                        CompletionDataList cp = new CompletionDataList();
                        cp.Add(new XmlTagCompletionData(tag, 0, true));
                        return(cp);
                    }
                }
                return(null);
            }

            // Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
            //FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
            if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/')
            {
                buf.BeginAtomicUndo();
                buf.InsertText(buf.CursorPosition, ">");
                buf.EndAtomicUndo();
                return(null);
            }

            //element completion
            if (currentChar == '<' && tracker.Engine.CurrentState is XmlFreeState)
            {
                CompletionDataList list = new CompletionDataList();
                GetElementCompletions(list);
                AddCloseTag(list, Tracker.Engine.Nodes);
                return(list.Count > 0? list : null);
            }

            //entity completion
            if (currentChar == '&' && (tracker.Engine.CurrentState is XmlFreeState ||
                                       tracker.Engine.CurrentState is XmlAttributeValueState))
            {
                CompletionDataList list = new CompletionDataList();

                //TODO: need to tweak semicolon insertion
                list.Add("apos").Description = "'";
                list.Add("quot").Description = "\"";
                list.Add("lt").Description   = "<";
                list.Add("gt").Description   = ">";
                list.Add("amp").Description  = "&";

                //not sure about these "completions". they're more like
                //shortcuts than completions but they're pretty useful
                list.Add("'").CompletionText  = "apos;";
                list.Add("\"").CompletionText = "quot;";
                list.Add("<").CompletionText  = "lt;";
                list.Add(">").CompletionText  = "gt;";
                list.Add("&").CompletionText  = "amp;";

                GetEntityCompletions(list);
                return(list);
            }

            //doctype completion
            if (tracker.Engine.CurrentState is XmlDocTypeState)
            {
                if (tracker.Engine.CurrentStateLength == 1)
                {
                    CompletionDataList list = GetDocTypeCompletions();
                    if (list != null && list.Count > 0)
                    {
                        return(list);
                    }
                }
                return(null);
            }

            //attribute name completion
            if ((forced && Tracker.Engine.Nodes.Peek() is IAttributedXObject && !tracker.Engine.Nodes.Peek().IsEnded) ||
                (Tracker.Engine.CurrentState is XmlNameState &&
                 Tracker.Engine.CurrentState.Parent is XmlAttributeState &&
                 Tracker.Engine.CurrentStateLength == 1)
                )
            {
                IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek() as IAttributedXObject) ??
                                                  Tracker.Engine.Nodes.Peek(1) as IAttributedXObject;
                if (attributedOb == null)
                {
                    return(null);
                }

                //attributes
                if (attributedOb.Name.IsValid && (forced ||
                                                  (char.IsWhiteSpace(previousChar) && char.IsLetter(currentChar))))
                {
                    if (!forced)
                    {
                        triggerWordLength = 1;
                    }

                    var existingAtts = new Dictionary <string, string> (StringComparer.OrdinalIgnoreCase);

                    foreach (XAttribute att in attributedOb.Attributes)
                    {
                        existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
                    }

                    return(GetAttributeCompletions(attributedOb, existingAtts));
                }
            }

            //attribute value completion
            //determine whether to trigger completion within attribute values quotes
            if ((Tracker.Engine.CurrentState is XmlDoubleQuotedAttributeValueState ||
                 Tracker.Engine.CurrentState is XmlSingleQuotedAttributeValueState)
                //trigger on the opening quote
                && (Tracker.Engine.CurrentStateLength == 0
                    //or trigger on first letter of value, if unforced
                    || (!forced && Tracker.Engine.CurrentStateLength == 1))
                )
            {
                XAttribute att = (XAttribute)Tracker.Engine.Nodes.Peek();

                if (att.IsNamed)
                {
                    IAttributedXObject attributedOb = Tracker.Engine.Nodes.Peek(1) as IAttributedXObject;
                    if (attributedOb == null)
                    {
                        return(null);
                    }

                    char next = ' ';
                    if (completionContext.TriggerOffset < buf.Length)
                    {
                        next = buf.GetCharAt(completionContext.TriggerOffset);
                    }

                    char compareChar = (Tracker.Engine.CurrentStateLength == 0)? currentChar : previousChar;

                    if ((compareChar == '"' || compareChar == '\'') &&
                        (next == compareChar || char.IsWhiteSpace(next))
                        )
                    {
                        //if triggered by first letter of value, grab that letter
                        if (Tracker.Engine.CurrentStateLength == 1)
                        {
                            triggerWordLength = 1;
                        }

                        return(GetAttributeValueCompletions(attributedOb, att));
                    }
                }
            }

//			if (Tracker.Engine.CurrentState is XmlFreeState) {
//				if (line < 3) {
//				cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
//			}

            if (forced && Tracker.Engine.CurrentState is XmlFreeState)
            {
                CompletionDataList list = new CompletionDataList();
                MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName(Document.Name, list);
                return(list.Count > 0? list : null);
            }

            return(null);
        }
Пример #37
0
 public ToolsController(PageService pageService, SettingService settingService, LoggingService log)
 {
     this.pageService = pageService;
     this.settingService = settingService;
     this.log = log;
 }
Пример #38
0
 public static void ShowMessage(string message, string caption)
 {
     LoggingService.Info(message);
     ServiceManager.MessageService.ShowMessage(message, caption);
 }
 /// <summary>
 /// Gets all possible monitored resource descriptors.
 /// </summary>
 private static List<MonitoredResourceDescriptor> GetResourceDescriptors()
 {
     List<MonitoredResourceDescriptor> monitoredResourceDescriptors = new List<MonitoredResourceDescriptor>();
     LoggingService service = new LoggingService(GetBaseClientServiceInitializer());
     MonitoredResourceDescriptorsResource.ListRequest request = service.MonitoredResourceDescriptors.List();
     do
     {
         ListMonitoredResourceDescriptorsResponse response = request.Execute();
         if (response.ResourceDescriptors != null)
         {
             monitoredResourceDescriptors.AddRange(response.ResourceDescriptors);
         }
         request.PageToken = response.NextPageToken;
     }
     while (request.PageToken != null);
     return monitoredResourceDescriptors;
 }
Пример #40
0
 /// <summary>
 /// Shows a warning message.
 /// </summary>
 public static void ShowWarning(string message)
 {
     LoggingService.Warn(message);
     ServiceManager.MessageService.ShowWarning(message);
 }
Пример #41
0
        void GlobalSetup()
        {
            //FIXME: should we remove these when finalizing?
            try {
                ApplicationEvents.Quit += delegate(object sender, ApplicationQuitEventArgs e)
                {
                    // We can only attempt to quit safely if all windows are GTK windows and not modal
                    if (!IsModalDialogRunning())
                    {
                        e.UserCancelled = !IdeApp.Exit();
                        e.Handled       = true;
                        return;
                    }

                    // When a modal dialog is running, things are much harder. We can't just shut down MD behind the
                    // dialog, and aborting the dialog may not be appropriate.
                    //
                    // There's NSTerminateLater but I'm not sure how to access it from carbon, maybe
                    // we need to swizzle methods into the app's NSApplicationDelegate.
                    // Also, it stops the main CFRunLoop and enters a special runloop mode, not sure how that would
                    // interact with GTK+.

                    // For now, just bounce
                    NSApplication.SharedApplication.RequestUserAttention(NSRequestUserAttentionType.CriticalRequest);
                    // and abort the quit.
                    e.UserCancelled = true;
                    e.Handled       = true;
                };

                ApplicationEvents.Reopen += delegate(object sender, ApplicationEventArgs e) {
                    if (IdeApp.Workbench != null && IdeApp.Workbench.RootWindow != null)
                    {
                        IdeApp.Workbench.RootWindow.Deiconify();
                        IdeApp.Workbench.RootWindow.Visible = true;

                        IdeApp.Workbench.RootWindow.Present();
                        e.Handled = true;
                    }
                };

                ApplicationEvents.OpenDocuments += delegate(object sender, ApplicationDocumentEventArgs e) {
                    //OpenFiles may pump the mainloop, but can't do that from an AppleEvent, so use a brief timeout
                    GLib.Timeout.Add(10, delegate {
                        IdeApp.OpenFiles(e.Documents.Select(
                                             doc => new FileOpenInformation(doc.Key, null, doc.Value, 1, OpenDocumentOptions.DefaultInternal))
                                         );
                        return(false);
                    });
                    e.Handled = true;
                };

                ApplicationEvents.OpenUrls += delegate(object sender, ApplicationUrlEventArgs e) {
                    GLib.Timeout.Add(10, delegate {
                        // Open files via the monodevelop:// URI scheme, compatible with the
                        // common TextMate scheme: http://blog.macromates.com/2007/the-textmate-url-scheme/
                        IdeApp.OpenFiles(e.Urls.Select(url => {
                            try {
                                var uri = new Uri(url);
                                if (uri.Host != "open")
                                {
                                    return(null);
                                }

                                var qs      = System.Web.HttpUtility.ParseQueryString(uri.Query);
                                var fileUri = new Uri(qs ["file"]);

                                int line, column;
                                if (!Int32.TryParse(qs ["line"], out line))
                                {
                                    line = 1;
                                }
                                if (!Int32.TryParse(qs ["column"], out column))
                                {
                                    column = 1;
                                }

                                return(new FileOpenInformation(Uri.UnescapeDataString(fileUri.AbsolutePath), null,
                                                               line, column, OpenDocumentOptions.DefaultInternal));
                            } catch (Exception ex) {
                                LoggingService.LogError("Invalid TextMate URI: " + url, ex);
                                return(null);
                            }
                        }).Where(foi => foi != null));
                        return(false);
                    });
                };

                //if not running inside an app bundle (at dev time), need to do some additional setup
                if (NSBundle.MainBundle.InfoDictionary ["CFBundleIdentifier"] == null)
                {
                    SetupWithoutBundle();
                }
                else
                {
                    SetupDockIcon();
                }
            } catch (Exception ex) {
                LoggingService.LogError("Could not install app event handlers", ex);
                setupFail = true;
            }
        }
Пример #42
0
        public async Task RefreshHistoryDataFromCache(string grouping)
        {
            try
            {
                //await Task.Run(() =>
                //{
                //await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                //{

                LoggingService.LogInformation("RefreshDataFromCache'", "YouTubeService.RefreshDataFromCache");

                var foundPlaying = StandardFeedResults.Where(x => !string.IsNullOrEmpty(x.UIStateFull));


                if (foundPlaying != null & foundPlaying.Count() > 0)
                {
                    //StandardFeedResults.ToList().RemoveAll(x => x != foundPlaying.First());
                    var    tempUIDs = StandardFeedResults.Where(x => string.IsNullOrEmpty(x.UIStateFull)).Select(x => x.Uid).ToArray();
                    string foundUID = foundPlaying.First().Uid;
                    for (int i = 0; i < tempUIDs.Count(); i++)
                    {
                        //if (tempUIDs[i] != foundUID)
                        StandardFeedResults.Remove(StandardFeedResults.Where(x => x.Uid == tempUIDs[i] && string.IsNullOrEmpty(x.UIStateFull)).First());
                    }
                }
                else
                {
                    StandardFeedResults.Clear();
                }


                var found = AppDatabase.Current.RetrieveYoutubeHistoryItemByGrouping(grouping);
                if (found != null && found.Count > 0)
                {
                    //StandardFeedResults.ToList().RemoveAll(x => x._Grouping == grouping);
                    found.Reverse();

                    foreach (var item in found)
                    {
                        var ytdi = new YoutubeDataItem(item.Uid, item.Title, item.Subtitle, item.ImagePath, item.Description, item.VideoId, null);

                        ytdi._Grouping = grouping;

                        //if (StandardFeedResults.Count() == 0)
                        StandardFeedResults.Add(ytdi);
                        //else
                        //    StandardFeedResults.Insert(0, ytdi);
                    }

                    return;
                }

                //});

                //});
            }
            catch (Exception ex) {
                AlertService.LogAlertMessage("Error retrieving History from Cache", ex.Message);
            }

            return;
        }