Beispiel #1
0
        /// <summary>
        /// Connect to postgresDB
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <param name="connString"></param>
        /// <returns></returns>
        public static NpgsqlConnection Connect(string user, string password, string connString)
        {
            Disconnect();
            DBUserId           = user;
            DBPass             = password;
            DBConnectionString = connString;

            if (dbConn != null && dbConn.State == System.Data.ConnectionState.Open)
            {
                return(dbConn);
            }

            string conStr = $"User Id = {user}; Password = {password}; {connString}";

            try
            {
                dbConn = new NpgsqlConnection(conStr);
                dbConn.Open();
                connString = conStr;
            }
            catch (System.Exception e)
            {
                logger.LogError(e.ToString());
                throw;
            }
            return(dbConn);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            ILoggerManager loggerManager = new LoggerManager();

            Dictionary <string, object> settings = new Dictionary <string, object>();

            settings.Add("Log4Net.ConversionPattern", "%date [%thread] %-5level %logger - %message%newline");
            settings.Add("Log4Net.MaximumFileSize", "1MB");
            settings.Add("Log4Net.MaxSizeRollBackups", 5);
            settings.Add("Log4Net.File", @"d:\Log4NetLogger.txt");

            ILogger log4NetLogger = new Log4NetLogger("Log4NetLogger");

            log4NetLogger.Configure(settings);
            loggerManager.AddLogger("Log4NetLogger", log4NetLogger);

            ILogger eventLogLogger = new EventLogLogger("TestApp", "Application", 400, null);

            loggerManager.AddLogger("EventLogLogger", eventLogLogger);

            SystemLogger systemLogger = new SystemLogger(loggerManager);

            systemLogger.LogInfo("This is my first info log.");
            systemLogger.LogDebug("This is my first debug log.");
            systemLogger.LogWarning("This is my first warning log.");
            systemLogger.LogError(ErrorSeverity.Low, "This is my first low error log.", new Exception("This is my first low error log."));
            systemLogger.LogError(ErrorSeverity.Medium, "This is my first medium error log.", new Exception("This is my first medium error log."));
            systemLogger.LogError(ErrorSeverity.High, "This is my first high error log.", new Exception("This is my first high error log."));
            systemLogger.LogError(ErrorSeverity.Extreme, "This is my first extreme error log.", new Exception("This is my first extreme error log."));
            systemLogger.LogMethodStart("static void Main(string[] args)", new string[] { "args" }, new object[] { args });
            systemLogger.LogMethodEnd("static void Main(string[] args)", true);
            systemLogger.LogMethodEnd("static void Main(string[] args)", false);
        }
        public void Log_Error_EmitsExpectedEvent()
        {
            string eventName            = string.Empty;
            string message              = "TestMessage";
            string functionInvocationId = string.Empty;
            string activityId           = string.Empty;

            Exception ex = new Exception("Kaboom");

            _mockEventGenerator.Setup(p => p.LogFunctionTraceEvent(LogLevel.Error, _subscriptionId, _websiteName, _functionName, eventName, _category, ex.ToFormattedString(), message, ex.GetType().ToString(), ex.Message, functionInvocationId, _hostInstanceId, activityId));

            _logger.LogError(ex, message);

            _mockEventGenerator.VerifyAll();
        }
Beispiel #4
0
        public async Task DoWork(BackgroundJob job, CancellationToken token)
        {
            var result = new BackgroundJobResult()
            {
                EventNumber    = job.EventNumber,
                DateTimeRunUTC = DateTime.UtcNow
            };

            try
            {
                await job.Event.DoWork(token);

                result.Status = "Success";

                BackgroundService.AddBackgroundInformation(job.Event.Description, String.Format("Ran background process {0} : {1} -> {2}", job.Event.Description, result.Status, result.ExecutionInformation));
            }
            catch (Exception error)
            {
                SystemLogger.LogError <BackgroundWorker>("Error doing background worker work", error);
                result.Status = "Error: " + job.Event.Description;
                result.ExecutionInformation = error.Message + "\n" + error.StackTrace;
                BackgroundService.AddBackgroundError(job.Event.Description, error);
            }

            //BackgroundService.AddBackgroundInformation(job.Event.Description, String.Format("Ran background process {0} : {1} -> {2}", job.Event.Description, result.Status, result.ExecutionInformation));

            //BackgroundService.SaveBackgroundJobResult(result); /* I don't have a view of this yet */
        }
Beispiel #5
0
        public async Task <IHttpActionResult> Process(int eventId, HttpRequestMessage requestMessage)
        {
            JsonResult <T> jsonResult;

            try
            {
                await AuditService.LogUserEvent(eventId);

                var result = await ProcessEvent(eventId);

                if (result is FileActionResult)
                {
                    return(result as FileActionResult);
                }

                jsonResult = new JsonResult <T>(result, JSON_SETTINGS, Encoding.UTF8, requestMessage);
                //Logger.Debug("Result from processing " + eventId + " is:");
                //Logger.Debug(new JavaScriptSerializer().Serialize(jsonResult.Content));
                return(jsonResult);
            }
            catch (Exception error)
            {
                SystemLogger.LogError("Error in core processor during Process", this.GetType(), error);

                return(new BadRequestErrorMessageResult(SystemLogger.GetMessageStack(error), new DefaultContentNegotiator(), requestMessage, new List <MediaTypeFormatter>()
                {
                    new JsonMediaTypeFormatter()
                }));
            }
        }
Beispiel #6
0
        public async Task <IHttpActionResult> InitializeSystem()
        {
            try
            {
                if (!String.IsNullOrWhiteSpace(ConstructorError))
                {
                    return(BadRequest(ConstructorError));
                }
                await Container.Resolve <InitializationProcessor>().Process(0, Request); // Just to initialize core processor

                var json = ApplicationService.InitializeApplication(ConstructorError);
                if (JSON_SETTINGS != null)
                {
                    return(Json(json, JSON_SETTINGS));
                }
                else
                {
                    return(Json(json));
                }
            }
            catch (Exception error)
            {
                SystemLogger.LogError <MainController>("Error in initialize system", error);
                return(BadRequest(error.Message + "\n" + error.StackTrace + "\n" + ConstructorError));
            }
        }
Beispiel #7
0
        //[Authorize] //Not sure if we can have authorization. should  be possible
        public async Task <IHttpActionResult> SetAcmeChallenge()
        {
            //TODO:   1. Verify request using maybe key/value pair.
            //        2. Maybe just save to the correct path here with the correct file (maybe not, I can delete it using other way).
            try
            {
                string requestData;
                using (var stream = System.Web.HttpContext.Current.Request.InputStream)
                    using (var mem = new System.IO.MemoryStream())
                    {
                        stream.CopyTo(mem);
                        requestData = System.Text.Encoding.UTF8.GetString(mem.ToArray());
                    }

                Logger.Info("Set Acme Challenge Request data: " + requestData);

                var items      = requestData.Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var acmeString = items.Where(i => i.Contains("acme")).FirstOrDefault();
                var acmeValue  = acmeString.Split('=').Last();

                Logger.Info("Acme value is: " + acmeValue);

                //TODO:   The below code should also work?
                //        And, should also be sending full path
                Logger.Info("Setting acme challenge");
                //Logger.Info("RequestData = " + requestData);
                //try
                //{
                //    var jData = JsonHelper.Parse(requestData);
                //    var acmeValueTmp = jData.GetValue("acme");
                //    Logger.Info("acme value was found using json parser");

                //    if (acmeValue == acmeValueTmp)
                //    {
                //        Logger.Info("Acme value is the same both ways");
                //    }
                //    else
                //    {
                //        Logger.Info("Acme challenge is not the same both ways");
                //    }
                //}
                //catch (Exception error)
                //{
                //    Logger.Info("Acme value not json: " + error.Message);
                //}

                var challengePath = "TODO";//

                AcmeController.ChallengeResponse = acmeValue;
                AcmeController.ChallengePath     = challengePath;

                return(Json("success: " + acmeValue));
            }
            catch (Exception error)
            {
                SystemLogger.LogError <MainController>("Error in setting acme challenge", error);
                return(BadRequest("Unable to complete acme challenge: " + error.Message));
            }
        }
Beispiel #8
0
        public MainController(IUnityContainer container)
        {
            try
            {
                lock (_Lock)
                {
                    Container          = container;
                    ApplicationService = container.Resolve <ApplicationService>();
                    if (Setup == false)
                    {
                        Logger.Debug("MainController - Setup = false, performing setup");
                        var eventService = container.Resolve <EventService>(); // This is here to ensure EventService is initialize and it's constructor is called so that EventList is not empty

                        var dataService = container.Resolve <DataService>();

                        using (var session = dataService.OpenSession())
                        {
                            WebsiteUtils.DateFormat = "dd-MM-yyyy";
                            var appSettings = session.QueryOver <SystemSettings>().List <SystemSettings>().FirstOrDefault();
                            if (appSettings != null)
                            {
                                if (!String.IsNullOrWhiteSpace(WebsiteUtils.DateFormat))
                                {
                                    WebsiteUtils.DateFormat = appSettings.DateFormat;
                                }
                            }
                        }

                        ConstructorError = String.Empty;
                        Setup            = true;
                    }

                    JSON_SETTINGS = new JsonSerializerSettings {
                        DateFormatString = WebsiteUtils.DateFormat
                    };
                }
            }
            catch (Exception error)
            {
                SystemLogger.LogError <MainController>("Error in main controller constructor", error);
                ConstructorError = "";
                var err = error;
                while (err != null)
                {
                    ConstructorError = String.Format("{0}{1}\n{2}\n|---|\n", ConstructorError, error.Message, error.StackTrace);

                    err = error.InnerException;
                }
            }
        }
Beispiel #9
0
        internal void AddBackgroundError(string action, Exception error, bool logInDatabase = true)
        {
            SystemLogger.LogError <BackgroundService>(action, error);
            if (BackupService.BusyWithBackups == true)
            {
                return;
            }

            //Need to do something about thread being aborted exception

            var stackTrace = new System.Diagnostics.StackTrace();
            var stack      = stackTrace.GetFrame(1).GetMethod().Name;
            var item       = new BackgroundInformation(action, String.Format("Error:\n{0}\n{1}\n{2}\n{3}", error.Message, error.StackTrace, stack, stackTrace));

            //var currentDirectory = HttpRuntime.AppDomainAppPath;
            //var logs = currentDirectory + "\\Logs\\";
            //if (!Directory.Exists(logs))
            //{
            //    Directory.CreateDirectory(logs);
            //}
            //var path = logs + action + "_" + Guid.NewGuid().ToString();
            //File.WriteAllText(path, item.Information + "\n" + error.StackTrace);

            if (error is ThreadAbortException)
            {
                return;
            }

            if (logInDatabase == true)
            {
                using (var session = DataService.OpenSession())
                {
                    session.Save(item);
                    session.Flush();
                }
            }
        }
Beispiel #10
0
        public bool RestoreFullBackup(bool removeExistingItemsFirst, byte[] data, string dbConnectionString, params Type[] typesToIgnore)
        {
            if (removeExistingItemsFirst)
            {
                RemoveExistingData(dbConnectionString, typesToIgnore);
            }

            var stopwatch        = new Stopwatch();
            var cnt              = 1;
            var backupName       = "Restore_" + DateTime.Now.ToString("dd_MM_yyyy") + ".db";
            var currentDirectory = QBicUtils.GetCurrentDirectory() + "\\Data\\";

            if (!Directory.Exists(currentDirectory))
            {
                Directory.CreateDirectory(currentDirectory);
            }
            while (File.Exists(currentDirectory + backupName))
            {
                backupName = "Restore_" + DateTime.Now.ToString("dd_MM_yyyy") + "_" + cnt + ".db";
                cnt++;
            }

            try
            {
                File.WriteAllBytes(currentDirectory + backupName, data);

                var connectionString = String.Format(@"Data Source=##CurrentDirectory##\Data\{0};Version=3;Journal Mode=Off;Connection Timeout=12000", backupName);
                var store            = DataStore.GetInstance(false);
                var backupConfig     = store.CreateNewConfigurationUsingConnectionString(connectionString);
                var backupFactory    = backupConfig.BuildSessionFactory();

                DynamicClass.SetIdsToBeAssigned = true;
                var config  = store.CreateNewConfigurationUsingConnectionString(dbConnectionString);
                var factory = config.BuildSessionFactory();

                var ids = SystemTypes.Keys.ToList().OrderBy(i => i);

                var totalItems = 0;

                using (var backupSession = backupFactory.OpenStatelessSession())
                    using (var session = factory.OpenStatelessSession())
                    {
                        foreach (var id in ids)
                        {
                            var type = SystemTypes[id];

                            //if ((type == typeof(Models.SystemSettings) || (type == typeof(SystemSettingValue))) && restoreSystemSettings == false)
                            if (typesToIgnore.Contains(type))
                            {
                                var tmpItems = GetItems(type, backupSession);

                                continue;
                            }

                            var items = GetItems(type, backupSession);

                            var sameTypeProperties = type.GetProperties().Where(p => p.PropertyType == type).ToList();
                            if (sameTypeProperties.Count > 0)
                            {
                                var totalItemsToAdd = items.Where(i => i.GetType() == type).ToList();

                                var addedItems = new List <string>();
                                while (addedItems.Count < totalItemsToAdd.Count)
                                {
                                    foreach (var prop in sameTypeProperties)
                                    {
                                        var itemsToAdd = totalItemsToAdd.Where(i => ShouldAddItem(i, prop, totalItemsToAdd, addedItems) == true).ToList();

                                        totalItems += itemsToAdd.Count();

                                        InsertItems(itemsToAdd, factory, type);
                                        addedItems.AddRange(itemsToAdd.Select(i => i.Id));
                                    }
                                }
                            }
                            else
                            {
                                var itemsToAdd = items.Where(i => i.GetType() == type).ToList();

                                totalItems += itemsToAdd.Count();

                                InsertItems(itemsToAdd, factory, type);
                            }
                        }
                    }

                factory.Close();
                backupFactory.Close();

                using (var session = factory.OpenSession())
                {
                    var count = session
                                .CreateCriteria <BaseClass>()
                                .SetProjection(
                        Projections.Count(Projections.Id())
                        )
                                .List <int>()
                                .Sum();

                    //if (restoreSystemSettings == false)
                    //{
                    //    var settingsCount = session.QueryOver<Models.SystemSettings>().RowCount() +
                    //                        session.QueryOver<SystemSettingValue>().RowCount();
                    //    count -= settingsCount;
                    //}

                    var queryOverMethodInfo = typeof(ISession).GetMethods().FirstOrDefault(m => m.Name == "QueryOver" && m.GetParameters().Count() == 0);
                    foreach (var t in typesToIgnore)
                    {
                        var tCount = GetItemCount(t, session);
                        count -= tCount;
                    }

                    if (count != totalItems)
                    {
                        return(false);
                    }
                }

                stopwatch.Stop();

                Logger.Info("Full restore took " + stopwatch.ElapsedMilliseconds + " ms");

                return(true);
            }
            catch (Exception e)
            {
                SystemLogger.LogError <BackupService>("Error restoring full backup", e);
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                DynamicClass.SetIdsToBeAssigned = false;
                if (File.Exists(currentDirectory + backupName))
                {
                    File.Delete(currentDirectory + backupName);
                }
            }
        }
Beispiel #11
0
        public byte[] CreateFullBackup()
        {
            var cnt        = 1;
            var backupName = "Backup_" + DateTime.Now.ToString("dd_MM_yyyy") + ".db";

            var currentDirectory = QBicUtils.GetCurrentDirectory() + "\\Data\\";

            if (!Directory.Exists(currentDirectory))
            {
                Directory.CreateDirectory(currentDirectory); // try create the directory if it doesn't exist, else it would crash anyway
            }

            while (File.Exists(currentDirectory + backupName))
            {
                backupName = "Backup_" + DateTime.Now.ToString("dd_MM_yyyy") + "_" + cnt + ".db";
                cnt++;
            }

            try
            {
                DynamicClass.SetIdsToBeAssigned = true;

                Logger.Info("About to create backup");

                CreateBackupFile(currentDirectory + backupName);

                var connectionString = String.Format(@"Data Source=##CurrentDirectory##\Data\{0};Version=3;Journal Mode=Off;Connection Timeout=12000", backupName);
                var store            = DataStore.GetInstance(false);
                var config           = store.CreateNewConfigurationUsingConnectionString(connectionString);
                new SchemaUpdate(config).Execute(false, true); // Build the tables etc.
                var factory = config.BuildSessionFactory();

                var ids = SystemTypes.Keys.ToList().OrderBy(i => i);

                var total = 0;

                using (var backupSession = factory.OpenStatelessSession())
                    using (var session = DataService.OpenStatelessSession())
                    {
                        foreach (var id in ids)
                        {
                            var type = SystemTypes[id];
                            Logger.Info("Backing up " + type.ToString());

                            var items = GetItems(type, session);
                            Logger.Info("Got items");

                            var sameTypeProperties = type.GetProperties().Where(p => p.PropertyType == type).ToList();
                            if (sameTypeProperties.Count > 0)
                            {
                                var totalItemsToAdd = items.Where(i => i.GetType() == type).ToList();

                                var addedItems = new List <string>();
                                while (addedItems.Count < totalItemsToAdd.Count)
                                {
                                    foreach (var prop in sameTypeProperties)
                                    {
                                        var itemsToAdd = totalItemsToAdd.Where(i => ShouldAddItem(i, prop, totalItemsToAdd, addedItems) == true).ToList();

                                        total += itemsToAdd.Count();
                                        InsertItems(itemsToAdd, factory, type);
                                        addedItems.AddRange(itemsToAdd.Select(i => i.Id));
                                    }
                                }
                            }
                            else
                            {
                                var itemsToAdd = items.Where(i => i.GetType() == type).ToList();

                                total += itemsToAdd.Count();
                                InsertItems(itemsToAdd, factory, type);
                            }
                            Logger.Info("Items added to backup");
                        }
                    }

                Logger.Info("Closing factory");
                factory.Close();

                using (var session = factory.OpenSession())
                {
                    //var users = session.QueryOver<Models.User>().List().ToList();
                    var count = session
                                .CreateCriteria <BaseClass>()
                                .SetProjection(
                        Projections.Count(Projections.Id())
                        )
                                .List <int>()
                                .Sum();

                    if (count != total)
                    {
                        Logger.Info("Backup did not complete successfully.");
                        throw new Exception("Backup did not complete successfully. Try again or contact support.");
                    }
                }
                Logger.Info("Closing store session");

                return(File.ReadAllBytes(currentDirectory + backupName));
            }
            catch (Exception e)
            {
                SystemLogger.LogError <BackupService>("Error creating full backup", e);
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                DynamicClass.SetIdsToBeAssigned = false; // change it back.

                File.Delete(currentDirectory + backupName);
            }
        }