Beispiel #1
0
        public ActionResult GetConfigs()
        {
            FileLogic fileLogic = new FileLogic();
            var       a         = fileLogic.GetImageMime();

            return(Ok(new BaseResponse(a)));
        }
Beispiel #2
0
 public Window1(User user, Window mainWindow)
 {
     InitializeComponent();
     Closing        += WindowClosed;
     MyUser          = user;
     this.MainWindow = mainWindow;
     _userLogic      = new UserLogic();
     _fileLogic      = new FileLogic();
     _configLogic    = new ConfigLogic();
     //if (!File.Exists("MyConfig.xml"))
     //{
     //    downloadPath = "download";
     //    uploadPath = "upload";
     //}
     //if (!Directory.Exists(_configLogic.DownloadFolderPath))
     //    Directory.CreateDirectory(_configLogic.DownloadFolderPath);
     //if (!Directory.Exists(_configLogic.UploadFolderPath))
     //    Directory.CreateDirectory(_configLogic.UploadFolderPath);
     downloadPath = _configLogic.GetDownPath();
     uploadPath   = _configLogic.GetUpPath();
     Task.Factory.StartNew((() =>
     {
         _uploadLogic = new UploadLogic();
         _uploadLogic.MyUploadEvent += updateUploadTransferListView;
         _uploadLogic.UploadListener(uploadPath);
         //_uploadLogic.UploadListener("");
     }));
     _userLogic.RetrieveUserFilesLogic(MyUser, FileTransferListView);
     _userLogic.LoginFlagLogic(MyUser.UserName);
 }
Beispiel #3
0
        public Startup()
        {
            InitializeComponent();

            // We check for the cfg xml file to exist
            FileLogic.ensureConfigFileExists();
        }
Beispiel #4
0
        public UploadedFull UploadFile(IFormFile file)
        {
            Logger.LogWarning("Begin upload file");
            FileLogic    fileLogic = new FileLogic();
            UploadedFull uploaded  = fileLogic.UploadFile(file);

            return(uploaded);
        }
        public void DeleteFile()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.DeleteFile(1)).Returns(100);

            var logic = new FileLogic(mock.Object);

            Assert.IsInstanceOfType(logic.Delete("1"), typeof(bool));
        }
        public void GetFileById()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.GetFileById(1)).Returns(new Files());

            var logic = new FileLogic(mock.Object);

            Assert.IsInstanceOfType(logic.GetFileById(1), typeof(Files));
        }
        public void ReadFilesByUser()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.ReadFilesByUser(1)).Returns(new List <Files>());

            var logic = new FileLogic(mock.Object);

            Assert.IsInstanceOfType(logic.ReadFiles(), typeof(List <Files>));
        }
Beispiel #8
0
        /// <summary>
        /// Btn_AppOnlyCfg event : Onclick() Apply AppOnly configuration to the app.config file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_AppOnlyCfg_Click(object sender, RoutedEventArgs e)
        {
            FileLogic.setXMLSettingsAttribute("appID", Tb_AppID.Text);
            FileLogic.setXMLSettingsAttribute("appSecret", Tb_AppSecret.Text);
            this.Hide();
            BulkWindow bulkWindow = new BulkWindow();

            bulkWindow.Show();
            this.Close();
        }
        public void CreateFile()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.CreateFile(1, "qwe", "123")).Returns(100);

            var logic = new FileLogic(mock.Object);

            Assert.IsTrue(logic.CreateFile(1, "qwe", "qwe"));
        }
        public void UpdateMark()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.UpdateMark(1, 3)).Returns(100);

            var logic = new FileLogic(mock.Object);

            Assert.IsFalse(logic.UpdateMark("1", "3"));
        }
Beispiel #11
0
        public void GetLogPathName_ReturnWeekendExpectedFileName(string strDateTest, string expected)
        {
            //Arrange
            DateTime.TryParse(strDateTest, out DateTime dateTest);

            //Act
            string fileName = new FileLogic(new FileWrapper()).GetLogPathName(dateTest);

            //Assert
            Assert.Equal(expected, fileName);
        }
        public void UpdateText()
        {
            var mock = new Mock <IFileDao>();

            mock.Setup(item => item.UpdateText(1, "qwe")).Returns(100);

            var logic = new FileLogic(mock.Object);

            Assert.IsNotNull(logic.GetFileById(2));

            Assert.IsFalse(logic.UpdateMark("1", "3"));
        }
Beispiel #13
0
        public void TestMethod_OpenFile()
        {
            // Arrange
            string[]  expectedRes = new string[] { "Course Project", "Tymoshenko Oleh 525-b" }; // ожидаемые считанные данные
            string    fName       = "C:\\Users\\Oleh\\Desktop\\large\\testFile.txt";            // путь к файлу, из которого необходимо читать
            FileLogic fileLogic   = new FileLogic();                                            // экземпляр класса для реализ. робты с файлом

            // Act
            string[] gettedRes = fileLogic.OpenFile(fName);    // вызыв. метод для открытия файла
            //Assert
            CollectionAssert.AreEqual(expectedRes, gettedRes); // сравнение ожидидаемого и полученного результата
        }
Beispiel #14
0
 public void SetUp()
 {
     folder = new Folder {
         Parent = null, Readers = null, OwnerId = 0, Name = "ROOT", Files = null, Folders = null, Id = 0
     };
     file = new File {
         Content = "Algo de texto.", CreationDate = DateTime.Now, Id = 0, LastModifiedDate = DateTime.Now, Name = "Archivo", OwnerId = 0, Parent = folder, Readers = null
     };
     fileNull = new File {
         Parent = folder
     };
     fileRepository   = new Mock <IDataRepository <File> >();
     folderRepository = new Mock <IDataRepository <Folder> >();
     userRepository   = new Mock <IDataRepository <User> >();
     logRepository    = new Mock <IDataRepository <LogItem> >();
     fileLogic        = new FileLogic(fileRepository.Object, folderRepository.Object, userRepository.Object, logRepository.Object);
 }
Beispiel #15
0
        public void GetLogPathName_WhenWeekendDayAndFileDoesNotExists_DoNothing()
        {
            //Arrange
            DateTime saturdayTest = new DateTime(2020, 6, 6);

            _mockWrapper
            .Setup_FileExists(false)
            .Setup_GetLastWriteTime(saturdayTest.AddDays(-6))
            .Setup_MoveFile();

            //Act
            string fileName = new FileLogic(_mockWrapper.Object).GetLogPathName(saturdayTest);

            //Assert
            Assert.Equal("weekend.txt", fileName);
            _mockWrapper.Verify_GetLastWriteTime(Times.Never);
            _mockWrapper.Verify_MoveFile(Times.Never);
        }
Beispiel #16
0
        BoardLogic.ChessCoordinates CheckSpaces(BoardLogic.ChessCoordinates checkingTheseCoordinates, BoardLogic.ChessCoordinates originalCoordinates)
        {
            int row    = checkingTheseCoordinates.Row;
            int column = FileLogic.GetColumnFromChar(checkingTheseCoordinates.Column).GetHashCode();

            if (Program.board[column, row].Piece == null)
            {
                return(Program.board[column, row]);
            }
            else if (Program.board[column, row].Piece.IsLight != Program.board[FileLogic.GetColumnFromChar(originalCoordinates.Column).GetHashCode(), originalCoordinates.Row].Piece.IsLight)
            {
                return(Program.board[column, row]);
            }
            else
            {
                return(new BoardLogic.ChessCoordinates('0', -1, null));
            }
        }
Beispiel #17
0
        public ActionResult <ApiDirectory> Get(string relativePathToDirectory)
        {
            if (string.IsNullOrEmpty(relativePathToDirectory))
            {
                relativePathToDirectory = "";
            }

            relativePathToDirectory = WebUtility.UrlDecode(relativePathToDirectory);

            var directoryInfo = _fileProvider.GetDirectoryContents(relativePathToDirectory);

            if (!directoryInfo.Exists)
            {
                return(NotFound(new ApiError("The directory requested does not exist")));
            }

            return(FileLogic.GetDirectoryInfo(directoryInfo, relativePathToDirectory));
        }
Beispiel #18
0
        public void TestMethod_SaveInFileAndOpenFile()
        {
            // Arrange
            // ожидаемые считанные данны
            string[]  expectedAndSavingInf = new string[] { "Test Method FileLogic.SaveInFile", "Course Project", "Tymoshenko Oleh 525-b" };
            string    fName     = "C:\\Users\\Oleh\\Desktop\\large\\testFileSaving.txt";    // путь к файлу, из которого необходимо читать
            FileLogic fileLogic = new FileLogic();                                          // экземпляр класса для реализ. робты с файлом
            // Act
            string gettedResSaving = fileLogic.SaveInFile(expectedAndSavingInf, ref fName); // вызыв. метод для сохранения файла

            //Assert
            if (gettedResSaving != null) // если ошибка при сохранении
            {
                throw new System.Exception();
            }
            string[] readedInf = fileLogic.OpenFile(fName);             // вызыв. метод для считывания данных для проверки на сходство из теми,
            // которые сохранили
            CollectionAssert.AreEqual(expectedAndSavingInf, readedInf); // сравнение ожидидаемого и полученного результата
        }
Beispiel #19
0
        public void GetLogPathName_WhenWeekendDay_CheckAndSaveFormerWeekendFile()
        {
            //Arrange
            DateTime saturdayTest = new DateTime(2020, 6, 6);

            _mockWrapper
            .Setup_FileExists(true)
            .Setup_GetLastWriteTime(saturdayTest.AddDays(-6))
            .Setup_MoveFile();

            //Act
            string fileName = new FileLogic(_mockWrapper.Object).GetLogPathName(saturdayTest);

            //Assert
            Assert.Equal("weekend.txt", fileName);
            _mockWrapper.Verify_GetLastWriteTime(Times.Once);
            _mockWrapper.Verify_MoveFile(Times.Once);
            _mockWrapper.Verify_MoveFile_withNewFileName("weekend-20200530.txt", Times.Once);
        }
Beispiel #20
0
        /// <summary>
        /// Opens the AppOnly login window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_BulkScenario_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();

            string appID     = FileLogic.getXMLSettings("appID");
            string appSecret = FileLogic.getXMLSettings("appSecret");

            //We check if appId and secret are configured
            if (string.IsNullOrWhiteSpace(appID) || string.IsNullOrWhiteSpace(appSecret))
            {
                this.Hide();
                AppOnlyConfig appConfig = new AppOnlyConfig();
                appConfig.Show();
                this.Close();
            }
            else
            {
                BulkWindow bw = new BulkWindow();
                bw.Show();
                this.Close();
            }
        }
Beispiel #21
0
        private void Btn_Connect_Click(object sender, RoutedEventArgs e)
        {
            string ID   = FileLogic.getXMLSettings("appID");
            string Sec  = FileLogic.getXMLSettings("appSecret");
            string site = Tb_CsvFile.Text;

            using (ClientContext ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(site, ID, Sec))
            {
                /*
                 * Web web = ctx.Web;
                 * ctx.Load(web);
                 * ctx.ExecuteQuery();
                 */
                this.Context = ctx;
            }

            SPOLogic spol = new SPOLogic(Context);

            var items = spol.GetAllDocumentsInaLibrary("Documents");

            MessageBox.Show(items.Count.ToString());
        }
Beispiel #22
0
        public static void Start(string connectionString)
        {
            using (HeavyProfiler.Log("Start"))
                using (var initial = HeavyProfiler.Log("Initial"))
                {
                    StartParameters.IgnoredDatabaseMismatches = new List <Exception>();
                    StartParameters.IgnoredCodeErrors         = new List <Exception>();

                    string?logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log");

                    SchemaBuilder sb = new CustomSchemaBuilder {
                        LogDatabaseName = logDatabase, Tracer = initial
                    };
                    sb.Schema.Version          = typeof(Starter).Assembly.GetName().Version;
                    sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US");

                    MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>();
                    MixinDeclarations.Register <UserEntity, UserEmployeeMixin>();

                    OverrideAttributes(sb);

                    var detector = SqlServerVersionDetector.Detect(connectionString);
                    Connector.Default = new SqlConnector(connectionString, sb.Schema, detector !.Value);

                    CacheLogic.Start(sb);

                    DynamicLogicStarter.Start(sb);
                    DynamicLogic.CompileDynamicCode();

                    DynamicLogic.RegisterMixins();
                    DynamicLogic.BeforeSchema(sb);

                    TypeLogic.Start(sb);

                    OperationLogic.Start(sb);
                    ExceptionLogic.Start(sb);

                    MigrationLogic.Start(sb);

                    CultureInfoLogic.Start(sb);
                    FilePathEmbeddedLogic.Start(sb);
                    SmtpConfigurationLogic.Start(sb);
                    EmailLogic.Start(sb, () => Configuration.Value.Email, (et, target) => Configuration.Value.SmtpConfiguration);

                    AuthLogic.Start(sb, "System", null);

                    AuthLogic.StartAllModules(sb);
                    ResetPasswordRequestLogic.Start(sb);
                    UserTicketLogic.Start(sb);
                    SessionLogLogic.Start(sb);

                    ProcessLogic.Start(sb);
                    PackageLogic.Start(sb, packages: true, packageOperations: true);

                    SchedulerLogic.Start(sb);

                    QueryLogic.Start(sb);
                    UserQueryLogic.Start(sb);
                    UserQueryLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    UserQueryLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    ChartLogic.Start(sb);


                    UserChartLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    UserChartLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    DashboardLogic.Start(sb);
                    DashboardLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
                    DashboardLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
                    ViewLogLogic.Start(sb, new HashSet <Type> {
                        typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity)
                    });
                    DiffLogLogic.Start(sb, registerAll: true);
                    ExcelLogic.Start(sb, excelReport: true);
                    ToolbarLogic.Start(sb);

                    SMSLogic.Start(sb, null, () => Configuration.Value.Sms);
                    SMSLogic.RegisterPhoneNumberProvider <PersonEntity>(p => p.Phone, p => null);
                    SMSLogic.RegisterDataObjectProvider((PersonEntity p) => new { p.FirstName, p.LastName, p.Title, p.DateOfBirth });
                    SMSLogic.RegisterPhoneNumberProvider <CompanyEntity>(p => p.Phone, p => null);

                    NoteLogic.Start(sb, typeof(UserEntity), /*Note*/ typeof(OrderEntity));
                    AlertLogic.Start(sb, typeof(UserEntity), /*Alert*/ typeof(OrderEntity));
                    FileLogic.Start(sb);

                    TranslationLogic.Start(sb, countLocalizationHits: false);
                    TranslatedInstanceLogic.Start(sb, () => CultureInfo.GetCultureInfo("en"));

                    HelpLogic.Start(sb);
                    WordTemplateLogic.Start(sb);
                    MapLogic.Start(sb);
                    PredictorLogic.Start(sb, () => new FileTypeAlgorithm(f => new PrefixPair(Starter.Configuration.Value.Folders.PredictorModelFolder)));
                    PredictorLogic.RegisterAlgorithm(CNTKPredictorAlgorithm.NeuralNetwork, new CNTKNeuralNetworkPredictorAlgorithm());
                    PredictorLogic.RegisterPublication(ProductPredictorPublication.MonthlySales, new PublicationSettings(typeof(OrderEntity)));

                    RestLogLogic.Start(sb);
                    RestApiKeyLogic.Start(sb);

                    WorkflowLogicStarter.Start(sb, () => Starter.Configuration.Value.Workflow);

                    EmployeeLogic.Start(sb);
                    ProductLogic.Start(sb);
                    CustomerLogic.Start(sb);
                    OrderLogic.Start(sb);
                    ShipperLogic.Start(sb);

                    StartSouthwindConfiguration(sb);

                    TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.UserEntities, o => o.Employee == EmployeeEntity.Current);
                    TypeConditionLogic.Register <EmployeeEntity>(SouthwindGroup.UserEntities, e => EmployeeEntity.Current.Is(e));

                    TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.CurrentCustomer, o => o.Customer == CustomerEntity.Current);
                    TypeConditionLogic.Register <PersonEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);
                    TypeConditionLogic.Register <CompanyEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);

                    ProfilerLogic.Start(sb,
                                        timeTracker: true,
                                        heavyProfiler: true,
                                        overrideSessionTimeout: true);

                    DynamicLogic.StartDynamicModules(sb);
                    DynamicLogic.RegisterExceptionIfAny();

                    SetupCache(sb);

                    Schema.Current.OnSchemaCompleted();
                }
        }
Beispiel #23
0
        public static void Start(string connectionString, bool isPostgres, bool includeDynamic = true, bool detectSqlVersion = true)
        {
            using (HeavyProfiler.Log("Start"))
                using (var initial = HeavyProfiler.Log("Initial"))
                {
                    StartParameters.IgnoredDatabaseMismatches = new List <Exception>();
                    StartParameters.IgnoredCodeErrors         = new List <Exception>();

                    string?logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log");

                    SchemaBuilder sb = new CustomSchemaBuilder {
                        LogDatabaseName = logDatabase, Tracer = initial
                    };
                    sb.Schema.Version          = typeof(Starter).Assembly.GetName().Version !;
                    sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US");

                    MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>();
                    MixinDeclarations.Register <UserEntity, UserEmployeeMixin>();
                    MixinDeclarations.Register <OrderDetailEmbedded, OrderDetailMixin>();
                    MixinDeclarations.Register <BigStringEmbedded, BigStringMixin>();

                    ConfigureBigString(sb);
                    OverrideAttributes(sb);

                    if (!isPostgres)
                    {
                        var sqlVersion = detectSqlVersion ? SqlServerVersionDetector.Detect(connectionString) : SqlServerVersion.AzureSQL;
                        Connector.Default = new SqlServerConnector(connectionString, sb.Schema, sqlVersion !.Value);
                    }
                    else
                    {
                        var postgreeVersion = detectSqlVersion ? PostgresVersionDetector.Detect(connectionString) : null;
                        Connector.Default = new PostgreSqlConnector(connectionString, sb.Schema, postgreeVersion);
                    }

                    CacheLogic.Start(sb, cacheInvalidator: sb.Settings.IsPostgres ? new PostgresCacheInvalidation() : null);

                    DynamicLogicStarter.Start(sb);
                    if (includeDynamic)//Dynamic
                    {
                        DynamicLogic.CompileDynamicCode();

                        DynamicLogic.RegisterMixins();
                        DynamicLogic.BeforeSchema(sb);
                    }//Dynamic

                    // Framework modules

                    TypeLogic.Start(sb);

                    OperationLogic.Start(sb);
                    ExceptionLogic.Start(sb);
                    QueryLogic.Start(sb);

                    // Extensions modules

                    MigrationLogic.Start(sb);

                    CultureInfoLogic.Start(sb);
                    FilePathEmbeddedLogic.Start(sb);
                    BigStringLogic.Start(sb);
                    EmailLogic.Start(sb, () => Configuration.Value.Email, (template, target, message) => Configuration.Value.EmailSender);

                    AuthLogic.Start(sb, "System", "Anonymous"); /* null); anonymous*/

                    AuthLogic.StartAllModules(sb);
                    ResetPasswordRequestLogic.Start(sb);
                    UserTicketLogic.Start(sb);
                    SessionLogLogic.Start(sb);
                    WebAuthnLogic.Start(sb, () => Configuration.Value.WebAuthn);

                    ProcessLogic.Start(sb);
                    PackageLogic.Start(sb, packages: true, packageOperations: true);

                    SchedulerLogic.Start(sb);
                    OmniboxLogic.Start(sb);

                    UserQueryLogic.Start(sb);
                    UserQueryLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    UserQueryLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    UserQueryLogic.RegisterTranslatableRoutes();

                    ChartLogic.Start(sb, googleMapsChartScripts: false /*requires Google Maps API key in ChartClient */);
                    UserChartLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    UserChartLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    UserChartLogic.RegisterTranslatableRoutes();

                    DashboardLogic.Start(sb);
                    DashboardLogic.RegisterUserTypeCondition(sb, RG2Group.UserEntities);
                    DashboardLogic.RegisterRoleTypeCondition(sb, RG2Group.RoleEntities);
                    DashboardLogic.RegisterTranslatableRoutes();
                    ViewLogLogic.Start(sb, new HashSet <Type> {
                        typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity)
                    });
                    DiffLogLogic.Start(sb, registerAll: true);
                    ExcelLogic.Start(sb, excelReport: true);
                    ToolbarLogic.Start(sb);
                    ToolbarLogic.RegisterTranslatableRoutes();
                    FileLogic.Start(sb);

                    TranslationLogic.Start(sb, countLocalizationHits: false);
                    TranslatedInstanceLogic.Start(sb, () => CultureInfo.GetCultureInfo("en"));

                    HelpLogic.Start(sb);
                    WordTemplateLogic.Start(sb);
                    MapLogic.Start(sb);
                    RestLogLogic.Start(sb);
                    RestApiKeyLogic.Start(sb);

                    WorkflowLogicStarter.Start(sb, () => Starter.Configuration.Value.Workflow);

                    ProfilerLogic.Start(sb,
                                        timeTracker: true,
                                        heavyProfiler: true,
                                        overrideSessionTimeout: true);

                    // RG2 modules

                    EmployeeLogic.Start(sb);
                    ProductLogic.Start(sb);
                    CustomerLogic.Start(sb);
                    OrderLogic.Start(sb);
                    ShipperLogic.Start(sb);
                    ItemLogic.Start(sb);
                    ItemCategoryLogic.Start(sb);

                    StartRG2Configuration(sb);

                    TypeConditionLogic.Register <OrderEntity>(RG2Group.UserEntities, o => o.Employee == EmployeeEntity.Current);
                    TypeConditionLogic.Register <EmployeeEntity>(RG2Group.UserEntities, e => EmployeeEntity.Current.Is(e));

                    TypeConditionLogic.Register <OrderEntity>(RG2Group.CurrentCustomer, o => o.Customer == CustomerEntity.Current);
                    TypeConditionLogic.Register <PersonEntity>(RG2Group.CurrentCustomer, o => o == CustomerEntity.Current);
                    TypeConditionLogic.Register <CompanyEntity>(RG2Group.CurrentCustomer, o => o == CustomerEntity.Current);

                    if (includeDynamic)//2
                    {
                        DynamicLogic.StartDynamicModules(sb);
                    }//2

                    SetupCache(sb);

                    Schema.Current.OnSchemaCompleted();

                    if (includeDynamic)//3
                    {
                        DynamicLogic.RegisterExceptionIfAny();
                    }//3
                }
        }
Beispiel #24
0
        public override bool ValidMovement(BoardLogic.ChessCoordinates startLocation, BoardLogic.ChessCoordinates endLocation)
        {
            ValidMoves.Clear();

            int column = FileLogic.GetColumnFromChar(startLocation.Column).GetHashCode();
            int row    = startLocation.Row;

            if (row - 1 >= 0)
            {
                int goingDown = row;
                while (true)
                {
                    if (goingDown - 1 >= 0)
                    {
                        BoardLogic.ChessCoordinates maybeGood = CheckSpaces(Program.board[column, goingDown - 1], startLocation);
                        if (maybeGood == new BoardLogic.ChessCoordinates('0', -1, null))
                        {
                            break;
                        }
                        else
                        {
                            ValidMoves.Add(maybeGood);
                            goingDown = goingDown - 1;
                            if (shouldStop)
                            {
                                shouldStop = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (row + 1 <= 7)
            {
                int goingUp = row;
                while (true)
                {
                    if (goingUp + 1 <= 7)
                    {
                        BoardLogic.ChessCoordinates maybeGood = CheckSpaces(Program.board[column, goingUp + 1], startLocation);
                        if (maybeGood == new BoardLogic.ChessCoordinates('0', -1, null))
                        {
                            break;
                        }
                        else
                        {
                            ValidMoves.Add(maybeGood);
                            goingUp = goingUp + 1;
                            if (shouldStop)
                            {
                                shouldStop = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (column - 1 >= 0)
            {
                int goingLeft = column;
                while (true)
                {
                    if (goingLeft - 1 >= 0)
                    {
                        BoardLogic.ChessCoordinates maybeGood = CheckSpaces(Program.board[goingLeft - 1, row], startLocation);
                        Console.WriteLine(maybeGood);
                        if (maybeGood == new BoardLogic.ChessCoordinates('0', -1, null))
                        {
                            break;
                        }
                        else
                        {
                            ValidMoves.Add(maybeGood);
                            goingLeft = goingLeft - 1;
                            if (shouldStop)
                            {
                                shouldStop = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (column + 1 <= 7)
            {
                int goingRight = column;
                while (true)
                {
                    if (goingRight + 1 <= 7)
                    {
                        BoardLogic.ChessCoordinates maybeGood = CheckSpaces(Program.board[goingRight + 1, row], startLocation);
                        if (maybeGood == new BoardLogic.ChessCoordinates('0', -1, null))
                        {
                            break;
                        }
                        else
                        {
                            ValidMoves.Add(maybeGood);
                            goingRight = goingRight + 1;
                            if (shouldStop)
                            {
                                shouldStop = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            BoardLogic.ChessCoordinates lookingFor = new BoardLogic.ChessCoordinates(BoardLogic.GetCharFromNumber(FileLogic.GetColumnFromChar(endLocation.Column).GetHashCode()), endLocation.Row, null);

            foreach (var space in ValidMoves)
            {
                if (space == lookingFor)
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #25
0
 public FileController()
 {
     logic  = new FileLogic();
     logger = LogManager.GetCurrentClassLogger();
 }
Beispiel #26
0
        public override bool ValidMovement(BoardLogic.ChessCoordinates startLocation, BoardLogic.ChessCoordinates endLocation)
        {
            //validate movement eventually
            ValidMoves.Clear();

            int column = FileLogic.GetColumnFromChar(startLocation.Column).GetHashCode();
            int row    = startLocation.Row;

            if (Program.board[column, row].Piece.IsLight)
            {
                if (column - 1 >= 0)
                {
                    if (Program.board[column - 1, row].Piece == null)
                    {
                        ValidMoves.Add(Program.board[column - 1, row]);
                        if (column == 6)
                        {
                            if (Program.board[column - 2, row].Piece == null)
                            {
                                ValidMoves.Add(Program.board[column - 2, row]);
                            }
                        }
                    }
                    if (row - 1 >= 0 && Program.board[column - 1, row - 1].Piece != null && Program.board[column - 1, row - 1].Piece.IsLight != Program.board[column, row].Piece.IsLight)
                    {
                        ValidMoves.Add(Program.board[column - 1, row - 1]);
                    }
                    if (row + 1 <= 7 && Program.board[column - 1, row + 1].Piece != null && Program.board[column - 1, row + 1].Piece.IsLight != Program.board[column, row].Piece.IsLight)
                    {
                        ValidMoves.Add(Program.board[column - 1, row + 1]);
                    }
                }
            }
            else if (!Program.board[column, row].Piece.IsLight)
            {
                if (column + 1 <= 7)
                {
                    if (Program.board[column + 1, row].Piece == null)
                    {
                        ValidMoves.Add(Program.board[column + 1, row]);
                        if (column == 1)
                        {
                            if (Program.board[column + 2, row].Piece == null)
                            {
                                ValidMoves.Add(Program.board[column + 2, row]);
                            }
                        }
                    }
                    if (row - 1 >= 0 && Program.board[column + 1, row - 1].Piece != null && Program.board[column + 1, row - 1].Piece.IsLight != Program.board[column, row].Piece.IsLight)
                    {
                        ValidMoves.Add(Program.board[column + 1, row - 1]);
                    }
                    if (row + 1 <= 7 && Program.board[column + 1, row + 1].Piece != null && Program.board[column + 1, row + 1].Piece.IsLight != Program.board[column, row].Piece.IsLight)
                    {
                        ValidMoves.Add(Program.board[column + 1, row + 1]);
                    }
                }
            }
            BoardLogic.ChessCoordinates lookingFor = new BoardLogic.ChessCoordinates(BoardLogic.GetCharFromNumber(FileLogic.GetColumnFromChar(endLocation.Column).GetHashCode()), endLocation.Row, null);
            //BoardLogic.ChessCoordinates lookingFor2 = new BoardLogic.ChessCoordinates(BoardLogic.GetCharFromNumber(endLocation.Row), FileLogic.GetColumnFromChar(endLocation.Column).GetHashCode(), null);

            foreach (var space in ValidMoves)
            {
                if (space == lookingFor)
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #27
0
        /// <summary>
        /// Extract all items in a path to create a CSV file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Extract_Click(object sender, RoutedEventArgs e)
        {
            string localPath = @Tb_LocalPath.Text;

            #region UserInput checks
            if (localPath == "")
            {
                MessageBox.Show("Please fill the local path field");
                return;
            }
            if (!Directory.Exists(localPath))
            {
                MessageBox.Show("Cannot find local path, please double check");
                return;
            }

            /*
             * if (Cb_doclib.SelectedItem == null)
             * {
             *  MessageBox.Show("Please select a document library");
             *  return;
             * }*/
            #endregion

            // We retrieve the source folder information to compute the extract file path and create it
            DirectoryInfo sourceFolder = new DirectoryInfo(localPath);
            Reporting     extractCSV   = new Reporting(sourceFolder.Name);

            //We retrive the list of DirectoryInfo and FileInfo
            List <FileInfo>      files   = FileLogic.getFiles(localPath);
            List <DirectoryInfo> folders = FileLogic.getSourceFolders(localPath);

            // We loop every files then folders to create a file mapping and extrat metadata to a csv file
            foreach (FileInfo file in files)
            {
                FileMapping filemap = new FileMapping
                {
                    Name     = file.Name,
                    Path     = file.FullName,
                    Modified = file.LastWriteTimeUtc,
                    Created  = file.CreationTimeUtc,
                    Owner    = File.GetAccessControl(file.FullName).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(),
                    ItemType = FileMapping.Type.File
                };
                extractCSV.writeExtract(filemap);
            }

            foreach (DirectoryInfo dir in folders)
            {
                FileMapping filemap = new FileMapping
                {
                    Name     = dir.Name,
                    Path     = dir.FullName,
                    Modified = dir.LastWriteTimeUtc,
                    Created  = dir.CreationTimeUtc,
                    Owner    = File.GetAccessControl(dir.FullName).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(),
                    ItemType = FileMapping.Type.Folder
                };
                extractCSV.writeExtract(filemap);
            }
            MessageBox.Show("Extraction done");
        }
Beispiel #28
0
        // Extra
        public ActionResult Copy([FromBody] ApiCopyFile model)
        {
            if (string.IsNullOrEmpty(model.RelativePathToDirectory))
            {
                model.RelativePathToDirectory = "";
            }

            if (string.IsNullOrEmpty(model.FileName))
            {
                // directory move
                if (string.IsNullOrEmpty(model.RelativePathToDirectory))
                {
                    // You cannot copy the root directory
                    return(StatusCode(403));
                }

                var fullOriginalPath = this.GetAbsoluteDirectoryPath(model.RelativePathToDirectory);
                if (!ResolvedPathIsValid(fullOriginalPath))
                {
                    // User may be attempting to view "Up" directories -- app should only let people view "Down"
                    return(StatusCode(403));
                }

                // Directory copy needs to go to the current "Parent"
                // So copying directory C to D with structure a/b/c/ would yield
                // a/b/c
                // a/b/d
                var fullDestinationPath = this.GetAbsoluteDirectoryPath(Path.Join(model.RelativePathToDirectory, "../", model.CopyName));
                if (!ResolvedPathIsValid(fullDestinationPath))
                {
                    // User may be attempting to view "Up" directories -- app should only let people view "Down"
                    return(StatusCode(403));
                }

                if (!System.IO.Directory.Exists(fullOriginalPath))
                {
                    return(NotFound(new ApiError("The file you are requesting to move does not exist")));
                }

                if (System.IO.Directory.Exists(fullDestinationPath))
                {
                    // In "real" production circumstances, I would figure out if we can just replace the file or increment its filename
                    return(Conflict(new ApiError("There is already a file in the destination directory with that name. Delete that file and try again")));
                }

                FileLogic.DirectoryCopy(fullOriginalPath, fullDestinationPath);
            }
            else
            {
                // file move
                var fullOriginalPath = this.GetAbsoluteFilePath(model.RelativePathToDirectory, model.FileName);
                if (!ResolvedPathIsValid(fullOriginalPath))
                {
                    // User may be attempting to view "Up" directories -- app should only let people view "Down"
                    return(StatusCode(403));
                }

                var fullDestinationPath = this.GetAbsoluteFilePath(model.RelativePathToDirectory, model.CopyName);
                if (!ResolvedPathIsValid(fullDestinationPath))
                {
                    // User may be attempting to view "Up" directories -- app should only let people view "Down"
                    return(StatusCode(403));
                }

                if (!System.IO.File.Exists(fullOriginalPath))
                {
                    return(NotFound(new ApiError("The file you are requesting to move does not exist")));
                }

                if (System.IO.File.Exists(fullDestinationPath))
                {
                    // In "real" production circumstances, I would figure out if we can just replace the file or increment its filename
                    return(Conflict(new ApiError("There is already a file in the destination directory with that name. Delete that file and try again")));
                }

                System.IO.File.Copy(fullOriginalPath, fullDestinationPath);
            }

            return(Ok());
        }
        /// <summary>
        /// Saving the new configuration
        /// </summary>
        private void saveConfiguration()
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            DumpType dtype   = DumpType.File;     //default value
            String   svalue  = String.Empty;      //define the way where the xml will be dropped
            WcfType  binding = WcfType.NamedPipe; //default value

            if (!FileSelected && !MsmqSelected && !WcfSelected)
            {
                Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
                MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.SelectType));
                return;
            }
            //retrieve the current dump layer
            if (FileSelected)
            {
                dtype  = DumpType.File;
                svalue = FolderPath;
                //test if the folder exist
                if (!FileLogic.IsValidPathFolder(svalue))
                {
                    Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
                    MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.ValidFolderPath));
                    return;
                }
            }

            if (MsmqSelected)
            {
                dtype  = DumpType.Msmq;
                svalue = MsmqPath;

                if (!MsmqLayer.IsExist(svalue))
                {
                    Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
                    MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.ValidMsmqPath));
                    return;
                }
            }

            if (WcfSelected)
            {
                dtype  = DumpType.Wcf;
                svalue = WcfUri;

                if (!Enum.TryParse <WcfType>(SelectedBindingType, out binding))
                {
                    Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
                    MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.ValidWcfBinding));
                    return;
                }

                if (String.IsNullOrEmpty(svalue))
                {
                    Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
                    MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.ValidWcfUri));
                    return;
                }
            }

            _editor.updateConfigurationFile(dtype, svalue, binding);
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;

            if (dtype == DumpType.Wcf)
            {
                MessageBox.Show(String.Format(ResourceLogic.GetString(ResourceKeyName.WcfPortCreation), binding.ToString()));
            }

            //confguration is applied so just apply show mode
            ConfigChange = false;

            MessageBox.Show(ResourceLogic.GetString(ResourceKeyName.ConfigurationSaved));
        }
Beispiel #30
0
        public static void Start(string connectionString)
        {
            string logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log");

            SchemaBuilder sb = new SchemaBuilder();

            sb.Schema.Version          = typeof(Starter).Assembly.GetName().Version;
            sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US");

            MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>();
            MixinDeclarations.Register <UserEntity, UserEmployeeMixin>();

            OverrideAttributes(sb);

            SetupDisconnectedStrategies(sb);

            DynamicQueryManager dqm = new DynamicQueryManager();

            Connector.Default = new SqlConnector(connectionString, sb.Schema, dqm, SqlServerVersion.SqlServer2012);

            CacheLogic.Start(sb);

            TypeLogic.Start(sb, dqm);

            OperationLogic.Start(sb, dqm);

            MigrationLogic.Start(sb, dqm);

            CultureInfoLogic.Start(sb, dqm);
            EmbeddedFilePathLogic.Start(sb, dqm);
            SmtpConfigurationLogic.Start(sb, dqm);
            EmailLogic.Start(sb, dqm, () => Configuration.Value.Email, et => Configuration.Value.SmtpConfiguration);

            AuthLogic.Start(sb, dqm, "System", null);

            AuthLogic.StartAllModules(sb, dqm);
            ResetPasswordRequestLogic.Start(sb, dqm);
            UserTicketLogic.Start(sb, dqm);
            SessionLogLogic.Start(sb, dqm);

            ProcessLogic.Start(sb, dqm);
            PackageLogic.Start(sb, dqm, packages: true, packageOperations: true);

            MapLogic.Start(sb, dqm);
            SchedulerLogic.Start(sb, dqm);

            QueryLogic.Start(sb);
            UserQueryLogic.Start(sb, dqm);
            UserQueryLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
            UserQueryLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
            ChartLogic.Start(sb, dqm);
            UserChartLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
            UserChartLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
            DashboardLogic.Start(sb, dqm);
            DashboardLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities);
            DashboardLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities);
            ViewLogLogic.Start(sb, dqm, new HashSet <Type> {
                typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity)
            });
            DiffLogLogic.Start(sb, dqm);

            ExceptionLogic.Start(sb, dqm);

            SMSLogic.Start(sb, dqm, null, () => Configuration.Value.Sms);
            SMSLogic.RegisterPhoneNumberProvider <PersonEntity>(p => p.Phone, p => null);
            SMSLogic.RegisterDataObjectProvider((PersonEntity p) => new { p.FirstName, p.LastName, p.Title, p.DateOfBirth });
            SMSLogic.RegisterPhoneNumberProvider <CompanyEntity>(p => p.Phone, p => null);

            NoteLogic.Start(sb, dqm, typeof(UserEntity), /*Note*/ typeof(OrderEntity));
            AlertLogic.Start(sb, dqm, typeof(UserEntity), /*Alert*/ typeof(OrderEntity));
            FileLogic.Start(sb, dqm);

            TranslationLogic.Start(sb, dqm);
            TranslatedInstanceLogic.Start(sb, dqm, () => CultureInfo.GetCultureInfo("en"));

            HelpLogic.Start(sb, dqm);
            WordTemplateLogic.Start(sb, dqm);

            EmployeeLogic.Start(sb, dqm);
            ProductLogic.Start(sb, dqm);
            CustomerLogic.Start(sb, dqm);
            OrderLogic.Start(sb, dqm);
            ShipperLogic.Start(sb, dqm);

            StartSouthwindConfiguration(sb, dqm);

            TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.UserEntities, o => o.Employee.RefersTo(EmployeeEntity.Current));
            TypeConditionLogic.Register <EmployeeEntity>(SouthwindGroup.UserEntities, e => e == EmployeeEntity.Current);

            TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.CurrentCustomer, o => o.Customer == CustomerEntity.Current);
            TypeConditionLogic.Register <PersonEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);
            TypeConditionLogic.Register <CompanyEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current);

            DisconnectedLogic.Start(sb, dqm);
            DisconnectedLogic.BackupFolder        = @"D:\SouthwindTemp\Backups";
            DisconnectedLogic.BackupNetworkFolder = @"D:\SouthwindTemp\Backups";
            DisconnectedLogic.DatabaseFolder      = @"D:\SouthwindTemp\Database";

            ProfilerLogic.Start(sb, dqm,
                                timeTracker: true,
                                heavyProfiler: true,
                                overrideSessionTimeout: true);

            SetupCache(sb);

            SetSchemaNames(Schema.Current);

            if (logDatabase.HasText())
            {
                SetLogDatabase(sb.Schema, new DatabaseName(null, logDatabase));
            }

            Schema.Current.OnSchemaCompleted();
        }