public async Task <FileResult> Download(int templateId)
        {
            var template = db.Templates.First(x => x.TemplateId == templateId);
            var filters  = JsonConvert.DeserializeObject <FilterInputs>(template.Filters);

            var csvUtils = new CsvMethods();
            var bytes    = await csvUtils.GetZipFile(
                filters.Schools,
                //filters.SchoolYears,
                //filters.Terms,
                //filters.Subjects,
                //filters.Courses,
                filters.Teachers,
                filters.Sections,
                template.OneRosterVersion);

            var    logUtils = new LoggingMethods();
            string ip       = Request.UserHostAddress;

            logUtils.LogAdminDownload(template, UserName, ip);

            var downloadFileName = "EdFiExport_" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".zip";

            return(File(bytes, "application/zip", downloadFileName));
        }
예제 #2
0
        public static int Main(string[] args)
        {
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;
            var textFilePath = Path.Combine(appDirectory, "log-textFile.log");
            var jsonFilePath = Path.Combine(appDirectory, "log-jsonFile.log");

            File.Delete(textFilePath);
            File.Delete(jsonFilePath);

            // Initialize NLog
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(appDirectory, "NLog.46.config"));
#if NETCOREAPP
            // Hacks for the fact the NLog on Linux just can't do anything right
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var target = (FileTarget)LogManager.Configuration.FindTargetByName("textFile");
                if (target is not null)
                {
                    target.FileName = Path.Combine(appDirectory, "log-textFile.log");
                }

                target = (FileTarget)LogManager.Configuration.FindTargetByName("jsonFile");
                if (target is not null)
                {
                    target.FileName = Path.Combine(appDirectory, "log-jsonFile.log");
                }
                LogManager.ReconfigExistingLoggers();
            }
#endif

            Logger logger = LogManager.GetCurrentClassLogger();
            return(LoggingMethods.RunLoggingProcedure(logger.Info));
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : true);

            var logUtils = new LoggingMethods();

            switch (result)
            {
            case SignInStatus.Success:
                logUtils.LogUserLogin(model.Email, IpAddress, true, null);
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                logUtils.LogUserLogin(model.Email, IpAddress, false, "Locked out");
                ModelState.AddModelError("", "This account has been locked out.  Please try again in 1 hour.  Or modify the [LockoutEndDateUtc] field in the [AspNetUsers] table.");
                return(View(model));

            case SignInStatus.Failure:
            default:
                logUtils.LogUserLogin(model.Email, IpAddress, false, "Invalid login attempt");
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
예제 #4
0
        public static int Main(string[] args)
        {
            // This test creates and unloads an appdomain
            // It seems that in some (unknown) conditions the tracer gets loader into the child appdomain
            // When that happens, there is a risk that the startup log thread gets aborted during appdomain unload,
            // adding error logs which in turn cause a failure in CI.
            // Disabling the startup log at the process level should prevent this.
            Environment.SetEnvironmentVariable("DD_TRACE_STARTUP_LOGS", "0");

            LoggingMethods.DeleteExistingLogs();

            // Initialize Serilog
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;
            var textFilePath = Path.Combine(appDirectory, "log-textFile.log");
            var jsonFilePath = Path.Combine(appDirectory, "log-jsonFile.log");

            var log = new LoggerConfiguration()
                      .Enrich.FromLogContext()
                      .MinimumLevel.Is(LogEventLevel.Information)
                      .WriteTo.File(
                textFilePath,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {{ dd_service: \"{dd_service}\", dd_version: \"{dd_version}\", dd_env: \"{dd_env}\", dd_trace_id: \"{dd_trace_id}\", dd_span_id: \"{dd_span_id}\" }} {Message:lj} {NewLine}{Exception}")
#if SERILOG_2_0
                      .WriteTo.File(
                new JsonFormatter(),
                jsonFilePath)
#endif
                      .CreateLogger();

            return(LoggingMethods.RunLoggingProcedure(LogWrapper(log)));
        }
        public ActionResult LogOff()
        {
            var logUtils = new LoggingMethods();

            logUtils.LogUserLogout(UserName, IpAddress);

            CommonUtils.ExistingResponses.Clear();
            Session.Clear();

            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return(RedirectToAction("Login", "Account"));
        }
예제 #6
0
        public static int Main(string[] args)
        {
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;
            var textFilePath = Path.Combine(appDirectory, "log-textFile.log");

            File.Delete(textFilePath);

            // Initialize NLog
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(appDirectory, "NLog.Pre40.config"));
            Logger logger = LogManager.GetCurrentClassLogger();

            return(LoggingMethods.RunLoggingProcedure(logger.Info));
        }
예제 #7
0
        public static int Main(string[] args)
        {
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;
            var textFilePath = Path.Combine(appDirectory, "log-textFile.log");
            var jsonFilePath = Path.Combine(appDirectory, "log-jsonFile.log");

            File.Delete(textFilePath);
            File.Delete(jsonFilePath);

            // Initialize log4net
            var logRepository = LogManager.GetRepository(typeof(Program).Assembly);

            XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(appDirectory, "log4net.205.config")));

            return(LoggingMethods.RunLoggingProcedure(log.Info));
        }
예제 #8
0
        public static int Main(string[] args)
        {
            // Initialize Serilog
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;
            var textFilePath = Path.Combine(appDirectory, "log-textFile.log");
            var jsonFilePath = Path.Combine(appDirectory, "log-jsonFile.log");

            File.Delete(textFilePath);
            File.Delete(jsonFilePath);

            var log = new LoggerConfiguration()
                      .Enrich.FromLogContext()
                      .MinimumLevel.Is(LogEventLevel.Information)
                      .WriteTo.File(
                textFilePath,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {{ dd_service: \"{dd_service}\", dd_version: \"{dd_version}\", dd_env: \"{dd_env}\", dd_trace_id: \"{dd_trace_id}\", dd_span_id: \"{dd_span_id}\" }} {Message:lj} {NewLine}{Exception}")
                      .CreateLogger();

            return(LoggingMethods.RunLoggingProcedure(LogWrapper(log)));
        }
예제 #9
0
        public async Task <ActionResult> Index(string id)  //Careful when changing this method definition.  There is a custom route for it in the RouteConfig.
        {
            var logUtils = new LoggingMethods();
            var template = db.Templates.First(x => x.AccessUrl.Contains(id));

            if (Request.Headers["token"] == null) //http://forums.asp.net/t/1991328.aspx?Reading+HTTP+Header+in+MVC+5
            {
                var errorMsg = "No Security Token Received";
                logUtils.LogUserDownload(template, IpAddress, false, errorMsg);
                return(Json(new { ErrorMessage = errorMsg }, JsonRequestBehavior.AllowGet));
            }

            string token = Request.Headers["token"];

            if (template == null || template.AccessToken != token)
            {
                var errorMsg = "Url not found and/or token doesnt match";
                logUtils.LogUserDownload(template, IpAddress, false, errorMsg);
                return(Json(new { ErrorMessage = errorMsg }, JsonRequestBehavior.AllowGet));
            }

            var filters  = JsonConvert.DeserializeObject <FilterInputs>(template.Filters);
            var csvUtils = new CsvMethods();
            var bytes    = await csvUtils.GetZipFile(
                filters.Schools,
                //filters.SchoolYears,
                //filters.Terms,
                //filters.Subjects,
                //filters.Courses,
                filters.Teachers,
                filters.Sections,
                template.OneRosterVersion);

            logUtils.LogUserDownload(template, IpAddress, true, null);

            var downloadFileName = "EdFiExport_" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".zip";

            return(File(bytes, "application/zip", downloadFileName));
        }
예제 #10
0
        public static int Main(string[] args)
        {
            // This test creates and unloads an appdomain
            // It seems that in some (unknown) conditions the tracer gets loader into the child appdomain
            // When that happens, there is a risk that the startup log thread gets aborted during appdomain unload,
            // adding error logs which in turn cause a failure in CI.
            // Disabling the startup log at the process level should prevent this.
            Environment.SetEnvironmentVariable("DD_TRACE_STARTUP_LOGS", "0");

            LoggingMethods.DeleteExistingLogs();

            // Initialize log4net
            var logRepository = LogManager.GetRepository(typeof(Program).Assembly);
            var appDirectory  = Directory.GetParent(typeof(Program).Assembly.Location).FullName;

#if NETFRAMEWORK && LOG4NET_2_0_5
            XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(appDirectory, "log4net.205.config")));
#else
            // Regardless of package version, for .NET Core just assert against raw log lines
            XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(appDirectory, "log4net.Pre205.config")));
#endif

            return(LoggingMethods.RunLoggingProcedure(log.Info));
        }
예제 #11
0
        private async void uiBtnRun_Click(object sender, EventArgs e)
        {
            if (cboSelectedProject.Text == $"No published projects in '{_publishedProjectsPath}'")
            {
                return;
            }

            string projectPackagePath = Path.Combine(Folders.GetFolder(FolderType.PublishedFolder), cboSelectedProject.Text);

            if (!File.Exists(projectPackagePath))
            {
                MessageBox.Show($"Unable to find '{projectPackagePath}' in Published directory", "Error");
                return;
            }

            string newProjectPath = Path.Combine(Folders.GetFolder(FolderType.TempFolder), Path.GetFileNameWithoutExtension(cboSelectedProject.Text));

            if (Directory.Exists(newProjectPath))
            {
                Directory.Delete(newProjectPath, true);
            }

            try
            {
                Directory.CreateDirectory(newProjectPath);
                File.Copy(projectPackagePath, Path.Combine(Folders.GetFolder(FolderType.TempFolder), cboSelectedProject.Text), true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                return;
            }

            string  configPath;
            string  projectPath;
            Project project;

            try
            {
                configPath  = Project.ExtractGalleryProject(newProjectPath);
                projectPath = Directory.GetParent(configPath).ToString();
                project     = Project.OpenProject(configPath);
            }
            catch (Exception ex)
            {
                Directory.Delete(newProjectPath, true);
                MessageBox.Show(ex.Message, "Error");
                return;
            }

            switch (project.ProjectType)
            {
            case ProjectType.OpenBots:
                var projectName = new DirectoryInfo(projectPath).Name;
                //initialize Logger
                Logger engineLogger = null;
                switch (_appSettings.EngineSettings.LoggingSinkType)
                {
                case SinkType.File:
                    if (string.IsNullOrEmpty(_appSettings.EngineSettings.LoggingValue.Trim()))
                    {
                        _appSettings.EngineSettings.LoggingValue = Path.Combine(Folders.GetFolder(FolderType.LogFolder), "OpenBots Engine Logs.txt");
                    }

                    engineLogger = new LoggingMethods().CreateFileLogger(_appSettings.EngineSettings.LoggingValue, Serilog.RollingInterval.Day,
                                                                         _appSettings.EngineSettings.MinLogLevel);
                    break;

                case SinkType.HTTP:
                    engineLogger = new LoggingMethods().CreateHTTPLogger(projectName, _appSettings.EngineSettings.LoggingValue, _appSettings.EngineSettings.MinLogLevel);
                    break;
                }

                frmScriptEngine newEngine = new frmScriptEngine(configPath, engineLogger);
                newEngine.ShowDialog();
                newEngine.Dispose();
                break;

            case ProjectType.Python:
            case ProjectType.TagUI:
            case ProjectType.CSScript:
            case ProjectType.PowerShell:
                await ExecutionManager.RunTextEditorProject(configPath, project.ProjectArguments);

                break;
            }

            if (Directory.Exists(newProjectPath))
            {
                Directory.Delete(newProjectPath, true);
            }
        }
예제 #12
0
 public void SetUp()
 {
     _loggingMethods = new LoggingMethods();
 }
예제 #13
0
        public virtual void ScriptFinished(ScriptFinishedResult result, string error = null)
        {
            if (ChildScriptFailed && !ChildScriptErrorCaught)
            {
                error  = "Terminate with failure";
                result = ScriptFinishedResult.Error;
                Log.Fatal("Result Code: " + result.ToString());
            }
            else
            {
                Log.Information("Result Code: " + result.ToString());
            }

            //add result variable if missing
            var resultVar = EngineContext.Variables.Where(f => f.VariableName == "OpenBots.Result").FirstOrDefault();

            //handle if variable is missing
            if (resultVar == null)
            {
                resultVar = new OBScriptVariable()
                {
                    VariableName = "OpenBots.Result", VariableValue = ""
                }
            }
            ;

            //check value
            var resultValue = resultVar.VariableValue.ToString();

            if (error == null)
            {
                Log.Information("Error: None");

                if (string.IsNullOrEmpty(resultValue))
                {
                    EngineContext.TaskResult = "Successfully Completed Script";
                }
                else
                {
                    EngineContext.TaskResult = resultValue;
                }
            }

            else
            {
                if (ErrorsOccured.Count > 0)
                {
                    error = ErrorsOccured.OrderByDescending(x => x.LineNumber).FirstOrDefault().StackTrace;
                }

                Log.Error("Error: " + error);
                EngineContext.TaskResult = error;
            }

            if ((EngineContext.ScriptEngine != null && !EngineContext.IsChildEngine) ||
                (EngineContext.IsServerExecution && !EngineContext.IsServerChildExecution))
            {
                Log.CloseAndFlush();
            }

            EngineContext.CurrentEngineStatus = EngineStatus.Finished;
            ScriptFinishedEventArgs args = new ScriptFinishedEventArgs
            {
                LoggedOn      = DateTime.Now,
                Result        = result,
                Error         = error,
                ExecutionTime = _stopWatch.Elapsed,
                FileName      = EngineContext.FilePath
            };

            //convert to json
            var serializedArguments = JsonConvert.SerializeObject(args);

            //write execution metrics
            if (EngineContext.EngineSettings.TrackExecutionMetrics && (EngineContext.FilePath != null))
            {
                string summaryLoggerFilePath = Path.Combine(Folders.GetFolder(FolderType.LogFolder), "OpenBots Execution Summary Logs.txt");
                Logger summaryLogger         = new LoggingMethods().CreateJsonFileLogger(summaryLoggerFilePath, RollingInterval.Infinite);
                summaryLogger.Information(serializedArguments);

                if (!EngineContext.IsChildEngine)
                {
                    summaryLogger.Dispose();
                }
            }

            ScriptFinishedEvent?.Invoke(this, args);
        }
예제 #14
0
        public async override Tasks.Task RunCommand(object sender)
        {
            var engine = (IAutomationEngineInstance)sender;

            //get text to log and log file name
            var textToLog = (string)await v_LogText.EvaluateCode(engine);

            var loggerFilePath = (string)await v_LogFile.EvaluateCode(engine);

            LogEventLevel logLevel = LogEventLevel.Information;

            //determine log file
            switch (v_LogType)
            {
            case "Verbose":
                logLevel = LogEventLevel.Verbose;
                break;

            case "Debug":
                logLevel = LogEventLevel.Debug;
                break;

            case "Information":
                logLevel = LogEventLevel.Information;
                break;

            case "Warning":
                logLevel = LogEventLevel.Warning;
                break;

            case "Error":
                logLevel = LogEventLevel.Error;
                break;

            case "Fatal":
                logLevel = LogEventLevel.Fatal;
                break;
            }

            if (loggerFilePath != "Engine Logs")
            {
                //create new logger and log to custom file
                using (var logger = new LoggingMethods().CreateFileLogger(loggerFilePath, RollingInterval.Infinite))
                {
                    switch (v_LogType)
                    {
                    case "Verbose":
                        logger.Verbose(textToLog);
                        break;

                    case "Debug":
                        logger.Debug(textToLog);
                        break;

                    case "Information":
                        logger.Information(textToLog);
                        break;

                    case "Warning":
                        logger.Warning(textToLog);
                        break;

                    case "Error":
                        logger.Error(textToLog);
                        break;

                    case "Fatal":
                        logger.Fatal(textToLog);
                        break;
                    }
                }
            }

            string logMessage = $"{v_LogType} - {textToLog}";

            engine.ReportProgress($"Logging Line {LineNumber}: {(v_IsPrivate ? engine.PrivateCommandLog : logMessage)}", Enum.GetName(typeof(LogEventLevel), logLevel));
        }
예제 #15
0
        public static int Main(string[] args)
        {
            // This test creates and unloads an appdomain
            // It seems that in some (unknown) conditions the tracer gets loader into the child appdomain
            // When that happens, there is a risk that the startup log thread gets aborted during appdomain unload,
            // adding error logs which in turn cause a failure in CI.
            // Disabling the startup log at the process level should prevent this.
            Environment.SetEnvironmentVariable("DD_TRACE_STARTUP_LOGS", "0");

            var env = SampleHelpers.GetDatadogEnvironmentVariables();

            foreach (var kvp in env)
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");
            }

            bool isAttached = SampleHelpers.IsProfilerAttached();

            Console.WriteLine(" * Checking if the profiler is attached: {0}", isAttached);

            LoggingMethods.DeleteExistingLogs();

            // Initialize NLog
            var appDirectory = Directory.GetParent(typeof(Program).Assembly.Location).FullName;

#if NLOG_4_6
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(appDirectory, "NLog.46.config"));
            Console.WriteLine("Using NLOG_4_6 configuration");

            global::NLog.LogManager.ThrowExceptions         = true;
            global::NLog.Common.InternalLogger.LogToConsole = true;
            global::NLog.Common.InternalLogger.LogLevel     = LogLevel.Debug;
#elif NLOG_4_0
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(appDirectory, "NLog.40.config"));
            Console.WriteLine("Using NLOG_4_0 configuration");

            global::NLog.LogManager.ThrowExceptions         = true;
            global::NLog.Common.InternalLogger.LogToConsole = true;
            global::NLog.Common.InternalLogger.LogLevel     = LogLevel.Debug;
#else
            LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(appDirectory, "NLog.Pre40.config"));
            Console.WriteLine("Using pre NLOG_4_0 configuration");
#endif
#if NETCOREAPP
            // Hacks for the fact the NLog on Linux just can't do anything right
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var target = (FileTarget)LogManager.Configuration.FindTargetByName("textFile");
                if (target is not null)
                {
                    target.FileName = Path.Combine(appDirectory, "log-textFile.log");
                }

                target = (FileTarget)LogManager.Configuration.FindTargetByName("jsonFile");
                if (target is not null)
                {
                    target.FileName = Path.Combine(appDirectory, "log-jsonFile.log");
                }
                LogManager.ReconfigExistingLoggers();
            }
#endif

            Logger Logger = LogManager.GetCurrentClassLogger();
            return(LoggingMethods.RunLoggingProcedure(Logger.Info));
        }
예제 #16
0
        static void Main(string[] args)
        {
            //SetProcessDPIAware();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //exception handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            //get app settings
            var appSettings = new ApplicationSettings();

            appSettings = appSettings.GetOrCreateApplicationSettings();

            //create native chrome manifest file
            var manifestSettingsManger = new ManifestSettingsManager();

            manifestSettingsManger.Save();

            //if the exe was passed a filename argument then run the script
            if (args.Length > 0)
            {
                string configPath = args[0];

                if (!File.Exists(configPath))
                {
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "Application";
                        eventLog.WriteEntry($"An attempt was made to run an OpenBots project from '{new DirectoryInfo(configPath).Parent}'" +
                                            "but the 'project.obconfig' file was not found. Please verify that the file exists at the path indicated.",
                                            EventLogEntryType.Error, 101, 1);
                    }

                    Application.Exit();
                    return;
                }

                //initialize Logger
                string engineLoggerFilePath = Path.Combine(Folders.GetFolder(FolderType.LogFolder), "OpenBots Engine Logs.txt");
                Logger engineLogger         = new LoggingMethods().CreateFileLogger(engineLoggerFilePath, Serilog.RollingInterval.Day);

                ProjectType projectType = Project.OpenProject(configPath).ProjectType;
                switch (projectType)
                {
                case ProjectType.OpenBots:
                    Application.Run(new frmScriptEngine(configPath, engineLogger));
                    break;

                case ProjectType.Python:
                case ProjectType.TagUI:
                case ProjectType.CSScript:
                case ProjectType.PowerShell:
                    ExecutionManager.RunTextEditorProject(configPath, Project.OpenProject(configPath).ProjectArguments).Wait();
                    break;
                }
            }
            else if (appSettings.ClientSettings.StartupMode == "Builder Mode" && appSettings.ClientSettings.IsRestarting)
            {
                Application.DoEvents();
                Application.Run(new frmScriptBuilder(appSettings.ClientSettings.RecentProjects[0]));
            }
            else if (appSettings.ClientSettings.StartupMode == "Builder Mode")
            {
                SplashForm = new frmSplash();
                SplashForm.Show();

                Application.DoEvents();
                Application.Run(new frmScriptBuilder(null));
            }
            else
            {
                SplashForm = new frmSplash();
                SplashForm.Show();

                Application.DoEvents();
                Application.Run(new frmAttendedMode());
            }
        }