private void Run(object sender, RoutedEventArgs e)
 {
     KeyWordsPage.Visibility = Visibility.Hidden;
     ResultsPage.Visibility  = Visibility.Visible;
     OcrResults.ItemsSource  = _ocrResults;
     try
     {
         Task.Run(() =>
         {
             foreach (var file in _processingFiles)
             {
                 this.Dispatcher.Invoke(() =>
                 {
                     _ocrResults.Add(new OcrResults()
                     {
                         FileName = new FileInfo(file).Name, OcredText = "Processing..."
                     });
                     OcrResults.Items.Refresh();
                 });
                 _settings.FileName = file;
                 ServerHelper.UploadFileToServer(file);
                 var results = ServerHelper.GetOcrResults(_settings);
                 this.Dispatcher.Invoke(() =>
                 {
                     _ocrResults.RemoveAt(_ocrResults.Count - 1);
                     _ocrResults.AddRange(results);
                     OcrResults.Items.Refresh();
                 });
             }
         });
     }
     catch (Exception ex)
     {
         MessageBox.Show("ERROR\n" + ex.Message);
     }
 }
Example #2
0
        public void WriteVideoBytes(Media video)
        {
            //we need to save the file on file system
            if (video.Binary == null || !video.Binary.Any())
            {
                throw new mobSocialException("Can't write empty bytes for picture");
            }

            //get the directory path from the relative path
            var directoryPath = ServerHelper.GetLocalPathFromRelativePath(_mediaSettings.VideoSavePath);
            var fileExtension = PathUtility.GetFileExtensionFromContentType(video.MimeType);

            if (string.IsNullOrEmpty(video.SystemName))
            {
                video.SystemName = $"{Guid.NewGuid().ToString("n")}";
            }

            var proposedFileName = $"{video.SystemName}{fileExtension}";
            var filePath         = PathUtility.GetFileSavePath(directoryPath, proposedFileName);

            File.WriteAllBytes(filePath, video.Binary);

            //clear bytes
            video.Binary    = null;
            video.LocalPath = ServerHelper.GetRelativePathFromLocalPath(filePath);

            //create thumbnail for video
            var thumbnailRelativeFilePath = Path.Combine(_mediaSettings.PictureSavePath, video.SystemName + ".thumb.jpg");
            var thumbnailLocalFilePath    = ServerHelper.GetLocalPathFromRelativePath(thumbnailRelativeFilePath);

            //TODO: Generate thumbnails of different sizes to save bandwidth

            _videoProcessor.WriteVideoThumbnailPicture(filePath, thumbnailLocalFilePath);
            //store relative path in thumbnail path
            video.ThumbnailPath = thumbnailRelativeFilePath;
        }
Example #3
0
        public async Task Image([Summary("The user to show a banner for")] SocketGuildUser user = null)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed image on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (await ServerHelper.CheckIfContextIsDM(Context))
            {
                return;
            }

            if (user == null)
            {
                user = Context.Message.Author as SocketGuildUser;
            }

            var background = await _servers.GetBackground(user.Guild.Id);

            var memoryStream = await _bannerImageService.CreateImage(user, background);

            memoryStream.Seek(0, SeekOrigin.Begin);
            await Context.Channel.SendFileAsync(memoryStream, $"{user.Username}.png");
        }
Example #4
0
        private void ProcessUidList()
        {
            string lastErrorMessage = "";

            Platform.Log(LogLevel.Info, "Populating new images into study folder.. {0} to go", Context.WorkQueueUidList.Count);

            StudyProcessorContext context = new StudyProcessorContext(_destinationStudyStorage);

            // Load the rules engine
            context.SopProcessedRulesEngine = new ServerRulesEngine(ServerRuleApplyTimeEnum.SopProcessed, Context.WorkQueueItem.ServerPartitionKey);
            context.SopProcessedRulesEngine.AddOmittedType(ServerRuleTypeEnum.SopCompress);
            context.SopProcessedRulesEngine.Load();

            // Add the update commands to
            context.UpdateCommands.AddRange(BuildUpdateCommandList());

            // Add command to update the Series & Sop Instances.
            context.UpdateCommands.Add(new SeriesSopUpdateCommand(Context.WorkQueueItemStudyStorage, _destinationStudyStorage, UidMapper));

            // Load the Study XML File
            StudyXml xml = LoadStudyXml(_destinationStudyStorage);

            PrintUpdateCommands(context.UpdateCommands);
            foreach (WorkQueueUid uid in Context.WorkQueueUidList)
            {
                // Load the file outside the try/catch block so it can be
                // referenced in the c
                string    imagePath = GetReconcileUidPath(uid);
                DicomFile file      = new DicomFile(imagePath);

                try
                {
                    file.Load();

                    string groupID = ServerHelper.GetUidGroup(file, Context.Partition, Context.WorkQueueItem.InsertTime);

                    SopInstanceProcessor sopProcessor = new SopInstanceProcessor(context)
                    {
                        EnforceNameRules = true
                    };

                    ProcessingResult result = sopProcessor.ProcessFile(groupID, file, xml, false, true, uid, GetReconcileUidPath(uid),
                                                                       SopInstanceProcessorSopType.NewSop);
                    if (result.Status != ProcessingStatus.Success)
                    {
                        throw new ApplicationException(String.Format("Unable to reconcile image {0}", file.Filename));
                    }

                    _processedCount++;

                    Platform.Log(ServerPlatform.InstanceLogLevel, "Reconciled SOP {0} [{1} of {2}]", uid.SopInstanceUid, _processedCount, Context.WorkQueueUidList.Count);
                }
                catch (Exception e)
                {
                    Platform.Log(LogLevel.Error, e, "Error occurred when processing uid {0}", uid.SopInstanceUid);

                    if (e is InstanceAlreadyExistsException ||
                        e.InnerException != null && e.InnerException is InstanceAlreadyExistsException)
                    {
                        // TODO (Rigel) - Check if we should include the WorkItemData to insert into the WorkQueue here.
                        DuplicateSopProcessorHelper.CreateDuplicateSIQEntry(file, _destinationStudyStorage, GetReconcileUidPath(uid),
                                                                            Context.WorkQueueItem, uid, null);
                    }
                    else
                    {
                        lastErrorMessage = e.Message;
                        SopInstanceProcessor.FailUid(uid, true);
                    }
                    _failedCount++;
                }
            }

            if (_processedCount == 0)
            {
                throw new ApplicationException(lastErrorMessage);
            }
        }
Example #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void cleanTheDatabase()
        public virtual void CleanTheDatabase()
        {
            ServerHelper.cleanTheDatabase(SharedServerTestBase.server());
        }
        // Se agrega esta funcion para asignar el trabajo una sola vez, y despues dentro de "ValidarToken()" solo se llama a la misma.
        private void ValidarTokenBackGruondWorker()
        {
            backgroundWorker.DoWork += (s, e) =>
            {
                ProgressBar.Dispatcher.Invoke(progressBarDelegate, Visibility.Visible);
                //IconoValidarToken.Dispatcher.Invoke(iconoTokenDelegate,Visibility.Hidden);
                //DNITextBox.Dispatcher.Invoke(dNIPacienteDelegate,Visibility.Hidden);
                //SesionTextBox.Dispatcher.Invoke(sesionPacienteDelegate,Visibility.Hidden);
                //ValidarTokenBtn.Dispatcher.Invoke(tokenButtonDelegate,Visibility.Hidden);
                // Thread.Sleep(5000); // Es solo para ver como queda la animacion este sleep.
                // Valido el token DNI + Sesion
                RespuestaToken = ServerHelper.ValidarToken(Sesion.Token);
                var result = RespuestaToken;
                Sesion.TokenVerificado = true;
                // Muestro el Snackbar
                switch (result.CodigoTokenValid)
                {
                case ServerHelper.TOKEN_SINCONEXION:
                    Snackbar.Dispatcher.Invoke(snackBarDelegate, "No hay conexión a internet para validar el token.");
                    EstadoVentanaLabel.Dispatcher.Invoke(estadoGeneralDelegate, "Sin conexión");
                    DificultadRatingBar.Dispatcher.Invoke(ratingBarDelegate, Visibility.Hidden);
                    SinConexiónTextBlock.Dispatcher.Invoke(sinConexionTextBlockDelegate, Visibility.Visible);
                    SinConexionCard.Dispatcher.Invoke(sinConexionCardDelegate, Visibility.Visible);
                    IniRehabBtn.Dispatcher.Invoke(iniRehabBtnDelegate, true);
                    Sesion.TokenValido = false;
                    break;

                case ServerHelper.TOKEN_INVALIDO:
                    Snackbar.Dispatcher.Invoke(snackBarDelegate, "Token inválido. Revisa los datos.");
                    DificultadRatingBar.Dispatcher.Invoke(ratingBarDelegate, Visibility.Hidden);
                    TokenInvalidoTextBlock.Dispatcher.Invoke(tokenInvalidoTextBlockDelegate, Visibility.Visible);
                    SinConexionCard.Dispatcher.Invoke(sinConexionCardDelegate, Visibility.Visible);
                    EstadoVentanaLabel.Dispatcher.Invoke(estadoGeneralDelegate, "Token rechazado");
                    IniRehabBtn.Dispatcher.Invoke(iniRehabBtnDelegate, false);
                    Sesion.TokenValido = false;
                    break;

                case ServerHelper.TOKEN_VALIDO:
                    if (result.Ejercicio.Nombre != "Reach")
                    {
                        EjercicioPersonalizado = true;
                    }
                    Snackbar.Dispatcher.Invoke(snackBarDelegate, "Token Válido.");
                    EstadoVentanaLabel.Dispatcher.Invoke(estadoGeneralDelegate, "Token válido");
                    Sesion.TokenValido = true;
                    IdLabel.Dispatcher.Invoke(labelIdDelegate, result.Paciente.PacienteId);
                    NombreLabel.Dispatcher.Invoke(labelNombreDelegate, result.Paciente.Nombre);
                    PacienteCard.Dispatcher.Invoke(pacienteCardDelegate, Visibility.Visible);
                    SinConexionCard.Dispatcher.Invoke(sinConexionCardDelegate, Visibility.Hidden);
                    NombreEjercicioLabel.Dispatcher.Invoke(nombreEjercicioDelegate, result.Ejercicio.Nombre);
                    DificultadRatingBar.Dispatcher.Invoke(dificultadEjercicioDelegate, result.Ejercicio.Dificultad);
                    DificultadRatingBar.Dispatcher.Invoke(ratingBarDelegate, Visibility.Visible);
                    RepeticionesEjercicioLabel.Dispatcher.Invoke(repeticionesEjercicioDelegate, result.Repeticiones);
                    IniRehabBtn.Dispatcher.Invoke(iniRehabBtnDelegate, true);
                    break;

                default:
                    break;
                }
                AtrasBtn.Dispatcher.Invoke(atrasBtnDelegate, Visibility.Visible);
                ProgressBar.Dispatcher.Invoke(progressBarDelegate, Visibility.Hidden);
            };
        }
Example #7
0
 public ThemeProvider(ILocalFileProvider localFileProvider, IDataSerializer dataSerializer)
 {
     _localFileProvider = localFileProvider;
     _dataSerializer    = dataSerializer;
     _themeDirectory    = ServerHelper.MapPath($"{ApplicationConfig.ThemeDirectory}");
 }
Example #8
0
        public void tCheckStatus()
        {
            ServerHelper Helper = new ServerHelper();

            Helper.CheckStatus("This is a test of the emergency broadcasting system!", 40);
        }
Example #9
0
        private void ProcessUidList()
        {
            int counter = 0;

            Platform.Log(LogLevel.Info, "Populating images into study folder.. {0} to go", Context.WorkQueueUidList.Count);

            StudyProcessorContext context = new StudyProcessorContext(_destinationStudyStorage)
            {
                SopProcessedRulesEngine =
                    new ServerRulesEngine(ServerRuleApplyTimeEnum.SopProcessed,
                                          Context.WorkQueueItem.ServerPartitionKey)
            };

            // Load the rules engine
            context.SopProcessedRulesEngine.AddOmittedType(ServerRuleTypeEnum.SopCompress);
            context.SopProcessedRulesEngine.Load();

            // Add the update commands to update the files.  Note that the new Study Instance Uid is already part of this update.
            context.UpdateCommands.AddRange(Commands);

            // Add command to update the Series & Sop Instances.
            context.UpdateCommands.Add(new SeriesSopUpdateCommand(Context.WorkQueueItemStudyStorage, _destinationStudyStorage, UidMapper));

            // Create/Load the Study XML File
            StudyXml xml = LoadStudyXml(_destinationStudyStorage);

            string lastErrorMessage = "";

            foreach (WorkQueueUid uid in Context.WorkQueueUidList)
            {
                string imagePath = GetReconcileUidPath(uid);
                var    file      = new DicomFile(imagePath);

                var sopProcessor = new SopInstanceProcessor(context)
                {
                    EnforceNameRules = true
                };

                try
                {
                    file.Load();

                    string groupID = ServerHelper.GetUidGroup(file, _destinationStudyStorage.ServerPartition, Context.WorkQueueItem.InsertTime);

                    ProcessingResult result = sopProcessor.ProcessFile(groupID, file, xml, false, true, uid, imagePath);
                    if (result.Status != ProcessingStatus.Success)
                    {
                        throw new ApplicationException(String.Format("Unable to reconcile image {0}", file.Filename));
                    }

                    counter++;
                    Platform.Log(ServerPlatform.InstanceLogLevel, "Reconciled and Processed SOP {0} [{1} of {2}]",
                                 uid.SopInstanceUid, counter, Context.WorkQueueUidList.Count);
                }
                catch (Exception e)
                {
                    Platform.Log(LogLevel.Error, e, "Error occurred when processing uid {0}", uid.SopInstanceUid);

                    lastErrorMessage = e.Message;

                    SopInstanceProcessor.FailUid(uid, true);
                }
            }

            if (counter == 0)
            {
                throw new ApplicationException(lastErrorMessage);
            }
        }
Example #10
0
        public async Task PlayAsync([Remainder] string query)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed play ({query}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, query, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (!CheckIfLavaLinkIsEnabled())
            {
                return;
            }

            if (await ServerHelper.CheckIfContextIsDM(Context))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(query))
            {
                await ReplyAsync("Please provide search terms.");

                return;
            }

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                await ReplyAsync("I'm not connected to a voice channel.");
                await ReplyAsync("Joining you ;-)");
                await JoinAsync();
            }

            //var searchResponse = await _lavaNode.SearchAsync(query);
            var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAsync($"I wasn't able to find anything for `{query}`.");

                return;
            }

            var player = _lavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    foreach (var track in searchResponse.Tracks)
                    {
                        player.Queue.Enqueue(track);
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await ReplyAsync($"Enqueued: {track.Title}");
                }
            }
            else
            {
                var track = searchResponse.Tracks[0];                         // First result, maybe a random one?

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) // Play a playlist, maybe make this an option?
                {
                    for (var i = 0; i < searchResponse.Tracks.Count; i++)
                    {
                        if (i == 0)
                        {
                            await player.PlayAsync(track);
                            await ReplyAsync($"Now Playing: {track.Title}");
                        }
                        else
                        {
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    await player.PlayAsync(track);
                    await ReplyAsync($"Now Playing: {track.Title}");
                }
            }
        }
Example #11
0
        public static List <SelectListItem> GetCultures()
        {
            var cultureInfos = ServerHelper.GetAvailableCultureInfos().ToList();

            return(GetSelectItemListWithAction(cultureInfos, info => info.Name, info => $"{info.DisplayName} - {info.Name}"));
        }
Example #12
0
        public static List <SelectListItem> GetTimezones()
        {
            var timeZones = ServerHelper.GetAvailableTimezones();

            return(GetSelectItemList(timeZones, info => info.Id, info => info.DisplayName));
        }
        /// <summary>
        /// ProcessSavedFile a specified <see cref="WorkQueueUid"/>
        /// </summary>
        /// <param name="item">The <see cref="WorkQueue"/> item being processed</param>
        /// <param name="sop">The <see cref="WorkQueueUid"/> being processed</param>
        /// <param name="studyXml">The <see cref="StudyXml"/> object for the study being processed</param>
        /// <returns>true if the <see cref="WorkQueueUid"/> is successfully processed. false otherwise</returns>
        protected virtual bool ProcessWorkQueueUid(Model.WorkQueue item, WorkQueueUid sop, StudyXml studyXml)
        {
            Platform.CheckForNullReference(item, "item");
            Platform.CheckForNullReference(sop, "sop");
            Platform.CheckForNullReference(studyXml, "studyXml");

            OnProcessUidBegin(item, sop);

            string path = null;

            try
            {
                if (sop.Duplicate && sop.Extension != null)
                {
                    path = ServerHelper.GetDuplicateUidPath(StorageLocation, sop);
                    var file = new DicomFile(path);
                    file.Load();

                    InstancePreProcessingResult result = PreProcessFile(sop, file);

                    if (false == file.DataSet[DicomTags.StudyInstanceUid].ToString().Equals(StorageLocation.StudyInstanceUid) ||
                        result.DiscardImage)
                    {
                        RemoveWorkQueueUid(sop, null);
                    }
                    else
                    {
                        var duplicateResult = ProcessDuplicate(file, sop, studyXml);
                        if (duplicateResult.ActionTaken == DuplicateProcessResultAction.Delete || duplicateResult.ActionTaken == DuplicateProcessResultAction.Accept)
                        {
                            // make sure the folder is also deleted if it's empty
                            string folder = Path.GetDirectoryName(path);

                            String reconcileRootFolder = ServerHelper.GetDuplicateFolderRootPath(StorageLocation);
                            DirectoryUtility.DeleteIfEmpty(folder, reconcileRootFolder);
                        }
                    }
                }
                else
                {
                    try
                    {
                        path = StorageLocation.GetSopInstancePath(sop.SeriesInstanceUid, sop.SopInstanceUid);
                        var file = new DicomFile(path);
                        file.Load();

                        InstancePreProcessingResult result = PreProcessFile(sop, file);

                        if (false == file.DataSet[DicomTags.StudyInstanceUid].ToString().Equals(StorageLocation.StudyInstanceUid) ||
                            result.DiscardImage)
                        {
                            RemoveWorkQueueUid(sop, path);
                        }
                        else
                        {
                            ProcessFile(sop, file, studyXml, !result.AutoReconciled);
                        }
                    }
                    catch (DicomException ex)
                    {
                        // bad file. Remove it from the filesystem and the queue
                        RemoveBadDicomFile(path, ex.Message);
                        DeleteWorkQueueUid(sop);
                        return(false);
                    }
                }

                return(true);
            }
            catch (StudyIsNearlineException)
            {
                // handled by caller
                throw;
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception when processing file: {0} SOP Instance: {1}", path, sop.SopInstanceUid);
                item.FailureDescription = e.InnerException != null?
                                          String.Format("{0}:{1}", e.GetType().Name, e.InnerException.Message) : String.Format("{0}:{1}", e.GetType().Name, e.Message);

                //No longer needed.  Update was moved into the SopInstanceProcessor
                //sop.FailureCount++;
                //UpdateWorkQueueUid(sop);
                return(false);
            }
            finally
            {
                OnProcessUidEnd(item, sop);
            }
        }
        private ProcessDuplicateResult ProcessDuplicate(DicomFile dupFile, WorkQueueUid uid, StudyXml studyXml)
        {
            var result = new ProcessDuplicateResult();

            var data = uid.SerializeWorkQueueUidData;

            string duplicateSopPath = ServerHelper.GetDuplicateUidPath(StorageLocation, uid);
            string basePath         = StorageLocation.GetSopInstancePath(uid.SeriesInstanceUid, uid.SopInstanceUid);

            if (!File.Exists(basePath))
            {
                // NOTE: This is special case. The file which caused dicom service to think this sop is a duplicate
                // no longer exists in the study folder. Perhaps it has been moved to another folder during auto reconciliation.
                // We have nothing to compare against so let's just throw it into the SIQ queue.
                CreateDuplicateSIQEntry(uid, dupFile, null);
                result.ActionTaken = DuplicateProcessResultAction.Reconcile;
            }
            else
            {
                var duplicateEnum = data.DuplicateProcessing.HasValue ? data.DuplicateProcessing.Value : DuplicateProcessingEnum.Compare;

                // Check if system is configured to override the rule for this study
                if (duplicateEnum == DuplicateProcessingEnum.OverwriteSop)
                {
                    return(OverwriteDuplicate(dupFile, uid, studyXml));
                }

                // Check if system is configured to override the rule for this study
                if (duplicateEnum == DuplicateProcessingEnum.OverwriteSopAndUpdateDatabase)
                {
                    return(OverwriteAndUpdateDuplicate(dupFile, uid, studyXml));
                }

                var baseFile = new DicomFile(basePath);
                baseFile.Load();

                if (duplicateEnum == DuplicateProcessingEnum.OverwriteReport)
                {
                    return(ProcessDuplicateReport(dupFile, baseFile, uid, studyXml));
                }

                // DuplicateProcessingEnum.Compare
                if (!dupFile.TransferSyntax.Equals(baseFile.TransferSyntax))
                {
                    // If they're compressed, and we have a codec, lets decompress and still do the comparison
                    if (dupFile.TransferSyntax.Encapsulated &&
                        !dupFile.TransferSyntax.LossyCompressed &&
                        DicomCodecRegistry.GetCodec(dupFile.TransferSyntax) != null)
                    {
                        dupFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                    }

                    if (baseFile.TransferSyntax.Encapsulated &&
                        !baseFile.TransferSyntax.LossyCompressed &&
                        DicomCodecRegistry.GetCodec(baseFile.TransferSyntax) != null)
                    {
                        baseFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                    }

                    if (dupFile.TransferSyntax.Encapsulated || baseFile.TransferSyntax.Encapsulated)
                    {
                        string failure = String.Format("Base file transfer syntax is '{0}' while duplicate file has '{1}'",
                                                       baseFile.TransferSyntax, dupFile.TransferSyntax);

                        var list          = new List <DicomAttributeComparisonResult>();
                        var compareResult = new DicomAttributeComparisonResult
                        {
                            ResultType = ComparisonResultType.DifferentValues,
                            TagName    = DicomTagDictionary.GetDicomTag(DicomTags.TransferSyntaxUid).Name,
                            Details    = failure
                        };
                        list.Add(compareResult);
                        CreateDuplicateSIQEntry(uid, dupFile, list);
                        result.ActionTaken = DuplicateProcessResultAction.Reconcile;
                        return(result);
                    }
                }

                var failureReason = new List <DicomAttributeComparisonResult>();
                if (baseFile.DataSet.Equals(dupFile.DataSet, ref failureReason))
                {
                    Platform.Log(LogLevel.Info,
                                 "Duplicate SOP being processed is identical.  Removing SOP: {0}",
                                 baseFile.MediaStorageSopInstanceUid);


                    RemoveWorkQueueUid(uid, duplicateSopPath);
                    result.ActionTaken = DuplicateProcessResultAction.Delete;
                }
                else
                {
                    CreateDuplicateSIQEntry(uid, dupFile, failureReason);
                    result.ActionTaken = DuplicateProcessResultAction.Reconcile;
                }
            }

            return(result);
        }
Example #15
0
 public void tCheckStatus()
 {
     ServerHelper Helper = new ServerHelper();
     Helper.CheckStatus("This is a test of the emergency broadcasting system!", 40);
 }
Example #16
0
        public async Task Warn([Summary("The user to warn")] SocketGuildUser user, [Summary("The reason for the warning")][Remainder] string reason = "No Reason Provided")
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{user}#{discriminator} warned {user} for {reason} in {channel} on {server}",
                                   Context.User.Username, Context.User.Discriminator, user.Username, reason, Context.Channel.Name, Context.Guild?.Name ?? "DM");

            if (user.Id == _client.CurrentUser.Id)
            {
                await ReplyAsync("Nice try, but I am immune from warnings!");

                return;
            }

            if (user.Id == Context.User.Id)
            {
                await ReplyAsync("Lol, you are warning yourself!");
            }

            var server = await ServerHelper.GetOrAddServer(Context.Guild.Id, _serverRepository);

            var userDb = await UserHelper.GetOrAddUser(user, _userRepository);

            var warning = new Warning
            {
                UserId   = userDb.Id,
                ServerId = server.Id,
                Text     = reason
            };
            await _warningRepository.AddAsync(warning);

            var warn = await _warningRepository.GetUsersWarnings(server, userDb);

            var wAction = await _warningRepository.GetWarningAction(server);

            if (wAction == null)
            {
                wAction = new WarnAction
                {
                    Action          = WarningAction.NoAction,
                    ActionThreshold = 1
                };
                await ReplyAsync($"{Context.User.Mention}: NOTE! The warning action has not been set!");
            }

            await Context.Channel.SendEmbedAsync("You have been warned!", $"{user.Mention} you have been warned for: `{reason}`!\n" +
                                                 $"This is warning #`{warn.Count()}` of `{wAction.ActionThreshold}`\n" +
                                                 $"The action is set to: { Enum.GetName(typeof(WarningAction), wAction.Action)}",
                                                 ColorHelper.GetColor(server));

            if (warn.Count() >= wAction.ActionThreshold)
            {
                var message = $"The maximum number of warnings has been reached, because of the warn action ";
                switch (wAction.Action)
                {
                case WarningAction.NoAction:
                    message += "nothing happens.";
                    break;

                case WarningAction.Kick:
                    message += $"{user.Username} has been kicked.";
                    await user.KickAsync("Maximum Warnings Reached!");

                    break;

                case WarningAction.Ban:
                    message += $"{user.Username} has been banned.";
                    await user.BanAsync(0, "Maximum Warnings Reached!");

                    break;

                default:
                    message += "default switch statement :(";
                    break;
                }

                await ReplyAsync(message);
            }
            await _servers.SendLogsAsync(Context.Guild, $"User Warned", $"{Context.User.Mention} warned {user.Username} for: {reason}", ImageLookupUtility.GetImageUrl("LOGGING_IMAGES"));
        }
Example #17
0
        private void ProcessUidList()
        {
            int counter = 0;

            Platform.Log(LogLevel.Info, "Populating new images into study folder.. {0} to go", Context.WorkQueueUidList.Count);

            StudyProcessorContext context = new StudyProcessorContext(_destinationStudyStorage);

            // Load the rules engine
            context.SopProcessedRulesEngine = new ServerRulesEngine(ServerRuleApplyTimeEnum.SopProcessed, Context.WorkQueueItem.ServerPartitionKey);
            context.SopProcessedRulesEngine.AddOmittedType(ServerRuleTypeEnum.SopCompress);
            context.SopProcessedRulesEngine.Load();

            // Load the Study XML File
            StudyXml xml = LoadStudyXml(_destinationStudyStorage);

            string lastErrorMessage = "";

            foreach (WorkQueueUid uid in Context.WorkQueueUidList)
            {
                string    imagePath = GetReconcileUidPath(uid);
                DicomFile file      = new DicomFile(imagePath);

                try
                {
                    file.Load();

                    string groupID = ServerHelper.GetUidGroup(file, _destinationStudyStorage.ServerPartition, Context.WorkQueueItem.InsertTime);

                    SopInstanceProcessor sopProcessor = new SopInstanceProcessor(context);
                    ProcessingResult     result       = sopProcessor.ProcessFile(groupID, file, xml, false, true, uid, GetReconcileUidPath(uid), SopInstanceProcessorSopType.NewSop);
                    if (result.Status != ProcessingStatus.Success)
                    {
                        throw new ApplicationException(String.Format("Unable to reconcile image {0}", file.Filename));
                    }

                    counter++;

                    Platform.Log(ServerPlatform.InstanceLogLevel, "Reconciled SOP {0} [{1} of {2}]",
                                 uid.SopInstanceUid, counter, Context.WorkQueueUidList.Count);
                }
                catch (Exception e)
                {
                    Platform.Log(LogLevel.Error, e, "Error occurred when processing uid {0}", uid.SopInstanceUid);

                    if (e is InstanceAlreadyExistsException ||
                        e.InnerException != null && e.InnerException is InstanceAlreadyExistsException)
                    {
                        // TODO (Rigel) - Check if we should include the WorkQueueData field here
                        DuplicateSopProcessorHelper.CreateDuplicateSIQEntry(file, _destinationStudyStorage, GetReconcileUidPath(uid),
                                                                            Context.WorkQueueItem, uid, null);
                    }
                    else
                    {
                        lastErrorMessage = e.Message;
                        SopInstanceProcessor.FailUid(uid, true);
                    }
                }
            }


            if (counter == 0)
            {
                throw new ApplicationException(lastErrorMessage);
            }
        }
Example #18
0
        private string GetBundle(string[] inputFiles, string type)
        {
            var bundleFileProcessor = new BundleFileProcessor();
            var bundle = new BundlerMinifier.Bundle();
            //we wil store the file names with date of modification to keep track whether a new bundle should be generated or not
            //any minor modification will cause regeneration of the bundle
            //we do this because it is a performance intensive operation and the we should only do it when needed

            var distinctFiles      = inputFiles.Distinct().ToList();
            var fileNamesWithDates = new List <string>();

            foreach (var inputFile in distinctFiles)
            {
                //the input file can either be 1. theme-css 2. plugin-css 3. admin-css 4. common-css
                //check them one by one
                var file = ServerHelper.MapPath("~/Content/Themes" + inputFile);
                if (!_localFileProvider.FileExists(file))
                {
                    //plugins
                    file = ServerHelper.MapPath("~/" + inputFile);
                    if (!_localFileProvider.FileExists(file))
                    {
                        //administration & common
                        file = ServerHelper.MapPath("~/" + inputFile, true);
                        if (!_localFileProvider.FileExists(file))
                        {
                            continue; //can't do anything...the file doesn't exist
                        }
                    }
                }
                bundle.InputFiles.Add(file);
                var modDate = _localFileProvider.GetLastModifiedDateTime(file);
                fileNamesWithDates.Add($"{file}:{modDate}");
            }

            var outputFilePart1  = GetOutputFileName(fileNamesWithDates);
            var outputFilePart2  = GetOutputFileName(distinctFiles);
            var outputFile       = outputFilePart1 + "_" + outputFilePart2;
            var bundlesDirectory = ServerHelper.MapPath(ApplicationConfig.BundlesDirectory, true);
            var bundleFileName   = bundlesDirectory + "/" + outputFile + $".min.{type}";

            bundle.OutputFileName = bundleFileName;
            //do we need to generate the bundle?
            if (!_localFileProvider.FileExists(bundleFileName))
            {
                //delete the existing bundles of these files
                try
                {
                    _localFileProvider.DeleteFiles(bundlesDirectory, $"*_{outputFilePart2}.min.{type}*");
                }
                catch
                {
                    //do nothing...the file must be locked...will try next time
                }
                bundle.FileName = bundleFileName + ".json";
                BundleMinifier.ErrorMinifyingFile += BundleMinifier_ErrorMinifyingFile;
                bundleFileProcessor.Process(bundle.FileName, new List <BundlerMinifier.Bundle>()
                {
                    bundle
                });
            }
            //if operation succeeded, return the url, else null
            if (bundle.OutputFileName == null)
            {
                return(null);
            }
            //also create a gzipped version as well
            using (var bundleFileStream = File.OpenRead(bundleFileName))
                using (var compressedFileStream = File.Create(bundleFileName + ".gz"))
                {
                    using (var compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                    {
                        bundleFileStream.CopyTo(compressionStream);
                    }
                }
            return(bundle.OutputFileName == null ? null : ApplicationEngine.MapUrl(bundleFileName));
        }
Example #19
0
        protected override void PageLoad()
        {
            base.PageLoad();
            base.Title = "最小学习量达成分析表";
            base.CheckUserPower("ReadEMSReport", PowerCheckType.Single);

            string    logPath = ServerHelper.MapPath(@"\Log\");
            TxtLog    log     = new TxtLog(logPath);
            Stopwatch time2   = new Stopwatch();

            time2.Start();

            if (CompanyID < 0)
            {
                CompanyID = base.UserCompanyID;
            }
            CompanyInfo company = CompanyBLL.ReadCompany(CompanyID);

            PostList = PostBLL.ReadPostListByPostId(company.Post);
            if (base.ExistsSonCompany)
            {
                userGroupList = AdminGroupBLL.ReadAdminGroupList(CompanyID, UserBLL.ReadUserGroupIDByCompanyID(base.SonCompanyID));
            }
            else
            {
                userGroupList = AdminGroupBLL.ReadAdminGroupList(CompanyID, UserBLL.ReadUserGroupIDByCompanyID(CompanyID.ToString()));
            }

            //设置默认岗位(去除待考岗位)
            //if (string.IsNullOrEmpty(PostIdCondition)) PostIdCondition = StringHelper.SubString(company.Post, "197");
            //if (string.IsNullOrEmpty(StudyPostIdCondition)) StudyPostIdCondition = StringHelper.SubString(company.Post, "197");
            //用户权限组默认给考试人员
            if (string.IsNullOrEmpty(groupID))
            {
                groupID = "36";
            }

            if (Action == "Search")
            {
                if (EndDate == DateTime.MinValue)
                {
                    EndDate = DateTime.Today;
                }
                EndDate = ShopCommon.SearchEndDate(EndDate);

                if (base.CompareUserPower("ManageGroupCompany", PowerCheckType.Single) && base.IsGroupCompany(company.GroupId))
                {
                    List <CompanyInfo> sonCompanyList = base.SonCompanyList;
                    //减少使用递归方法的频率
                    if (CompanyID != base.UserCompanyID)
                    {
                        sonCompanyList = CompanyBLL.ReadCompanyListByCompanyId(CompanyBLL.ReadCompanyIdList(CompanyID.ToString()));
                    }

                    GroupResult.Add(company.CompanySimpleName + "合计");
                    GroupResult.Add(0);
                    GroupResult.Add(0);
                    GroupResult.Add(0);
                    GroupResult.Add("");
                    GroupResult.Add("");
                    StringBuilder TotalTable = new StringBuilder();
                    TotalTable.AppendLine("<table class=\"evaluation_sheet\">");
                    TotalTable.AppendLine("<tr>");
                    TotalTable.AppendLine("<th colspan=\"5\">" + company.CompanySimpleName + " [" + StartDate.ToString("d") + "—" + EndDate.AddDays(-1).ToString("d") + "]");
                    TotalTable.Append("</th>");
                    TotalTable.AppendLine("</tr>");
                    TotalTable.AppendLine("<tr>");
                    TotalTable.AppendLine("<th>公司名</th>");
                    TotalTable.AppendLine("<th>参加岗位考试人数</th>");
                    TotalTable.AppendLine("<th>最小学习量<br />学习达标人数</th>");
                    TotalTable.AppendLine("<th>最小学习量<br />学习未达标人数</th>");
                    TotalTable.AppendLine("<th>最小学习量<br />学习达成率</th>");
                    TotalTable.AppendLine("</tr>");
                    foreach (CompanyInfo info in sonCompanyList)
                    {
                        if (info.CompanyId != CompanyID && !string.IsNullOrEmpty(info.PostStartDate.ToString()) && Convert.ToDateTime(info.PostStartDate) < EndDate)
                        {
                            TotalTable.Append(HtmlOut1(info, "TotalTable"));
                        }
                    }
                    TotalTable.AppendLine("<tr>");
                    TotalTable.AppendLine("<td>" + GroupResult[0] + "</td>");
                    TotalTable.AppendLine("<td>" + GroupResult[1] + "</td>");
                    TotalTable.AppendLine("<td>" + GroupResult[2] + "</td>");
                    TotalTable.AppendLine("<td>" + GroupResult[3] + "</td>");
                    TotalTable.AppendLine("<td>" + (double.Parse(GroupResult[2].ToString()) / double.Parse(GroupResult[1].ToString())).ToString("P") + "</td>");
                    TotalTable.AppendLine("</tr>");
                    TotalTable.AppendLine("</table>");
                    TotalTable.Append("<div style=\"line-height:25px; text-align:left; font-size:14px;\"><p style=\"text-align:left;  font-size:14px; line-heigh:30px; margin-top:20px;\">4S店每人每周完成1-2小时的基础学习,将带动公司提升“百年老店”运营,建议高标为100%,低标为70%。");
                    if (!string.IsNullOrEmpty(GroupResult[4].ToString()))
                    {
                        TotalTable.Append("<br /><br />目前:<span style=\"color:#00b050;\">" + GroupResult[4] + "</span> 达至 <span style=\"color:#00b050;\">100%</span> ,表现良好,予以肯定。");
                    }
                    if (!string.IsNullOrEmpty(GroupResult[5].ToString()))
                    {
                        TotalTable.Append("<br /><br /><span style=\"color:#FF0000;\">" + GroupResult[5] + "</span> 达成率尚不足 <span style=\"color:#FF0000;\">70%</span> ,请相关部门领导关注下属自主学习时间的妥善安排。");
                    }
                    TotalTable.Append("</p></div>\r\n");
                    ReportContentHtml = TotalTable.ToString();
                }
                else
                {
                    ReportContentHtml = HtmlOut1(company, "");
                }
            }

            time2.Stop();
            log.Write("总执行时间为:" + time2.Elapsed.TotalSeconds);
        }
Example #20
0
        public async Task LoginRequestHandler(ClientLoginInfoPacket packet, IRakConnection connection)
        {
            await using var ctx = new UchuContext();

            var info = new ServerLoginInfoPacket
            {
                CharacterInstanceAddress = Server.GetHost(),
                CharacterInstancePort    = ushort.MaxValue,
                ChatInstanceAddress      = Server.GetHost(),
                ChatInstancePort         = 2004
            };

            var characterSpecification = await ServerHelper.GetServerByType(ServerType.Character);

            if (characterSpecification == default)
            {
                info.LoginCode = LoginCode.InsufficientPermissions;
                info.Error     = new ServerLoginInfoPacket.ErrorMessage
                {
                    Message = "No character server instance is running. Please try again later."
                };
            }
            else
            {
                info.CharacterInstancePort = (ushort)characterSpecification.Port;

                if (!await ctx.Users.AnyAsync(u => u.Username == packet.Username))
                {
                    info.LoginCode = LoginCode.InsufficientPermissions;
                    info.Error     = new ServerLoginInfoPacket.ErrorMessage
                    {
                        Message = "We have no records of that Username and Password combination. Please try again."
                    };
                }
                else
                {
                    var user = await ctx.Users.SingleAsync(u => u.Username == packet.Username);

                    if (user != null && BCrypt.Net.BCrypt.EnhancedVerify(packet.Password, user.Password))
                    {
                        if (user.Banned)
                        {
                            info.LoginCode = LoginCode.InsufficientPermissions;
                            info.Error     = new ServerLoginInfoPacket.ErrorMessage
                            {
                                Message = $"This account has been banned by an admin. Reason:\n{user.BannedReason ?? "Unknown"}"
                            };
                        }
                        else if (!string.IsNullOrWhiteSpace(user.CustomLockout))
                        {
                            info.LoginCode = LoginCode.InsufficientPermissions;
                            info.Error     = new ServerLoginInfoPacket.ErrorMessage
                            {
                                Message = user.CustomLockout
                            };
                        }
                        else
                        {
                            var key = Server.SessionCache.CreateSession(user.UserId);

                            info.LoginCode = LoginCode.Success;
                            info.UserKey   = key;

                            //
                            // I don't intend, nor do I see anyone else, using these.
                            // Except maybe FirstTimeOnSubscription for the fancy screen.
                            //

                            info.FreeToPlay = user.FreeToPlay;
                            info.FirstLoginWithSubscription = user.FirstTimeOnSubscription;

                            //
                            // No longer the first time on subscription
                            //

                            user.FirstTimeOnSubscription = false;

                            await ctx.SaveChangesAsync();
                        }
                    }
                    else
                    {
                        info.LoginCode = LoginCode.InsufficientPermissions;
                        info.Error     = new ServerLoginInfoPacket.ErrorMessage
                        {
                            Message = "We have no records of that Username and Password combination. Please try again."
                        };
                    }
                }
            }

            connection.Send(info);
        }
Example #21
0
        protected string HtmlOut1(CompanyInfo company, string Type)
        {
            int       WeekNum = 0, ColNum = 10, PeoperNum = 0;
            string    logPath = ServerHelper.MapPath(@"\Log\");
            TxtLog    log     = new TxtLog(logPath);
            Stopwatch time1   = new Stopwatch();

            time1.Start();
            StringBuilder TextOut           = new StringBuilder();
            string        CompanyBrandId    = company.BrandId;
            DateTime      PostPlanStartDate = DateTime.MinValue;

            if (string.IsNullOrEmpty(company.PostStartDate.ToString()))
            {
                PostPlanStartDate = Convert.ToDateTime("2013-7-1");
            }
            else
            {
                PostPlanStartDate = Convert.ToDateTime(company.PostStartDate.ToString());
            }

            string rowspan = string.Empty;

            TextOut.Append("<table class=\"evaluation_sheet\">");
            TextOut.Append("<tr>");
            if (StartDate != DateTime.MinValue)
            {
                WeekNum = (EndDate - StartDate).Days / 7;
                if ((EndDate - StartDate).Days % 7 > 0)
                {
                    WeekNum = WeekNum + 1;
                }
                TextOut.Append("<th colspan=\"" + (ColNum + WeekNum * 3) + "\">" + company.CompanySimpleName + " [" + StartDate.ToString("d") + "—" + EndDate.AddDays(-1).ToString("d") + "]");
                rowspan = " rowspan=\"3\"";
            }
            else
            {
                TextOut.Append("<th colspan=\"" + ColNum + "\">" + company.CompanySimpleName + " [ 截止到:" + EndDate.AddDays(-1).ToString("d") + " ]");
                rowspan = " rowspan=\"3\"";
            }
            TextOut.Append("</th></tr>\r\n");
            TextOut.Append("<tr>\r\n");
            TextOut.Append("<th" + rowspan + " class=\"id\">序号</th>");
            //if (base.IsGroupCompany(company.GroupId)) TextOut.Append("<th" + rowspan + ">公司名</th>");
            TextOut.Append("<th" + rowspan + " class=\"name\">姓名</th>");
            TextOut.Append("<th" + rowspan + " class=\"post\">工作岗位</th>");
            TextOut.Append("<th" + rowspan + " class=\"post\">学习岗位</th>");
            TextOut.Append("<th colspan=\"" + (WeekNum * 3).ToString() + "\">学习已通过</th>");
            TextOut.Append("<th colspan=\"3\">合计<br />(");
            if (StartDate != DateTime.MinValue)
            {
                TextOut.Append(StartDate.ToString("d") + "—" + EndDate.AddDays(-1).ToString("d"));
            }
            else
            {
                TextOut.Append("截止到:" + EndDate.AddDays(-1).ToString("d"));
                StartDate = PostPlanStartDate;
            }
            TextOut.Append(")</th>");
            TextOut.Append("<th colspan=\"3\">从项目启动开始</th>");
            TextOut.Append("</tr>\r\n");
            TextOut.Append("<tr>\r\n");
            for (int j = 1; j <= WeekNum; j++)
            {
                TextOut.Append("<th colspan=\"3\">第" + j.ToString() + "周<br>" + StartDate.AddDays(7 * (j - 1)).ToString("M-d") + "—");
                if (j == WeekNum)
                {
                    TextOut.Append(EndDate.AddDays(-1).ToString("M-d") + "</th>");
                }
                else
                {
                    TextOut.Append(StartDate.AddDays((7 * j) - 1).ToString("M-d") + "</th>");
                }
            }
            TextOut.Append("<th rowspan=\"2\" class=\"total\">累计学习<br />考试次数</th>");
            TextOut.Append("<th rowspan=\"2\" class=\"total\">考试通过<br />课程数量</th>");
            TextOut.Append("<th rowspan=\"2\" class=\"total\">课程考试<br />通过率</th>");
            TextOut.Append("<th rowspan=\"2\" class=\"total\">累计<br>完成总数</th>");
            TextOut.Append("<th rowspan=\"2\" class=\"total\">目标<br>完成总数<br>(实际数)</th>");
            TextOut.Append("<th rowspan=\"2\" class=\"total\">学习进度<br>达成分析<br>(超前/落后)</th>");
            TextOut.Append("</tr>\r\n");
            TextOut.Append("<tr class=\"listTableHead\">\r\n");
            for (int j = 1; j <= WeekNum; j++)
            {
                TextOut.Append("<th class=\"total\">累计学习<br />考试次数</th>");
                TextOut.Append("<th class=\"total\">考试通过<br />课程数量</th>");
                TextOut.Append("<th class=\"total\">课程考试<br />通过率</th>");
            }
            TextOut.Append("</tr>\r\n");

            //统计目标课程数
            int TargetNum = 0, CompanyDelayNum = 0;
            //统计通过课程数量第一的数据信息
            string PassCourseFirstUser = string.Empty, GoodStudent = string.Empty; int FirstPassCourseNum = 0;
            //单个岗位的岗位计划开始时间
            DateTime PostStartDate = DateTime.MinValue;
            int      PostSign = 0;      //是否重新计算岗位总数的标记
            int      PostCourseNum = 0; //岗位课程数
            string   AllPostPlan = "0"; //岗位下所有级别的岗位课程
            int      RedNum = 0, YellowNum = 0, GreenNum = 0;

            //增加通过率所用补丁部分
            TestPaperInfo TestPaperModel = new TestPaperInfo();

            if (!string.IsNullOrEmpty(company.PostStartDate.ToString()))
            {
                TestPaperModel.TestMinDate = Convert.ToDateTime(company.PostStartDate);
            }
            TestPaperModel.TestMaxDate        = EndDate;
            TestPaperModel.CompanyIdCondition = company.CompanyId.ToString();
            TestPaperModel.Condition          = "[UserID] in (select [ID] from [_User] where [companyID]=" + company.CompanyId.ToString() + " and [status]=" + (int)UserState.Normal;
            if (!string.IsNullOrEmpty(groupID))
            {
                TestPaperModel.Condition += " and [GroupID] in (" + groupID + ")";
            }
            if (!string.IsNullOrEmpty(PostIdCondition))
            {
                TestPaperModel.Condition += " and [WorkingPostID] in (" + PostIdCondition + ")";
            }
            if (!string.IsNullOrEmpty(StudyPostIdCondition))
            {
                TestPaperModel.Condition += " and [StudyPostId] in (" + StudyPostIdCondition + ")";
            }
            TestPaperModel.Condition += ")";
            List <TestPaperInfo> TestPaperList = TestPaperBLL.NewReadList(TestPaperModel);

            UserSearchInfo userSearch = new UserSearchInfo();

            userSearch.Status          = (int)UserState.Normal;
            userSearch.InWorkingPostID = PostIdCondition;
            //if (base.IsGroupCompany(company.GroupId))
            //{
            //    userSearch.InCompanyID = CompanyBLL.ReadCompanyIdList(company.CompanyId.ToString());
            //    ColNum = 11;
            //    userSearch.InStudyPostID = "45";//集团打开默认显示学习岗位
            //}
            //else
            {
                userSearch.InCompanyID   = company.CompanyId.ToString();
                userSearch.InStudyPostID = StudyPostIdCondition; //只显示该学习岗位下的人员
            }
            userSearch.InGroupID = groupID;
            List <UserInfo> userList = UserBLL.SearchReportUserList(userSearch);
            //记录岗位课程ID串
            Dictionary <int, string[]> postCourseDic = new Dictionary <int, string[]>();

            time1.Stop();
            log.Write("执行到会员开始循环的时间为:" + time1.Elapsed.TotalSeconds);
            time1.Reset();
            foreach (UserInfo Info in userList)
            {
                time1.Reset();
                time1.Start();
                int PostId = int.MinValue, PerPassCourseNum = 0, PerCourseNum = 0;

                PostId = Info.StudyPostID;

                PostInfo PostModel = PostBLL.ReadPost(PostId);
                if (PostModel != null) //排除掉没有设置岗位的人
                {
                    //筛选出当前用户ID的成绩列表
                    List <TestPaperInfo> currentUserPaperList     = TestPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.UserId == Info.ID); });
                    List <TestPaperInfo> currentUserPassPaperList = currentUserPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.IsPass == 1); });

                    int ResidueCourseNum = 0;//岗位内剩余岗位课程数

                    if (!postCourseDic.ContainsKey(PostId))
                    {
                        //岗位数据信息 1:岗位课程ID串;2:岗位课程数量;3:岗位开始时间;4:目标课程数量
                        string[] postData = { "0", "0", DateTime.MinValue.ToString(), "0" };
                        AllPostPlan = PostBLL.ReadPostCourseID(company.CompanyId, PostId);
                        postData[0] = AllPostPlan;

                        if (!string.IsNullOrEmpty(AllPostPlan))
                        {
                            PostCourseNum = AllPostPlan.Split(',').Length;
                            postData[1]   = PostCourseNum.ToString();
                        }

                        //公司有事耽误的数量  由于岗位不一样,岗位计划开始的时间也不一样,所以有事耽误的数量也是不一致的,按岗位计算
                        PostStartDate = CompanyPostPlanBLL.ReadCompanyPostPlan(company.CompanyId, PostId);
                        //如果没有设置岗位开始时间或者岗位开始时间比公司开始时间早,统一使用公司开始时间
                        if (PostStartDate == DateTime.MinValue || PostStartDate < PostPlanStartDate)
                        {
                            PostStartDate = PostPlanStartDate;
                        }

                        //根据统一的岗位开始时间调取数据
                        CompanyDelayNum = ChangeNumBLL.CompanyChangeNum(company.CompanyId, PostId, PostStartDate, EndDate);
                        TargetNum       = CompanyRuleBLL.GetCourseNum(company.CompanyId, PostId, PostStartDate, EndDate); //理论值是每周两门
                        TargetNum       = TargetNum - CompanyDelayNum;

                        postData[2] = PostStartDate.ToString();
                        postData[3] = TargetNum.ToString();
                        postCourseDic.Add(PostId, postData);
                    }
                    else
                    {
                        AllPostPlan   = postCourseDic[PostId][0];
                        PostCourseNum = int.Parse(postCourseDic[PostId][1]);
                        PostStartDate = Convert.ToDateTime(postCourseDic[PostId][2]);
                        TargetNum     = int.Parse(postCourseDic[PostId][3]);
                    }

                    //如果员工是后来的,要以员工进来的时间为起始点
                    if (PostStartDate < Info.PostStartDate)//Info.RegisterDate
                    {
                        PostStartDate   = Info.PostStartDate;
                        CompanyDelayNum = ChangeNumBLL.CompanyChangeNum(company.CompanyId, PostId, PostStartDate, EndDate);
                        TargetNum       = CompanyRuleBLL.GetCourseNum(company.CompanyId, PostId, PostStartDate, EndDate); //理论值是每周两门
                        TargetNum       = TargetNum - CompanyDelayNum;
                    }
                    TargetNum = TargetNum - ChangeNumBLL.UserChangeNum(Info.ID, PostStartDate, EndDate);


                    //PassCateId 跨岗位通过的课程  PostResidueCourse 岗位内剩余课程
                    string PassCateId = string.Empty, NoPassCateId = string.Empty, PostResidueCourse = string.Empty;
                    if (!string.IsNullOrEmpty(company.PostStartDate.ToString()))
                    {
                        PassCateId        = TestPaperBLL.ReadCourseIDStr(currentUserPassPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.TestDate >= PostStartDate && TempModel.TestDate <= EndDate); }));
                        PostResidueCourse = StringHelper.SubString(AllPostPlan, TestPaperBLL.ReadCourseIDStr(currentUserPassPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.TestDate <= EndDate); })));
                    }
                    else
                    {
                        PassCateId        = TestPaperBLL.ReadCourseIDStr(currentUserPassPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.TestDate <= EndDate); }));
                        PostResidueCourse = StringHelper.SubString(AllPostPlan, PassCateId);
                    }

                    //跨岗位通过的课程数(全岗位计划开始后,累计完成的课程数)
                    int AllPassCourseNum = 0;
                    if (!string.IsNullOrEmpty(PassCateId))
                    {
                        AllPassCourseNum = PassCateId.Split(',').Length;
                    }
                    //获取岗位内剩余课程数
                    if (!string.IsNullOrEmpty(PostResidueCourse))
                    {
                        ResidueCourseNum = PostResidueCourse.Split(',').Length;
                    }

                    string PastPassCourse = string.Empty;
                    PeoperNum = PeoperNum + 1;
                    TextOut.Append("<tr>\r\n");
                    TextOut.Append("<td>" + PeoperNum + "</td>");
                    //if (base.IsGroupCompany(company.GroupId)) TextOut.Append("<td>" + CompanyBLL.ReadCompany(Info.CompanyID).CompanySimpleName + "</td>");
                    TextOut.Append("<td>" + Info.RealName + "</td>");
                    if (!string.IsNullOrEmpty(Info.PostName))
                    {
                        TextOut.Append("<td>" + Info.PostName + "</td>");
                    }
                    else
                    {
                        TextOut.Append("<td>" + PostBLL.ReadPost(Info.WorkingPostID).PostName + "</td>");
                    }
                    TextOut.Append("<td>" + PostModel.PostName + "</td>");
                    for (int j = 1; j <= WeekNum; j++)
                    {
                        int      WeekCourseNum = 0;
                        DateTime _StartDate    = StartDate.AddDays(7 * (j - 1));
                        DateTime _EndDate      = StartDate.AddDays(7 * j);
                        if (j == WeekNum)
                        {
                            _EndDate = EndDate;
                        }
                        if (_StartDate < PostStartDate)
                        {
                            _StartDate = PostStartDate;
                        }
                        if (_EndDate > PostStartDate)
                        {
                            PastPassCourse = TestPaperBLL.ReadCourseIDStr(currentUserPassPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.TestDate >= _StartDate && TempModel.TestDate <= _EndDate); }));
                            WeekCourseNum  = currentUserPaperList.FindAll(delegate(TestPaperInfo TempModel) { return(TempModel.TestDate >= _StartDate && TempModel.TestDate <= _EndDate); }).Count;
                        }
                        int PastPassCourseNum = 0;
                        if (!string.IsNullOrEmpty(PastPassCourse))
                        {
                            PastPassCourseNum = PastPassCourse.Split(',').Length;
                        }
                        PerPassCourseNum += PastPassCourseNum;
                        PerCourseNum     += WeekCourseNum;
                        TextOut.Append("<td>" + WeekCourseNum + "</td>");
                        TextOut.Append("<td>" + (PastPassCourseNum) + "</td>");
                        if (PastPassCourseNum == 0)
                        {
                            TextOut.Append("<td>0</td>");
                        }
                        else
                        {
                            TextOut.Append("<td>" + ((double)PastPassCourseNum / (double)WeekCourseNum).ToString("P") + "</td>");
                        }
                    }

                    //统计好学生 学习课程超过30门的人
                    if (PerCourseNum >= 30)
                    {
                        GoodStudent += " " + Info.RealName;
                    }

                    //统计通过课程数量第一的数据
                    if (PerPassCourseNum > 0 && PerPassCourseNum >= FirstPassCourseNum)
                    {
                        if (PerPassCourseNum > FirstPassCourseNum)
                        {
                            PassCourseFirstUser = Info.RealName;
                            FirstPassCourseNum  = PerPassCourseNum;
                        }
                        else
                        {
                            PassCourseFirstUser = PassCourseFirstUser + " " + Info.RealName;
                        }
                    }
                    TextOut.Append("<td>" + PerCourseNum + "</td>");
                    TextOut.Append("<td>" + PerPassCourseNum + "</td>");
                    if (PerCourseNum <= 0)
                    {
                        TextOut.Append("<td>0</td>");
                    }
                    else
                    {
                        TextOut.Append("<td>" + ((double)PerPassCourseNum / (double)PerCourseNum).ToString("P") + "</td>");
                    }
                    TextOut.Append("<td>" + (AllPassCourseNum) + "</td>");
                    TextOut.Append("<td>" + (TargetNum) + "</td>");
                    TargetNum = AllPassCourseNum - TargetNum;
                    TextOut.Append("<td style=\"");
                    if (TargetNum > 0)
                    {
                        TextOut.Append("background: #00b050;");
                        GreenNum += 1;
                    }
                    else if (TargetNum < 0)
                    {
                        TextOut.Append("background: #ff0000;");
                        RedNum += 1;
                    }
                    else
                    {
                        TextOut.Append("background: #ffff00;");
                        YellowNum += 1;
                    }
                    TextOut.Append(" color:#000;\">" + (TargetNum) + "</td>");
                    TextOut.Append("</tr>\r\n");

                    currentUserPaperList     = null;
                    currentUserPassPaperList = null;
                }
                PostModel = null;
                time1.Stop();
                log.Write(Info.RealName + "执行时间为:" + time1.Elapsed.Milliseconds);
            }
            TestPaperList = null;
            if (FirstPassCourseNum > 0)
            {
                TextOut.Append("<tr><th colspan=\"" + (ColNum + WeekNum * 3) + "\">课程考试通过数量最多的学霸为: <font color=red>" + PassCourseFirstUser + "</font>  ,数量为: <font color=red>" + FirstPassCourseNum.ToString() + "</font> 。</th></tr>");
            }
            if (!string.IsNullOrEmpty(GoodStudent))
            {
                TextOut.Append("<tr><th colspan=\"" + (ColNum + WeekNum * 3) + "\">月度考试数量超过30门的为好学生,此次好学生为: <font color=red>" + GoodStudent + "</font> 。</th></tr>");
            }
            TextOut.Append("<tr><th colspan=\"" + (ColNum + WeekNum * 3) + "\">未达标人数:" + RedNum.ToString() + " 刚好达标人数:" + YellowNum.ToString() + " 超越目标人数:" + GreenNum.ToString() + "</th></tr>");
            TextOut.Append("<tr><th colspan=\"" + (ColNum + WeekNum * 3) + "\">未达标人数:" + RedNum.ToString() + " 达标人数:" + (YellowNum + GreenNum).ToString() + " 达成率:" + ((double)(YellowNum + GreenNum) / (double)PeoperNum).ToString("P") + "</th></tr>");
            TextOut.Append("</table>");
            if (string.IsNullOrEmpty(Type))
            {
                return(TextOut.ToString());
            }
            else
            {
                GroupResult[1] = (int)GroupResult[1] + PeoperNum;
                GroupResult[2] = (int)GroupResult[2] + (YellowNum + GreenNum);
                GroupResult[3] = (int)GroupResult[3] + RedNum;
                if (((double)(YellowNum + GreenNum) / (double)PeoperNum) == 1.0)
                {
                    GroupResult[4] = GroupResult[4] + "<span style=\"margin:0px 10px;\">" + company.CompanySimpleName + "</span>";
                }
                else if (((double)(YellowNum + GreenNum) / (double)PeoperNum) < 0.7)
                {
                    GroupResult[5] = GroupResult[5] + "<span style=\"margin:0px 10px;\">" + company.CompanySimpleName + "</span>";
                }
                //GroupResult[4] += ((double)(YellowNum + GreenNum) / (double)PeoperNum);
                return("<tr><td>" + company.CompanySimpleName + "</td><td>" + PeoperNum + "</td><td>" + (YellowNum + GreenNum).ToString() + "</td><td>" + RedNum.ToString() + "</td><td>" + ((double)(YellowNum + GreenNum) / (double)PeoperNum).ToString("P") + "</td></tr>");
            }
        }
Example #22
0
        public ActionResult UploadImage()
        {
            string filePath = "/Upload/ProductPhoto/Original/" + RequestHelper.DateNow.ToString("yyyyMM") + "/";

            if (FileHelper.SafeFullDirectoryName(filePath))
            {
                try
                {
                    //上传文件
                    UploadHelper upload = new UploadHelper();
                    upload.Path           = "/Upload/ProductPhoto/Original/" + RequestHelper.DateNow.ToString("yyyyMM") + "/";
                    upload.FileType       = ShopConfig.ReadConfigInfo().UploadFile;
                    upload.FileNameType   = FileNameType.Guid;
                    upload.MaxWidth       = ShopConfig.ReadConfigInfo().AllImageWidth;  //整站图片压缩开启后的压缩宽度
                    upload.AllImageIsNail = ShopConfig.ReadConfigInfo().AllImageIsNail; //整站图片压缩开关
                    int needNail = RequestHelper.GetQueryString <int>("NeedNail");
                    if (needNail <= 0)
                    {
                        upload.AllImageIsNail = 0;                                       //如果页面传值不压缩图片,以页面传值为准;
                    }
                    int curMaxWidth = RequestHelper.GetQueryString <int>("CurMaxWidth"); //页面传值最大宽度
                    if (curMaxWidth > 0)
                    {
                        upload.AllImageIsNail = 1;
                        upload.MaxWidth       = curMaxWidth;//如果有页面传值设置图片最大宽度,以页面传值为准
                    }
                    FileInfo file      = null;
                    int      waterType = ShopConfig.ReadConfigInfo().WaterType;

                    //前台上传图片不打水印直接保存
                    file = upload.SaveAs();

                    //生成处理
                    string originalFile = upload.Path + file.Name;
                    string otherFile    = string.Empty;
                    string makeFile     = string.Empty;

                    Dictionary <int, int> dic = new Dictionary <int, int>();

                    if (!dic.ContainsKey(75))
                    {
                        dic.Add(75, 75);                      //后台商品图集默认使用尺寸(如果不存在则手动添加)
                    }
                    foreach (KeyValuePair <int, int> de in dic)
                    {
                        makeFile   = originalFile.Replace("Original", de.Key + "-" + de.Value);
                        otherFile += makeFile + "|";
                        ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(originalFile), ServerHelper.MapPath(makeFile), Convert.ToInt32(de.Key), Convert.ToInt32(de.Value), ThumbnailType.AllFix);
                    }
                    otherFile = otherFile.Substring(0, otherFile.Length - 1);
                    int proStyle = RequestHelper.GetForm <int>("proStyle");
                    if (proStyle < 0)
                    {
                        proStyle = 0;
                    }

                    int pcid = RequestHelper.GetForm <int>("pcid");
                    ProductPhotoInfo productPhoto = new ProductPhotoInfo();
                    productPhoto.ProductId = pcid;
                    productPhoto.ImageUrl  = originalFile;
                    productPhoto.ProStyle  = proStyle;
                    productPhoto.OrderId   = 0;

                    ProductPhotoBLL.Add(productPhoto);
                    return(Content("ok|" + originalFile.Replace("Original", "75-75")));
                }
                catch (Exception ex)
                {
                    return(Content(ex.Message));
                }
            }
            else
            {
                return(Content(ShopLanguage.ReadLanguage("ErrorPathName")));
            }
        }
Example #23
0
        protected void UploadImage(object sender, EventArgs e)
        {
            //取得传递值
            string control  = RequestHelper.GetQueryString <string>("Control");
            int    tableID  = RequestHelper.GetQueryString <int>("TableID");
            string filePath = RequestHelper.GetQueryString <string>("FilePath");
            string fileType = ShopConfig.ReadConfigInfo().UploadImage;

            if (FileHelper.SafeFullDirectoryName(filePath))
            {
                try
                {
                    //上传文件
                    UploadHelper upload = new UploadHelper();
                    upload.Path           = "/Upload/" + filePath + "/" + RequestHelper.DateNow.ToString("yyyyMM") + "/";
                    upload.FileType       = fileType;
                    upload.FileNameType   = FileNameType.Guid;
                    upload.MaxWidth       = ShopConfig.ReadConfigInfo().AllImageWidth;  //整站图片压缩开启后的压缩宽度
                    upload.AllImageIsNail = ShopConfig.ReadConfigInfo().AllImageIsNail; //整站图片压缩开关
                    int needNail = RequestHelper.GetQueryString <int>("NeedNail");
                    if (needNail == 0)
                    {
                        upload.AllImageIsNail = 0;                                       //如果页面有传值且值为0不压缩图片,以页面传值为准;
                    }
                    int curMaxWidth = RequestHelper.GetQueryString <int>("CurMaxWidth"); //页面传值最大宽度
                    if (curMaxWidth > 0)
                    {
                        upload.AllImageIsNail = 1;
                        upload.MaxWidth       = curMaxWidth;//如果有页面传值设置图片最大宽度,以页面传值为准
                    }
                    FileInfo file      = null;
                    int      waterType = ShopConfig.ReadConfigInfo().WaterType;

                    if (waterType == 2 || waterType == 3)
                    {
                        string needMark = RequestHelper.GetQueryString <string>("NeedMark");
                        if (needMark == string.Empty || needMark == "1")
                        {
                            int    waterPossition = ShopConfig.ReadConfigInfo().WaterPossition;
                            string text           = ShopConfig.ReadConfigInfo().Text;
                            string textFont       = ShopConfig.ReadConfigInfo().TextFont;
                            int    textSize       = ShopConfig.ReadConfigInfo().TextSize;
                            string textColor      = ShopConfig.ReadConfigInfo().TextColor;
                            string waterPhoto     = Server.MapPath(ShopConfig.ReadConfigInfo().WaterPhoto);

                            file = upload.SaveAs(waterType, waterPossition, text, textFont, textSize, textColor, waterPhoto);
                        }
                        else if (needMark == "0")
                        {
                            file = upload.SaveAs();
                        }
                    }
                    else
                    {
                        file = upload.SaveAs();
                    }
                    //生成处理
                    string originalFile       = upload.Path + file.Name;
                    string otherFile          = string.Empty;
                    string makeFile           = string.Empty;
                    Dictionary <int, int> dic = new Dictionary <int, int>();
                    if (tableID == ProductBLL.TableID)
                    {
                        foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.Product))
                        {
                            dic.Add(phototype.Width, phototype.Height);
                        }
                        if (!dic.ContainsKey(90))
                        {
                            dic.Add(90, 90);                      //后台商品列表默认使用尺寸(如果不存在则手动添加)
                        }
                    }
                    else if (tableID == ProductBrandBLL.TableID)
                    {
                        dic.Add(88, 31);
                    }
                    else if (tableID == ThemeActivityBLL.TableID)
                    {
                        dic.Add(300, 150);
                    }
                    else if (tableID == ArticleBLL.TableID)
                    {
                        foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.Article))
                        {
                            dic.Add(phototype.Width, phototype.Height);
                        }
                    }
                    else if (tableID == FavorableActivityGiftBLL.TableID)
                    {
                        dic.Add(100, 100);
                    }
                    else
                    {
                    }
                    if (dic.Count > 0)
                    {
                        foreach (KeyValuePair <int, int> kv in dic)
                        {
                            makeFile   = originalFile.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString());
                            otherFile += makeFile + "|";
                            ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(originalFile), ServerHelper.MapPath(makeFile), kv.Key, kv.Value, ThumbnailType.InBox);
                        }
                        otherFile = otherFile.Substring(0, otherFile.Length - 1);
                    }
                    ResponseHelper.Write("<script>alert('上传成功');  window.parent.o('" + IDPrefix + control + "').value='" + originalFile + "';if(window.parent.o('img_" + control + "')){window.parent.o('img_" + control + "').src='" + originalFile + "';};if(window.parent.o('imgurl_" + control + "')){window.parent.o('imgurl_" + control + "').href='" + originalFile + "';window.parent.o('imgurl_" + control + "').target='_blank'}</script>");
                    //保存数据库
                    UploadInfo tempUpload = new UploadInfo();
                    tempUpload.TableID      = tableID;
                    tempUpload.ClassID      = 0;
                    tempUpload.RecordID     = 0;
                    tempUpload.UploadName   = originalFile;
                    tempUpload.OtherFile    = otherFile;
                    tempUpload.Size         = Convert.ToInt32(file.Length);
                    tempUpload.FileType     = file.Extension;
                    tempUpload.RandomNumber = Cookies.Admin.GetRandomNumber(false);
                    tempUpload.Date         = RequestHelper.DateNow;
                    tempUpload.IP           = ClientHelper.IP;
                    UploadBLL.AddUpload(tempUpload);
                }
                catch (Exception ex)
                {
                    //ExceptionHelper.ProcessException(ex, false);
                    ResponseHelper.Write("<script>alert('" + ex.Message + "');  </script>");
                }
            }
            else
            {
                ScriptHelper.Alert(ShopLanguage.ReadLanguage("ErrorPathName"));
            }
        }
Example #24
0
 public string GetThemePath(string themeName)
 {
     return(ServerHelper.MapPath($"{ApplicationConfig.ThemeDirectory}/{themeName}"));
 }
Example #25
0
 /// <summary>
 /// 静态构造函数
 /// </summary>
 static GroupBuyAccessHelper()
 {
     accessHelper = new AccessHelper();
     accessHelper.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0.1;Data Source = " + ServerHelper.MapPath("/Plugins/Activity/GroupBuy/GroupBuy.mdb");
     tablePrefix = "SocoShop_";
 }
Example #26
0
        public async Task RegisterTimeZone([Summary("Your IANA or Windows timezone")][Remainder] string timeZone = null)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed registertimezone ({timezone}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, timeZone, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (await ServerHelper.CheckIfContextIsDM(Context))
            {
                return;
            }

            if (timeZone == null)
            {
                await Context.Channel.SendEmbedAsync("Provide a Time Zone", "Please provide a valid windows or IANA timezone.",
                                                     ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));

                return;
            }

            if (!TryParseTimeZone(timeZone, out TimeZoneInfo timeZoneInfo))
            {
                await Context.Channel.SendEmbedAsync("Invalid Time Zone", "Please provide a valid windows or IANA timezone.",
                                                     ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));
            }
            else
            {
                var user = await _userRepository.GetByUserId(Context.User.Id);

                if (user == null)
                {
                    await _userRepository.AddAsync(new User { UserId = Context.User.Id, UserName = Context.User.Username });

                    user = await _userRepository.GetByUserId(Context.User.Id);
                }

                var userTimeZone = await _userTimeZones.GetByUserID(Context.User.Id);

                if (userTimeZone == null)
                {
                    if (user == null)
                    {
                        await _userRepository.AddAsync(new User { UserId = Context.User.Id, UserName = Context.User.Username });
                    }

                    var userTz = new UserTimeZone
                    {
                        UserId   = user.Id,
                        TimeZone = timeZone,
                    };

                    await _userTimeZones.AddAsync(userTz);

                    await Context.Channel.SendEmbedAsync("Succesfully Registered", $"Successfully registered your time zone: `{timeZoneInfo.DisplayName}`",
                                                         ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));
                }
                else
                {
                    userTimeZone.TimeZone = timeZone;
                    await _userTimeZones.EditAsync(userTimeZone);

                    await Context.Channel.SendEmbedAsync("Succesfully Updated", $"Successfully updated your time zone: `{timeZoneInfo.DisplayName}`",
                                                         ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));
                }
            }
        }
        /// <summary>
        /// Auth the specified connectionProfile.
        /// </summary>
        /// <param name="connectionProfile">Connection profile.</param>
        public void Auth(ConnectionProfile connectionProfile)
        {
            //send login packet
            ServerPacketUserLogin serverPacketUserLogin = ServerHelper.LoginUserHashed(connectionProfile.UserName, connectionProfile.UserPassword);

            //if login success
            if (serverPacketUserLogin.NetworkError == NetworkError.NONE)
            {
                //set actual user infos
                Application.ActualUser   = serverPacketUserLogin.UserProfile;
                Application.UserPassword = tfPasswordField.Text;


                if (serverPacketUserLogin.UserAccountActivate)
                {
                    if (serverPacketUserLogin.UserDAuthPrivateKey != null)
                    {
                        Application.ActualUserPrivateKey = serverPacketUserLogin.UserDAuthPrivateKey;

                        PerformSegue("DAuthLoginSegue", this);
                        return;
                    }


                    //load user pets
                    Application.PetManager.LoadUserPetList(serverPacketUserLogin.UserProfile);

                    //instantiate main view controller
                    UIStoryboard         mainBoard            = UIStoryboard.FromName("Main", null);
                    MainTabBarController mainTabBarController = mainBoard.InstantiateViewController("MainTabBarController") as MainTabBarController;
                    PresentViewController(mainTabBarController, true, null);
                }
                else
                {
                    PerformSegue("ConnectConfirmAccountSegue", this);
                }
                return;
            }

            //chose right error message
            String messageError = string.Empty;

            switch (serverPacketUserLogin.NetworkError)
            {
            case NetworkError.GLOBAL_UNKNOWN:
                goto default;

            case NetworkError.SQL_USER_UNKNOWN:
                messageError = "Utilisateur ou mot de passe incorect";
                break;

            case NetworkError.SERVER_UNAVAILABLE:
                messageError = MSGBank.ERROR_NO_SERVER;
                break;

            default:
                messageError = MSGBank.ERROR_UNKNOWN;
                break;
            }
            BarHelper.DisplayErrorBar(uivMainView, MSGBank.ERROR_TITLE, messageError, 5);
            //ßMessageBox.ShowOK(MSGBank.ERROR_TITLE, messageError, this);
        }
Example #28
0
        public bool HandleZipUpload(byte[] fileBytes)
        {
            //get a temporary file from provided bytes
            var zipFile = _localFileProvider.GetTemporaryFile(fileBytes);

            //get temporary directory to extract the package
            var tempDirectory = _localFileProvider.GetTemporaryDirectory();

            try
            {
                //first extract the zip
                _localFileProvider.ExtractArchive(zipFile, tempDirectory);

                var metaJsonFile = _localFileProvider.CombinePaths(tempDirectory, "meta.json");
                if (!_localFileProvider.FileExists(metaJsonFile))
                {
                    _logger.Log <PluginAccountant>(LogLevel.Error, "Unsupported or damaged package uploaded");
                    return(false);
                }

                var packageMeta =
                    _dataSerializer.DeserializeAs <PackageMeta>(_localFileProvider.ReadAllText(metaJsonFile));
                if (packageMeta?.Items == null || !packageMeta.Items.Any())
                {
                    _logger.Log <PluginAccountant>(LogLevel.Error, "Unsupported or damaged package uploaded");
                    return(false);
                }

                var pluginsDirectory = ServerHelper.MapPath("~/Plugins");
                var themesDirectory  = ServerHelper.MapPath("~/Content/Themes");
                //extract each supported folder to themes and plugins
                foreach (var itemMeta in packageMeta.Items)
                {
                    //skip the version not supported
                    if (!AppVersionEvaluator.IsVersionSupported(itemMeta.SupportedVersion))
                    {
                        continue;
                    }

                    var itemDirectory        = _localFileProvider.CombinePaths(tempDirectory, itemMeta.Path);
                    var destinationDirectory = "";
                    destinationDirectory = _localFileProvider.CombinePaths(
                        packageMeta.Package == PackageMeta.PackageType.Plugin ? pluginsDirectory : themesDirectory,
                        packageMeta.PackageDirectoryName);

                    _localFileProvider.CopyDirectory(itemDirectory, destinationDirectory, true);

                    //load the package
                    var configFile = _localFileProvider.CombinePaths(destinationDirectory, "config.json");
                    if (packageMeta.Package == PackageMeta.PackageType.Plugin)
                    {
                        PluginLoader.LoadPluginFromConfig(configFile, true);
                    }
                    if (packageMeta.Package == PackageMeta.PackageType.Theme)
                    {
                        DependencyResolver.Resolve <IThemeProvider>().LoadTheme(destinationDirectory, true);
                    }
                }

                return(true);
            }
            catch (InvalidDataException ex)
            {
                _logger.Log <PluginAccountant>(LogLevel.Error, "The package doesn't appear to be a valid zip file.", ex);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.Log <PluginAccountant>(LogLevel.Error, ex.Message, ex);
                return(false);
            }
            finally
            {
                _localFileProvider.DeleteDirectory(tempDirectory, true);
                _localFileProvider.DeleteFile(zipFile);
            }
        }
Example #29
0
 public static string GetShareLink(Server server)
 {
     return(ServerHelper.GetUtilByTypeName(server.Type).GetShareLink(server));
 }
Example #30
0
        /// <summary>
        /// 上传用户头像
        /// </summary>
        /// <returns></returns>
        protected string UploadUserPhoto()
        {
            string originalFile = string.Empty;

            if (HttpContext.Current.Request.Files[0].FileName != string.Empty)
            {
                try
                {
                    //上传文件
                    UploadHelper upload = new UploadHelper();
                    upload.Path     = "/Upload/UserPhoto/Original/";
                    upload.FileType = ShopConfig.ReadConfigInfo().UploadFile;
                    FileInfo file = upload.SaveAs();
                    //生成处理
                    originalFile = upload.Path + file.Name;
                    string otherFile          = string.Empty;
                    string makeFile           = string.Empty;
                    Dictionary <int, int> dic = new Dictionary <int, int>();
                    dic.Add(70, 70);
                    dic.Add(190, 190);
                    foreach (KeyValuePair <int, int> kv in dic)
                    {
                        makeFile   = originalFile.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString());
                        otherFile += makeFile + "|";
                        ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(originalFile), ServerHelper.MapPath(makeFile), kv.Key, kv.Value, ThumbnailType.InBox);
                    }
                    otherFile = otherFile.Substring(0, otherFile.Length - 1);
                    //保存数据库
                    UploadInfo tempUpload = new UploadInfo();
                    tempUpload.TableID    = UserBLL.TableID;
                    tempUpload.ClassID    = 0;
                    tempUpload.RecordID   = 0;
                    tempUpload.UploadName = originalFile;
                    tempUpload.OtherFile  = otherFile;
                    tempUpload.Size       = Convert.ToInt32(file.Length);
                    tempUpload.FileType   = file.Extension;
                    tempUpload.Date       = RequestHelper.DateNow;
                    tempUpload.IP         = ClientHelper.IP;
                    UploadBLL.AddUpload(tempUpload);
                }
                catch (Exception ex)
                {
                    ExceptionHelper.ProcessException(ex, false);
                }
            }
            return(originalFile);
        }
Example #31
0
 public CommandHandler(IServiceProvider provider, DiscordSocketClient client, CommandService service, IConfiguration config, Servers servers, ServerHelper serverHelper, Images images)
 {
     _provider     = provider;
     _client       = client;
     _service      = service;
     _config       = config;
     _servers      = servers;
     _serverHelper = serverHelper;
     _images       = images;
 }