Ejemplo n.º 1
0
 public frmUsersInAccounts(DocumentActions documentActions)
 {
     InitializeComponent();
     this.documentActions = documentActions;
     userIds = documentActions.RoutedToUsers.Select(x => x.Id).ToList();
     this.Init();
 }
Ejemplo n.º 2
0
        private async Task Detail(DocumentActions document)
        {
            if (document == null)
            {
                return;
            }
            UnitOfWork unitOfWork = new UnitOfWork();

            ActionTakenGridView.ShowLoadingPanel();
            var list = await new UnitOfWork().DocumentActionsRepo.Fetch(x =>
                                                                        x.RefId == document.RefId && x.TableName == document.TableName,
                                                                        orderBy: x => x.OrderByDescending(m => m.DateCreated), includeProperties: "RoutedToUsers").ToListAsync();

            if (document.TableName == "PurchaseRequests")
            {
                var po = await unitOfWork.PurchaseOrdersRepo.GetAsync(x => x.PRId == document.RefId);

                foreach (var i in po)
                {
                    foreach (var obr in i.Obligations)
                    {
                        list.AddRange(unitOfWork.DocumentActionsRepo.Get(x =>
                                                                         x.RefId == obr.Id && x.TableName == "Obligations"));
                    }
                }
            }


            this.ActionTakenGridControl.DataSource = list;

            ActionTakenGridView.HideLoadingPanel();
        }
Ejemplo n.º 3
0
 public FilterReplicatedDocs(DocumentActions docActions, ReplicationStrategy strategy, PrefetchingBehavior prefetchingBehavior, string destinationId, Etag lastEtag)
 {
     this.docActions          = docActions;
     this.strategy            = strategy;
     this.prefetchingBehavior = prefetchingBehavior;
     this.destinationId       = destinationId;
     this.lastEtag            = lastEtag;
 }
Ejemplo n.º 4
0
 private void Detail(DocumentActions document)
 {
     if (document == null)
     {
         return;
     }
     this.ActionTakenGridControl.DataSource =
         new UnitOfWork().DocumentActionsRepo.Get(x =>
                                                  x.RefId == document.RefId && x.TableName == document.TableName, orderBy: x => x.OrderByDescending(m => m.DateCreated));
 }
Ejemplo n.º 5
0
        private async Task MakeWorkAsync(string filePath)
        {
            _threadCount++;
            try
            {
                if (await _dbInstance.CheckMongoConnection())
                {
                    if (!await _dbInstance.IsFileInDbAsync(FileActions.FileHash(filePath)))
                    {
                        var documentTfIdfDict = await DocumentActions.MakeTfIdfVectorAsync(
                            DocumentActions.MakeTfVector(DocumentActions.GetWordCanonedTokens(filePath)));

                        var allDocuments = await _dbInstance.GetAllDocumentsAsync();

                        var cosineSimilarityList = new List <double>();

                        var similarityDocuments = new List <PlagiarismDetectExpandedResult>();

                        foreach (var document in allDocuments)
                        {
                            var currentDocumentTfIdfDict = await DocumentActions.MakeTfIdfVectorAsync(
                                document.DocumentTfVector);

                            var vectors = MakeVectorsForCompare(currentDocumentTfIdfDict, documentTfIdfDict);

                            var cosineSim = Cosine_similarity(vectors.Item1, vectors.Item2);

                            cosineSimilarityList.Add(cosineSim);

                            if (cosineSim >= 0.4)
                            {
                                similarityDocuments.Add(new PlagiarismDetectExpandedResult(document.DocumentPath,
                                                                                           document.DocumentName, cosineSim));
                            }
                        }

                        M_Model.HandledFiles.Add(new PlagiarismDetectResult(Path.GetFileNameWithoutExtension(filePath),
                                                                            cosineSimilarityList.Max() * 100, similarityDocuments));
                    }
                    else
                    {
                        M_Model.HandledFiles.Add(new PlagiarismDetectResult(Path.GetFileNameWithoutExtension(filePath),
                                                                            100));
                    }
                }
            }
            catch (Exception e)
            {
                await Console.Error.WriteLineAsync(
                    "Не удалось подключиться к серверу MongoDb! \nВыполнение дальнейшей работы невозможно!\n" + e);

                StopProgramm();
            }
            _threadCount--;
        }
Ejemplo n.º 6
0
        public IHttpActionResult GetDetails([FromBody] DocumentActions item)
        {
            var list = new UnitOfWork().DocumentActionsRepo.Get(x =>
                                                                x.RefId == item.RefId && x.TableName == item.TableName)
                       .Select(x => new
            {
                x.DateCreated,
                x.ActionDate,
                x.CreatedBy,
                x.ActionTaken,
                CreatedByUsers = new ModelDb().Users.Where(m => m.Id == x.CreatedBy)
                                 .Select(m => new { FullName = m.FirstName + " " + m.LastName }).FirstOrDefault(),
                x.RouterUsers,
                x.Remarks,
                x.Programs,
                x.MainActivity,
                x.Activity,
                x.SubActivity
            })


                       .OrderByDescending(m => m.DateCreated).ToList();

            if (item.TableName == "PurchaseRequests")
            {
                var po = unitOfWork.PurchaseOrdersRepo.Get(x => x.PRId == item.RefId);

                foreach (var i in po)
                {
                    foreach (var obr in i.Obligations)
                    {
                        list.AddRange(unitOfWork.DocumentActionsRepo.Get(x =>
                                                                         x.RefId == obr.Id && x.TableName == "Obligations").Select(x => new
                        {
                            x.DateCreated,
                            x.ActionDate,
                            x.CreatedBy,
                            x.ActionTaken,
                            CreatedByUsers = new ModelDb().Users.Where(m => m.Id == x.CreatedBy)
                                             .Select(m => new { FullName = m.FirstName + " " + m.LastName }).FirstOrDefault(),
                            x.RouterUsers,
                            x.Remarks,
                            x.Programs,
                            x.MainActivity,
                            x.Activity,
                            x.SubActivity
                        }));
                    }
                }
            }
            return(Ok(list));
        }
Ejemplo n.º 7
0
        private void btnNewPO_Click(object sender, EventArgs e)
        {
            UnitOfWork unitOfWork = new UnitOfWork();

            documentActions = unitOfWork.DocumentActionsRepo.Find(x => x.Id == documentActions.Id);
            documentActions.RoutedToUsers.Clear();
            foreach (var i in userIds)
            {
                documentActions.RoutedToUsers.Add(unitOfWork.UsersRepo.Find(x => x.Id == i));
            }
            unitOfWork.Save();
            Close();
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Вставляет документ в MongoDB.
 /// </summary>
 /// <param name="document">Документ типа Document.</param>
 public void InsertDocument(Document document)
 {
     if (document != null)
     {
         InsertFileData(document.DocumentName, document.DocumentPath, document.DocumentType);
         InsertDocumentData(document.DocumentHash, document.DocumentAuthor, document.DocumentAuthorGroup,
                            document.DocumentTfVector, document.AddTime, document.DocumentTokens);
         UpdateOrInsertIdfVector(DocumentActions.MakeIdfVector(document.DocumentTfVector));
         LogViewModel.AddNewLog("Документ " + document.DocumentName + " добавлен!", DateTime.Now);
     }
     else
     {
         LogViewModel.AddNewLog("Документ не был передан для вставки!", DateTime.Now, LogType.Error);
     }
 }
Ejemplo n.º 9
0
        private void Detail()
        {
            try
            {
                UnitOfWork unitOfWork = new UnitOfWork();

                this.documentActionsBindingSource.DataSource =
                    unitOfWork.DocumentActionsRepo.Get(x => x.CreatedBy == User.UserId && x.RefId == document.RefId);
                this.usersBindingSource.DataSource = unitOfWork.UsersRepo.Get();
                document = unitOfWork.DocumentActionsRepo.Find(x => x.Id == document.Id);
                this.txtDocuement.Text       = document.Description;
                this.txtTask.Text            = document.Remarks;
                this.cboAssignedBy.EditValue = document.CreatedBy;
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 10
0
        private void btnTaskDone_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Do you want to submit this?", "Submit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
                UnitOfWork unitOfWork = new UnitOfWork();
                document = unitOfWork.DocumentActionsRepo.Find(x => x.Id == document.Id);
                if (cboActionDone.GetSelectedDataRow() is DocumentActions item)
                {
                    document.isDone   = true;
                    document.ActionId = item.Id;
                    unitOfWork.Save();
                }

                Close();
            }
            catch (Exception exception)
            {
            }
        }
Ejemplo n.º 11
0
        public DocumentDatabase(InMemoryRavenConfiguration configuration, TransportState transportState = null)
        {
            DocumentLock        = new PutSerialLock();
            Name                = configuration.DatabaseName;
            Configuration       = configuration;
            this.transportState = transportState ?? new TransportState();
            ExtensionsState     = new AtomicDictionary <object>();

            using (LogManager.OpenMappedContext("database", Name ?? Constants.SystemDatabase))
            {
                Log.Debug("Start loading the following database: {0}", Name ?? Constants.SystemDatabase);

                initializer = new DocumentDatabaseInitializer(this, configuration);

                initializer.InitializeEncryption();
                initializer.ValidateLicense();

                initializer.SubscribeToDomainUnloadOrProcessExit();
                initializer.ExecuteAlterConfiguration();
                initializer.SatisfyImportsOnce();

                backgroundTaskScheduler = configuration.CustomTaskScheduler ?? TaskScheduler.Default;


                recentTouches = new SizeLimitedConcurrentDictionary <string, TouchedDocumentInfo>(configuration.MaxRecentTouchesToRemember, StringComparer.OrdinalIgnoreCase);

                configuration.Container.SatisfyImportsOnce(this);

                workContext = new WorkContext
                {
                    Database            = this,
                    DatabaseName        = Name,
                    IndexUpdateTriggers = IndexUpdateTriggers,
                    ReadTriggers        = ReadTriggers,
                    TaskScheduler       = backgroundTaskScheduler,
                    Configuration       = configuration,
                    IndexReaderWarmers  = IndexReaderWarmers
                };

                try
                {
                    uuidGenerator = new SequentialUuidGenerator();
                    initializer.InitializeTransactionalStorage(uuidGenerator);
                    lastCollectionEtags = new LastCollectionEtags(TransactionalStorage, WorkContext);
                }
                catch (Exception)
                {
                    if (TransactionalStorage != null)
                    {
                        TransactionalStorage.Dispose();
                    }
                    throw;
                }

                try
                {
                    TransactionalStorage.Batch(actions => uuidGenerator.EtagBase = actions.General.GetNextIdentityValue("Raven/Etag"));

                    // Index codecs must be initialized before we try to read an index
                    InitializeIndexCodecTriggers();
                    initializer.InitializeIndexStorage();

                    Attachments   = new AttachmentActions(this, recentTouches, uuidGenerator, Log);
                    Documents     = new DocumentActions(this, recentTouches, uuidGenerator, Log);
                    Indexes       = new IndexActions(this, recentTouches, uuidGenerator, Log);
                    Maintenance   = new MaintenanceActions(this, recentTouches, uuidGenerator, Log);
                    Notifications = new NotificationActions(this, recentTouches, uuidGenerator, Log);
                    Patches       = new PatchActions(this, recentTouches, uuidGenerator, Log);
                    Queries       = new QueryActions(this, recentTouches, uuidGenerator, Log);
                    Tasks         = new TaskActions(this, recentTouches, uuidGenerator, Log);
                    Transformers  = new TransformerActions(this, recentTouches, uuidGenerator, Log);

                    inFlightTransactionalState = TransactionalStorage.GetInFlightTransactionalState(Documents.Put, Documents.Delete);

                    CompleteWorkContextSetup();

                    prefetcher       = new Prefetcher(workContext);
                    indexingExecuter = new IndexingExecuter(workContext, prefetcher);

                    RaiseIndexingWiringComplete();

                    InitializeTriggersExceptIndexCodecs();
                    SecondStageInitialization();
                    ExecuteStartupTasks();
                    lastCollectionEtags.Initialize();

                    Log.Debug("Finish loading the following database: {0}", configuration.DatabaseName ?? Constants.SystemDatabase);
                }
                catch (Exception)
                {
                    Dispose();
                    throw;
                }
            }
        }
Ejemplo n.º 12
0
 public frmTaskDone(DocumentActions document)
 {
     InitializeComponent();
     this.document = document;
     this.Detail();
 }
Ejemplo n.º 13
0
        //main programm methods

        /// <summary>
        /// Старт программы.
        /// </summary>
        private async void StartProgramm()
        {
            //Если по старту программы, сервер MongoDb не работает или не доступен
            //то, прерываем программу
            if (!await DataBase.GetInstance().CheckMongoConnection())
            {
                StopProgramm(true);
                return;
            }

            //Обработчик тика "главного" таймера (AutoWorkTimer). Вызывается раз в час
            //и добавляет данные.
            EventHandler autoWorkHandler = (sender, args) =>
            {
                //При нажатии кнопки "старт" сама кнопка блокируется, а кнопка "стоп" становится доступной
                DocumentAdderModel.IsStartBtnEnabled = false;
                DocumentAdderModel.IsStopBtnEnabled  = true;

                //Получаем пути файлов из репозитория.
                var filePaths = DocumentActions.GetFilePaths();

                //Получаем энумератор, для асинхронного (параллельного) "прохождения" по коллекции файлов.
                if (filePaths == null)
                {
                    return;
                }
                var filePathEnumerator = filePaths.GetEnumerator();

                //Поскольку программа работает параллельно, то выполнение потоков нужно отслеживать,
                //для этого создаем еще один таймер.
                //Смотрится экономнее в сравнении с циклом (while(true))
                var makeWorkTimer = new DispatcherTimer {
                    Interval = TimeSpan.FromSeconds(15)
                };

                //Обработчик "локального" таймера. Отслеживает количество потоков и количество оставшихся файлов.
                EventHandler makeWorkHandler = async(mwSender, mwArgs) =>
                {
                    //Если текущее количество выполняемых потоков больше определенного количества
                    //(указывается в настройках), то текущий "тик" можно пропустить.
                    if (_threadCount >= ProgramSettings.GetInstance().ThreadCount)
                    {
                        return;
                    }

                    //Цикл из количества доступных потоков, в которым идет обработка данных
                    for (; _threadCount < ProgramSettings.GetInstance().ThreadCount;)
                    {
                        //Проходимся по коллекции, если в ней еще есть файлы.
                        if (filePathEnumerator.MoveNext())
                        {
                            //Обрабатываем файлы
                            await MakeWork2Async(filePathEnumerator.Current);
                        }
                        //Если файлов не осталось - останавливаем "локальный" таймер и выходим из цикла.
                        else
                        {
                            makeWorkTimer.Stop();
                            break;
                        }
                    }
                };

                //Запускаем "локальный" таймер, привязывая к нему обработчик.
                makeWorkTimer.Tick += makeWorkHandler;
                makeWorkTimer.Start();
                makeWorkHandler(this, EventArgs.Empty);
            };

            //По нажатию кнопки старт мы запускаем "главный" таймер и программа начинает выполнять свою работу
            //сразу же.
            AutoWorkTimer.Tick += autoWorkHandler;
            AutoWorkTimer.Start();
            autoWorkHandler(this, EventArgs.Empty);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Обработка файла по указанному пути.
 /// </summary>
 /// <param name="filePath">Путь к файлу.</param>
 /// <returns></returns>
 private static async Task MakeWork2Async(string filePath)
 {
     //Проверяем состояние сервера MongoDb.
     if (await DataBase.GetInstance().CheckMongoConnection())
     {
         //Инкрементируем к-ство выполняемых потоков.
         ++_threadCount;
         if (!await DataBase.GetInstance().IsFileInDbAsync(FileActions.FileHash(filePath)))
         {
             var canonedTokens = DocumentActions.GetWordCanonedTokens(filePath);
             DocumentActions.Cyrillify(ref canonedTokens);
             var extension = Path.GetExtension(filePath);
             //эта переменная будет использоваться для занесения в базу пути файла и ее производных
             var newFilePath = filePath;
             //поскольку формат *.doc пересохраняется в *.docx после вызова метода GetWordCanonedTokens,
             //то при вставке документа в БД используется новый формат *.docx
             if (extension != null && extension.Equals(".doc"))
             {
                 newFilePath += "x";
             }
             newFilePath = FileActions.FileMoveOrDelete(newFilePath, FileActionType.RenameAndMove);
             var fileName = Path.GetFileNameWithoutExtension(filePath);
             //Здесь будут хранится данные из имени файла.
             string[] fileNameData;
             try
             {
                 fileNameData = DocumentActions.SplitFileName(fileName);
             }
             catch (FileNameFormatException ex)
             {
                 LogViewModel.AddNewLog(ex.Message + " " + fileName, DateTime.Now, LogType.Information);
                 fileNameData = new[]
                 {
                     "Undefined", //ФИО-автора
                     "Undefined", //Группа автора
                     fileName     //Название работы
                 };
             }
             //создаем новый документ <Document> для вставки в коллекцию
             var insertDoc = new Document(
                 fileNameData[2], //Здесь хранится имя документа
                 fileNameData[0], //Здесь хранится ФИО автора документа
                 fileNameData[1], //Здесь хранится группа автора документа
                 newFilePath,
                 Path.GetExtension(newFilePath),
                 FileActions.FileHash(newFilePath),
                 canonedTokens.ToArray(),
                 DocumentActions.MakeTfVector(canonedTokens),
                 File.GetLastWriteTime(newFilePath));
             //вставляем в БД
             await DataBase.GetInstance().InsertDocumentAsync(insertDoc);
         }
         else
         {
             var fileName = Path.GetFileNameWithoutExtension(filePath);
             LogViewModel.AddNewLog("Файл " + fileName + " уже есть в базе данных!", DateTime.Now, LogType.Information);
             FileActions.FileMoveOrDelete(filePath, FileActionType.MoveDuplicate);
         }
         --_threadCount;
     }
     else
     {
         StopProgramm(true);
     }
 }
Ejemplo n.º 15
0
 public frmDocActionChild(MethodType methodType, DocumentActions documentActions) : base(methodType, documentActions)
 {
 }