Ejemplo n.º 1
0
        public static Return RestoreDatabase(string backUpFilePath)
        {
            Return returnObj = BaseMapper.GenerateReturn();

            if (!string.IsNullOrEmpty(backUpFilePath) && File.Exists(backUpFilePath))
            {
                var databaseName = BaseMapper.GetDataModel().Database.Connection.Database;

                var sqlCommand = $@"ALTER DATABASE {databaseName} SET Single_User WITH Rollback Immediate; USE master; RESTORE DATABASE {databaseName} FROM DISK = '{backUpFilePath}'; ALTER DATABASE {databaseName} SET Multi_User";

                try
                {
                    var result = BaseMapper.GetDataModel(true).Database.ExecuteSqlCommand(transactionalBehavior: System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sql: sqlCommand);
                    returnObj.SetRawData(result);

                    return(returnObj);
                }
                catch (Exception ex)
                {
                    ErrorHelper.LogException(ex);
                    returnObj.Error = ErrorHelper.CreateError(ex);

                    return(returnObj);
                }
            }

            return(returnObj);
        }
Ejemplo n.º 2
0
        public static Return GetFromCache(string url)
        {
            var returnObj = new Return();

            try
            {
                //var inContext = (string)ContextHelper.GetFromCache(url);

                //if (inContext != null && inContext != "")
                //{
                //    returnObj.SetRawData(inContext);

                //    return returnObj;
                //}
                var fileInfo = GetFileInfoFromUrl(url);

                if (fileInfo.Exists)
                {
                    //if (BaseMapper.CanConnectToDB != null && BaseMapper.CanConnectToDB == true)
                    //{
                    //	if ((CacheDurationInSeconds != null) && (DateTime.Now > fileInfo.LastWriteTime.AddSeconds((double)CacheDurationInSeconds)))
                    //	{
                    //		File.Delete(fileInfo.FullName);
                    //		returnObj.Error = new Elmah.Error(new Exception("Cache has expired"));
                    //		return returnObj;
                    //	}
                    //}

                    using (FileStream fs = new FileStream(fileInfo.FullName,
                                                          FileMode.Open,
                                                          FileAccess.Read,
                                                          FileShare.ReadWrite))
                    {
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            var data = sr.ReadToEnd();
                            returnObj.SetRawData(data);
                            return(returnObj);
                        }
                    }
                }
                else
                {
                    returnObj.Error = new Elmah.Error(new Exception("Cache does not exist"));
                    return(returnObj);
                }
            }
            catch (Exception ex)
            {
                ErrorHelper.LogException(ex);

                returnObj.Error = new Elmah.Error(ex);
                return(returnObj);
            }
        }
Ejemplo n.º 3
0
        public Return AddEmailAddressToMailChimp(string listId, User user, Dictionary <string, object> mergeFields)
        {
            var returnObj = new Return();

            try
            {
                // Use the Status property if updating an existing member

                var memberExists = MailChimpManager.Members.ExistsAsync(listId, user.EmailAddress).Result;

                Member member = null;

                if (memberExists)
                {
                    member = new Member {
                        EmailAddress = user.EmailAddress, Status = Status.Subscribed, StatusIfNew = Status.Pending
                    };
                }
                else
                {
                    member = new Member {
                        EmailAddress = user.EmailAddress, Status = Status.Pending, StatusIfNew = Status.Pending
                    };
                }

                foreach (var mergeField in mergeFields)
                {
                    member.MergeFields.Add(mergeField.Key, mergeField.Value);
                }

                /*var birthDay = new DateTime(DateTime.Now.Year, user.Month, user.Day);
                 *
                 * member.MergeFields.Add("FNAME", user.Name);
                 * member.MergeFields.Add("CITY", user.City);
                 * member.MergeFields.Add("BIRTHDAY", birthDay.ToString("MM/dd"));
                 * member.MergeFields.Add("REGION", user.Region);*/

                //member.MergeFields.Add("LNAME", user.LastName);

                member = MailChimpManager.Members.AddOrUpdateAsync(listId, member).Result;

                returnObj.SetRawData(member);

                return(returnObj);
            }
            catch (Exception ex)
            {
                returnObj.Error = ErrorHelper.CreateError(ex.Message, ex.InnerException?.Message);
                return(returnObj);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Attempts to update the DB with all the changes made to the current DataContext
        /// </summary>
        /// <param name="logError"></param>
        /// <returns>An instance of the Return class</returns>
        public static Return SaveDataModel(bool logError = true)
        {
            var returnObj = new Return();

            try
            {
                var returnVal = GetDataModel().SaveChanges();
                returnObj.SetRawData(returnVal);

                if (returnVal == 0)
                {
                    throw new Exception("No changes made", new Exception("The transaction was successfull but no changes were made"));
                }
            }
            catch (DbEntityValidationException ex)
            {
                returnObj.Error = ErrorHelper.CreateError(ex);

                var message = "";
                foreach (var validationError in ex.EntityValidationErrors)
                {
                    foreach (var error in validationError.ValidationErrors)
                    {
                        message += error.ErrorMessage + "<br />\r\n";
                    }
                }

                returnObj.Error.Message += "<br>\r\n" + message;

                if (logError)
                {
                    ErrorHelper.LogException(ex);
                }
            }
            catch (Exception ex)
            {
                returnObj.Error = ErrorHelper.CreateError(ex);

                if (logError)
                {
                    ErrorHelper.LogException(ex);
                }
            }

            return(returnObj);
        }
Ejemplo n.º 5
0
        public Return AddUpdateEmailAddress(string listId, User user, Dictionary <string, object> mergeFields = null, List <string> addTags = null)
        {
            var returnObj = new Return();

            try
            {
                // Use the Status property if updating an existing member

                var memberExists = MailChimpManager.Members.ExistsAsync(listId, user.EmailAddress).Result;

                Member member = null;

                if (memberExists)
                {
                    member = MailChimpManager.Members.GetAsync(listId, user.EmailAddress).Result;                     //new Member { EmailAddress = user.EmailAddress, Status = Status.Subscribed, StatusIfNew = Status.Subscribed };
                }
                else
                {
                    member = new Member {
                        EmailAddress = user.EmailAddress, Status = Status.Subscribed, StatusIfNew = Status.Subscribed
                    };
                }

                if (mergeFields != null)
                {
                    foreach (var mergeField in mergeFields)
                    {
                        member.MergeFields.Add(mergeField.Key, mergeField.Value);
                    }
                }

                if (addTags != null)
                {
                    var listSegments = MailChimpManager.ListSegments.GetAllAsync(listId).Result;
                    var addSegments  = listSegments.Where(i => addTags.Contains(i.Name));

                    foreach (var currentTag in member.Tags)
                    {
                        if (!addSegments.Any(i => i.Id == currentTag.Id))
                        {
                            MailChimpManager.ListSegments.DeleteMemberAsync(listId, currentTag.Id.ToString(), member.EmailAddress);
                        }
                    }

                    foreach (var segment in addSegments)
                    {
                        MailChimpManager.ListSegments.AddMemberAsync(listId, segment.Id.ToString(), member);
                    }
                }

                /*var birthDay = new DateTime(DateTime.Now.Year, user.Month, user.Day);
                 *
                 * member.MergeFields.Add("FNAME", user.Name);
                 * member.MergeFields.Add("CITY", user.City);
                 * member.MergeFields.Add("BIRTHDAY", birthDay.ToString("MM/dd"));
                 * member.MergeFields.Add("REGION", user.Region);*/

                //member.MergeFields.Add("LNAME", user.LastName);

                member = MailChimpManager.Members.AddOrUpdateAsync(listId, member).Result;

                if (addTags != null)
                {
                    member = AddTagsToExistingMember(member, listId, addTags);
                }

                returnObj.SetRawData(member);

                return(returnObj);
            }
            catch (Exception ex)
            {
                returnObj.Error = ErrorHelper.CreateError(ex.Message, ex.InnerException?.Message);
                return(returnObj);
            }
        }
Ejemplo n.º 6
0
        public static Return BackupDatabase()
        {
            Return returnObj = BaseMapper.GenerateReturn();

            var databaseName = BaseMapper.GetDataModel().Database.Connection.Database;

            var sqlCommand = $@"BACKUP DATABASE {databaseName} TO DISK = '{DbBackupPath}{DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt")}-{databaseName}.bak'";

            try
            {
                var result = BaseMapper.GetDataModel(true).Database.ExecuteSqlCommand(transactionalBehavior: System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sql: sqlCommand);
                returnObj.SetRawData(result);

                return(returnObj);
            }
            catch (Exception ex)
            {
                ErrorHelper.LogException(ex);
                returnObj.Error = ErrorHelper.CreateError(ex);

                return(returnObj);
            }


            /*SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
             * string dbName = builder.InitialCatalog;
             * string backUpPath = URIHelper.BasePath + "App_Data/DBBackups/" + DateTime.Now.ToString("yyyy'-'MM'-'dd-HH'-'mm'-'ss'Z'") + "-" + dbName + ".bak";
             *
             * using (SqlConnection cnn = new SqlConnection(connectionString))
             * {
             *  cnn.Open();
             *  dbName = cnn.Database.ToString();
             *
             *  ServerConnection sc = new ServerConnection(cnn);
             *  Server sv = new Server(sc);
             *
             *  // Create backup device item for the backup
             *  BackupDeviceItem bdi = new BackupDeviceItem(backUpPath, DeviceType.File);
             *
             *  // Create the backup informaton
             *  Microsoft.SqlServer.Management.Smo.Backup bk = new Backup();
             *
             *  //bk.PercentComplete += new PercentCompleteEventHandler(percentComplete);
             *  bk.Devices.Add(bdi);
             *  bk.Action = BackupActionType.Database;
             *  bk.PercentCompleteNotification = 1;
             *  bk.BackupSetDescription = dbName;
             *  bk.BackupSetName = dbName;
             *  bk.Database = dbName;
             *
             *  //bk.ExpirationDate = DateTime.Now.AddSeconds(10);
             *  bk.LogTruncation = BackupTruncateLogType.Truncate;
             *  bk.FormatMedia = false;
             *  bk.Initialize = true;
             *  bk.Checksum = true;
             *  bk.ContinueAfterError = true;
             *  bk.Incremental = false;
             *
             *  try
             *  {
             *      // Run the backup
             *      bk.SqlBackup(sv);//Exception
             *      return returnObj;
             *  }
             *  catch (Exception ex)
             *  {
             *      ErrorHelper.LogException(ex);
             *
             *      returnObj.Error = ErrorHelper.CreateError(ex);
             *
             *      return returnObj;
             *  }
             * }*/
        }