Ejemplo n.º 1
0
        private CSharpRepoGenerator.RepositoryFunction GenerateListByForeignKey(RepositoryMemberInfo repositoryMembmerInfo)
        {
            string returnType = GetClassName(repositoryMembmerInfo);
            var    mainKey    = repositoryMembmerInfo.Info.QueryKey;

            string mainKeyType       = GetMemberType(mainKey);
            string methodSuffix      = mainKey.HasReference && (!Config.Entities.StrongTypes || !CanBeStronger(mainKey)) ? mainKey.Name : "";
            string mainKeyFieldLower = StringExt.ToCamelCase(mainKey.Name);

            var signature = $"Task<List<{returnType}>> GetBy{methodSuffix}({mainKeyType} {mainKeyFieldLower})";

            var template = $@"
public async {signature}
{{
    using (var db = GetDb())
    {{
        var payload = new
                        {{
                            {mainKey.Name} = {StrongTypeCastingType(mainKey)}{mainKeyFieldLower}
                        }};

        var result = await db.QuerySprocAsync<{returnType}>(""{repositoryMembmerInfo.Info.Name}"", payload).ConfigureAwait(continueOnCapturedContext: false);

        return result.ToList();
    }}
}}";

            return(new CSharpRepoGenerator.RepositoryFunction
            {
                Body = template,
                Signature = signature
            });
        }
Ejemplo n.º 2
0
        public static bool CorrigirQuestaoAluno(string codAvaliacao, string matrAluno, int codQuestao, double notaObtida, string profObservacao)
        {
            if (!StringExt.IsNullOrWhiteSpace(codAvaliacao, matrAluno) && codQuestao != 0)
            {
                AvalAcadReposicao aval  = ListarPorCodigoAvaliacao(codAvaliacao);
                Aluno             aluno = Aluno.ListarPorMatricula(matrAluno);
                int codPessoaFisica     = aluno.Usuario.PessoaFisica.CodPessoa;

                AvalQuesPessoaResposta resposta = aval.Avaliacao.PessoaResposta.FirstOrDefault(pr => pr.CodQuestao == codQuestao && pr.CodPessoaFisica == codPessoaFisica);

                resposta.RespNota       = notaObtida;
                resposta.ProfObservacao = profObservacao;

                aval.Avaliacao.AvalPessoaResultado
                .Single(r => r.CodPessoaFisica == codPessoaFisica)
                .Nota = aval.Avaliacao.PessoaResposta
                        .Where(pr => pr.CodPessoaFisica == codPessoaFisica)
                        .Average(pr => pr.RespNota);

                contexto.SaveChanges();

                return(true);
            }

            return(false);
        }
Ejemplo n.º 3
0
        public ActionResult CarregarRespostasPorQuestao(string codigo, string codQuestao)
        {
            if (!StringExt.IsNullOrWhiteSpace(codigo, codQuestao))
            {
                AvalAcademica acad           = AvalAcademica.ListarPorCodigoAvaliacao(codigo);
                int           codQuestaoTemp = int.Parse(codQuestao);

                var retorno = from questao in acad.Avaliacao.PessoaResposta
                              orderby questao.PessoaFisica.Nome
                              where questao.CodQuestao == codQuestaoTemp &&
                              questao.AvalTemaQuestao.QuestaoTema.Questao.CodTipoQuestao == TipoQuestao.DISCURSIVA
                              select new
                {
                    alunoMatricula       = acad.AlunosRealizaram.FirstOrDefault(a => a.Usuario.CodPessoaFisica == questao.CodPessoaFisica).Usuario.Matricula,
                    alunoNome            = questao.PessoaFisica.Nome,
                    codQuestao           = questao.CodQuestao,
                    questaoEnunciado     = questao.AvalTemaQuestao.QuestaoTema.Questao.Enunciado,
                    questaoChaveResposta = questao.AvalTemaQuestao.QuestaoTema.Questao.ChaveDeResposta,
                    alunoResposta        = questao.RespDiscursiva,
                    notaObtida           = questao.RespNota.HasValue ? questao.RespNota.Value.ToValueHtml() : "",
                    correcaoComentario   = questao.ProfObservacao != null ? questao.ProfObservacao : "",
                    flagCorrigida        = questao.RespNota != null ? true : false
                };
                return(Json(retorno));
            }
            return(Json(null));
        }
Ejemplo n.º 4
0
        public bool Validate()
        {
            if (!validInterfaceTypes.Contains(InterfaceType))
            {
                return(false);
            }

            if (!validIPTypes.Contains(IPType))
            {
                return(false);
            }

            if (IPType.ToLower() == validIPTypes[1].ToString())
            {
                if (StringExt.IsNullOrEmpty(IPAddress) || StringExt.IsNullOrEmpty(Subnet) || StringExt.IsNullOrEmpty(Gateway))
                {
                    return(false);
                }
            }

            if (InterfaceType.ToLower() == validInterfaceTypes[1].ToString())
            {
                if (StringExt.IsNullOrEmpty(SSID))// || StringExt.IsNullOrEmpty(Passcode))
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 5
0
        public static YrsMosDate StringToYrsMosDate(string str)
        {
            string value = String.Empty;

            if (String.IsNullOrEmpty(str))
            {
                return(null);
            }

            string[] stNum;
            string[] seperator = { "yrs", "mos" };
            if (!str.Contains("yrs"))
            {
                return(null);
            }
            stNum = str.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < stNum.Length; i++)
            {
                stNum[i] = stNum[i].Trim();
                if (stNum[i].Length == 1)
                {
                    stNum[i] = "0" + stNum[i];
                }
                value += stNum[i];
            }

            if (StringExt.IsNumeric(value))
            {
                YrsMosDate estLife = new YrsMosDate().SetYrsMosDate(value);
                return(estLife);
            }
            return(null);
        }
 public virtual IActionResult Delete(int id, string grid)
 {
     try
     {
         var item = Repo.GetItem(id);
         if (item == null)
         {
             return(new JavascriptResult(StringExt.JsAlert(UI.NotFound)));
         }
         if (OnDeleteCheck(item))
         {
             if (Repo.Delete(item))
             {
                 OnAfterDelete(id);
                 return(new JavascriptResult(!grid.IsEmpty()
                     ? string.Format(DeleteJsAction2, grid)
                     : DeleteJsAction));
             }
             return(new JavascriptResult(StringExt.JsAlert(MvcLogger.GetErrorMessage(ModelState))));
         }
         return(new JavascriptResult(StringExt.JsAlert(UI.NoAccess)));
     }
     catch (Exception ex)
     {
         return(new JavascriptResult(StringExt.JsAlert(MvcLogger.GetErrorMessage(ex))));
     }
 }
Ejemplo n.º 7
0
        public override PwEntry CreatePwEntry(PwDatabase pwStorage)
        {
            PwEntry entry = new PwEntry(true, true)
            {
                IconId = PwIcon.Identity
            };

            entry.CreationTime = DateTimeExt.FromUnixTimeStamp(createdAt);

            entry.LastModificationTime = DateTimeExt.FromUnixTimeStamp(updatedAt);

            entry.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, StringExt.GetValueOrEmpty(title)));
            entry.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, StringExt.GetValueOrEmpty(secureContents.member_name)));
            entry.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, StringExt.GetValueOrEmpty(secureContents.membership_no)));
            entry.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, StringExt.GetValueOrEmpty(secureContents.website)));
            entry.Strings.Set("Mitglied seit", new ProtectedString(false, StringExt.GetValueOrEmpty(secureContents.member_since_mm).PadLeft(2, '0') + " / " + StringExt.GetValueOrEmpty(secureContents.member_since_yy).PadLeft(4, '0')));
            entry.Strings.Set("Organisation", new ProtectedString(false, StringExt.GetValueOrEmpty(secureContents.org_name)));

            if (!string.IsNullOrEmpty(StringExt.GetValueOrEmpty(secureContents.notesPlain)))
            {
                entry.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, StringExt.GetValueOrEmpty(secureContents.notesPlain)));
            }

            return(entry);
        }
Ejemplo n.º 8
0
            public void Test(int testNum)
            {
                StringCharSourceFile  input  = new StringCharSourceFile(Input);
                BooLexerCore          lexer  = new BooLexerCore(input, new Dictionary <string, Symbol>());
                IEnumerator <AstNode> lexerE = lexer.GetEnumerator();

                string[] toks = Toks.Split(',');
                AstNode  t;

                for (int i = 0; i < toks.Length; i++)
                {
                    var    _ = StringExt.SplitAt(toks[i], ':');
                    string wantType = _.A, wantText = _.B;

                    wantType = wantType.Trim();

                    // Get the next token
                    Assert.IsTrue(lexerE.MoveNext());
                    t = lexerE.Current;
                    string type = t.NodeType.Name;
                    string msg  = string.Format("Test[{0}][{1}]: Expected {2}<{3}>, got {4}<{5}>",
                                                testNum, i, wantType, wantText, type, t.SourceText);
                    Assert.AreEqual(wantType, type, msg);
                    Assert.AreEqual(wantText, t.SourceText, msg);
                }
                Assert.IsFalse(lexerE.MoveNext());
            }
Ejemplo n.º 9
0
        public override void DrawAutoCompleteMember(int id, string searchTerms, bool selected)
        {
            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            GUILayout.Label("",
                            new GUIStyle()
            {
                fixedWidth  = 20,
                fixedHeight = 20,
                normal      = { background =
                                    MonkeyStyle.GetIconForFile("fake.unity") }
            });

            GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
            GUILayout.Label(GetStringValue(id).Highlight(searchTerms, true,
                                                         StringExt.ColorTag(MonkeyStyle.Instance.SearchResultTextColor),
                                                         StringExt.ColorTagClosing,
                                                         StringExt.ColorTag(MonkeyStyle.Instance.HighlightOnSelectedTextColor),
                                                         StringExt.ColorTagClosing), MonkeyStyle.Instance.CommandNameStyle,
                            GUILayout.ExpandWidth(true));
            GUILayout.EndHorizontal();

            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
        }
Ejemplo n.º 10
0
        private IEnumerator displayWordByWord()
        {
            // Word by word
            string[] array = instructions[0].message.Split(' ');
            textWrapper.setText(array[0]);

            yield return(new WaitForSeconds(StringExt.RichTextLength(array[0]) * displayTimePerCharacter));

            for (int i = 1; i < array.Length && !skipAnimation; i++)
            {
                textWrapper.appendText(" " + array[i]);
                yield return(new WaitForSeconds(StringExt.RichTextLength(array[i]) * displayTimePerCharacter));
            }

            float timeToWait = additionalDisplayTime;

            while (timeToWait > 0f && !skipAnimation)
            {
                timeToWait -= Time.deltaTime;
                yield return(null);
            }

            textWrapper.setText(instructions[0].message);

            // End word by word
        }
Ejemplo n.º 11
0
        private void playSound()
        {
            if (instructions[0].audioClip != null)
            {
                if (!audioController)
                {
                    Debug.LogWarning("No audiocontroller found in scene.");
                }
                else if (!audioSource)
                {
                    Debug.LogWarning("No audiomixer reference found in: " + name);
                }
                else
                {
                    displayTimePerCharacter = instructions[0].audioClip.length /
                                              StringExt.RichTextLength(instructions[0].message);

                    audioController.playTrack(instructions[0].audioClip, audioSource, false, true);
                }
            }
            else
            {
                displayTimePerCharacter = initialDisplayTimePerCharacter;
            }
        }
Ejemplo n.º 12
0
        private CSharpRepoGenerator.RepositoryFunction GenerateUpsert(RepositoryMemberInfo repositoryMembmerInfo)
        {
            var    className = GetClassName(repositoryMembmerInfo);
            string typeName  = StringExt.ToCamelCase(className);

            var    mainKey = FindMainKey(repositoryMembmerInfo.Info.BaseAtom);
            string keyType = GetMemberType(mainKey);

            string updateFields = GetUpdateFields(repositoryMembmerInfo, StringExt.ToCamelCase(className))
                                  .IndentAllLines(7, true);

            var signature = $"Task<{keyType}> Upsert({className} {typeName})";

            var template = $@"
public async {signature}
{{
    using (var db = GetDb())
    {{
        var payload = new
                        {{
                            {updateFields}
                        }};

        return (await db.QuerySprocAsync<{keyType}>(""{repositoryMembmerInfo.Info.Name}"", payload).ConfigureAwait(continueOnCapturedContext: false)).FirstOrDefault();
    }}
}}";

            return(new CSharpRepoGenerator.RepositoryFunction
            {
                Body = template,
                Signature = signature
            });
        }
Ejemplo n.º 13
0
        private CSharpRepoGenerator.RepositoryFunction GenerateSoftDelete(RepositoryMemberInfo repositoryMembmerInfo)
        {
            var    mainKey           = repositoryMembmerInfo.Info.QueryKey;
            string mainKeyName       = mainKey.Name;
            string mainKeyType       = GetMemberType(mainKey);
            string mainKeyFieldLower = StringExt.ToCamelCase(mainKey.Name);
            string strongTypeCasting = StrongTypeCastingType(mainKey);


            var signature = $"Task SoftDelete({mainKeyType} {mainKeyFieldLower})";

            var template = $@"
public async {signature}
{{
    using (var db = GetDb())
    {{
        var payload = new
                        {{
                            {mainKeyName} = {strongTypeCasting}{mainKeyFieldLower}
                        }};

        await db.ExecSprocAsync(""{repositoryMembmerInfo.Info.Name}"", payload).ConfigureAwait(continueOnCapturedContext: false);
    }}
}}";

            return(new CSharpRepoGenerator.RepositoryFunction
            {
                Body = template,
                Signature = signature
            });
        }
Ejemplo n.º 14
0
        private CSharpRepoGenerator.RepositoryFunction GenerateUpdate(RepositoryMemberInfo repositoryMembmerInfo)
        {
            var    className    = CSharpCodeClassGenerator.GetClassName(repositoryMembmerInfo.Info.BaseAtom);
            string updateFields = GetUpdateFields(repositoryMembmerInfo, StringExt.ToCamelCase(className))
                                  .IndentAllLines(7, true);

            var signature = $"Task Update({className} {StringExt.ToCamelCase(className)})";

            var template = $@"
public async {signature}
{{
    using (var db = GetDb())
    {{
        var payload = new
                        {{
                            {updateFields}
                        }};

        await db.ExecSprocAsync(""{repositoryMembmerInfo.Info.Name}"", payload).ConfigureAwait(continueOnCapturedContext: false);
    }}
}}";

            return(new CSharpRepoGenerator.RepositoryFunction
            {
                Body = template,
                Signature = signature
            });
        }
Ejemplo n.º 15
0
 void Awake()
 {
     manager = new GroupManager(caseSensitive);
     GroupManager.Group firstState = null;
     if (states != null)
     {
         foreach (string name in states)
         {
             if (!StringExt.IsNullOrWhitespace(name))
             {
                 GroupManager.Group s;
                 s = manager.Add(name);
                 if (firstState == null)
                 {
                     firstState = s;
                 }
             }
         }
     }
     if (main)
     {
         GroupManager.main = manager;
         if (firstState != null)
         {
             manager.activeGroup = firstState;
         }
     }
 }
Ejemplo n.º 16
0
        private static void RunCli(CliOptions options)
        {
            if (StringExt.IsNullOrWhiteSpace(options.Game.Value))
            {
                Console.WriteLine($"Empty game specified. Exiting...");
            }

            var userDataAccessor = new UserDataAccessor();

            var game = userDataAccessor.GetFirstGameWithName(options.Game.Value);

            if (StringExt.IsNullOrWhiteSpace(game.DOSEXEPath))
            {
                game = userDataAccessor.GetGameWithMainExecutable(options.Game.Value);
            }
            if (options.Setup.IsProvided)
            {
                if (options.Verbose.IsProvided)
                {
                    Console.WriteLine($"Running '{game.Name}''s setup executable: {game.SetupEXEPath}...");
                }
                game.RunSetup(userDataAccessor.GetUserData());
            }
            else
            {
                if (options.Verbose.IsProvided)
                {
                    Console.WriteLine($"Running the game named '{game.Name}' via the main executable at {game.DOSEXEPath}...");
                }

                game.Run(userDataAccessor.GetUserData());
            }
        }
Ejemplo n.º 17
0
        public UnidicEntry(string surfaceForm, Option <string> feature)
        {
            SurfaceForm = surfaceForm;
            IsRegular   = feature.HasValue;
            if (!IsRegular)
            {
                return;
            }

            var features = feature
                           .Map(f => StringExt.SplitWithQuotes(f, ',', '"').ToArray())
                           .ValueOr(Array.Empty <string>());

            PartOfSpeech          = MeCabEntryParser.PartOfSpeechFromString(MeCabEntryParser.OrNull(features, 0)); // f[0]:  pos1
            ConjugatedForm        = MeCabEntryParser.OrNull(features, 5);                                          // ; f[5]:  cForm
            DictionaryForm        = MeCabEntryParser.OrNull(features,  10);                                        // ; f[10]: orthBase
            Pronunciation         = MeCabEntryParser.OrNull(features, 9);                                          // ; f[9]:  pron
            Reading               = MeCabEntryParser.OrNull(features, 20);                                         // ; f[20]: kana
            DictionaryFormReading = MeCabEntryParser.OrNull(features, 21);                                         // ; f[21]: kanaBase
            Type = MeCabEntryParser.TypeFromString(ConjugatedForm);
            // ; f[1]:  pos2
            // ; f[2]:  pos3
            // ; f[3]:  pos4
            PartOfSpeechSections = features
                                   .Skip(1)
                                   .Take(3)
                                   .Where(f => f != "*")
                                   .ToList()
                                   .AsReadOnly();
        }
Ejemplo n.º 18
0
        public ActionResult CarregarRespostasDiscursivas(string codigo, string matrAluno)
        {
            if (!StringExt.IsNullOrWhiteSpace(codigo, matrAluno))
            {
                AvalAcadReposicao aval  = AvalAcadReposicao.ListarPorCodigoAvaliacao(codigo);
                Aluno             aluno = Aluno.ListarPorMatricula(matrAluno);
                int codPessoaFisica     = aluno.Usuario.PessoaFisica.CodPessoa;

                var retorno = from alunoResposta in aval.Avaliacao.PessoaResposta
                              orderby alunoResposta.CodQuestao
                              where alunoResposta.CodPessoaFisica == codPessoaFisica &&
                              alunoResposta.AvalTemaQuestao.QuestaoTema.Questao.CodTipoQuestao == TipoQuestao.DISCURSIVA
                              select new
                {
                    codQuestao           = alunoResposta.CodQuestao,
                    questaoEnunciado     = alunoResposta.AvalTemaQuestao.QuestaoTema.Questao.Enunciado,
                    questaoChaveResposta = alunoResposta.AvalTemaQuestao.QuestaoTema.Questao.ChaveDeResposta,
                    alunoResposta        = alunoResposta.RespDiscursiva,
                    notaObtida           = alunoResposta.RespNota.HasValue ? alunoResposta.RespNota.Value.ToValueHtml() : "",
                    correcaoComentario   = alunoResposta.ProfObservacao != null ? alunoResposta.ProfObservacao : "",
                    flagCorrigida        = alunoResposta.RespNota != null ? true : false
                };
                return(Json(retorno));
            }
            return(Json(null));
        }
Ejemplo n.º 19
0
        public async Task <object> PayAsync(OrderPayRequestDto input)
        {
            var order = await Repository.Include(x => x.OrderItems).FirstOrDefaultAsync(x => x.Id == input.OrderId);

            var appName = _httpContextAccessor?.HttpContext.Request.Headers["AppName"].FirstOrDefault();

            var app = await _appProvider.GetOrNullAsync(appName);

            var appid = app["appid"] ?? throw new AbpException($"App:{appName} appid未设置");

            var mchId = await _setting.GetOrNullAsync(MallManagementSetting.PayMchId);

            var mchKey = await _setting.GetOrNullAsync(MallManagementSetting.PayKey);

            var notifyUrl = await _setting.GetOrNullAsync(MallManagementSetting.PayNotify);

            var result = await _payApi.UnifiedOrderAsync(
                appid,
                mchId,
                mchKey,
                body : order.OrderItems.First().SpuName,
                outTradeNo : $"{mchId}{DateTime.Now:yyyyMMddHHmmss}{StringExt.BuildRandomStr(6)}",
                totalFee : Convert.ToInt32(order.PriceOriginal * 100),
                notifyUrl : notifyUrl,
                tradeType : Consts.TradeType.JsApi,
                openId : input.openid,
                billCreateIp : _httpContext.HttpContext.Connection.RemoteIpAddress.ToString()
                );

            return(result);
        }
Ejemplo n.º 20
0
        public void TranslateToStandardFormatString_HappyPath()
        {
            var actual = StringExt.TranslateToStandardFormatString("{Number} {Date:yyyyMM}-{Number:x}");

            actual.format.Should().Be("{0} {1:yyyyMM}-{0:x}");
            actual.itemNames.Should().BeEquivalentTo("Number", "Date");
        }
Ejemplo n.º 21
0
        public static string Truncate(this string text, int length = 140)
        {
            string output = text;

            if (!String.IsNullOrEmpty(text))
            {
                output = Regex.Replace(output, @"\t|\n|\r", " ");

                // strip tags
                output = Markdown.ToHtml(text);
                output = Regex.Replace(output, @"<[^>]+>|&nbsp;", "").Trim();
                output = Regex.Replace(output, @"{{[^>]+}}|&nbsp;", "").Trim();

                // strip extra whitespace
                output = Regex.Replace(output, @"\s{2,}", " ");

                if (text.Length > length)
                {
                    output = StringExt.Truncate(output, length);
                    output = output + " ...";
                }
            }

            return(output);
        }
        private string AddCustomConfigFile()
        {
            string gameConfigFilePath = string.Empty;

            //if the "do not use any config file at all" has not been checked
            if (this._game.NoConfig == false)
            {
                //use at first the game's custom config file
                if (StringExt.IsNullOrWhiteSpace(this._game.DBConfPath) == false)
                {
                    gameConfigFilePath = this._game.DBConfPath;
                }

                //if not, use the default dosbox.conf file
                else if (StringExt.IsNullOrWhiteSpace(_userData.DBDefaultConfFilePath) == false && _userData.DBDefaultConfFilePath != "No configuration file (*.conf) found in AmpShell's directory.")
                {
                    gameConfigFilePath = _userData.DBDefaultConfFilePath;
                }
            }
            string dosboxArgs = string.Empty;

            if (StringExt.IsNullOrWhiteSpace(gameConfigFilePath) == false)
            {
                dosboxArgs += $"-conf \"{gameConfigFilePath}\"";
            }

            return(dosboxArgs);
        }
Ejemplo n.º 23
0
        public async override Task <bool> InsertAsync(DB db)
        {
            if (!IsSet(nameof(id)))
            {
                id = await Users.GetUserNextUIDAsync(db);
            }

            if (!IsSet(nameof(login)))
            {
                login = await Users.FindAvailableLoginAsync(db, firstname, lastname);
            }

            if (!IsSet(nameof(password)))
            {
                password = "******" + StringExt.RandomSecureString(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789");
            }

            bool res = await base.InsertAsync(db);

            // if asked, create a default ENT email for the user
            if (res && create_ent_email)
            {
                await CreateDefaultEntEmailAsync(db);
            }

            return(res);
        }
        /// <summary> Starts DOSBox, and returns its <see cref="Process" />. </summary>
        /// <returns> The DOSBox <see cref="Process" />. </returns>
        private Process StartGame(string args)
        {
            if (this._game.IsDOSBoxUsed(_userData) == false)
            {
                var targetAndArguments = this._game.SplitTargetAndArguments();
                var nativeLaunchPsi    = new ProcessStartInfo(targetAndArguments[0], targetAndArguments[1])
                {
                    UseShellExecute  = true,
                    WorkingDirectory = Path.GetDirectoryName(this._game.DOSEXEPath)
                };
                return(StartProcess(nativeLaunchPsi));
            }
            var psi = new ProcessStartInfo(this._game.GetDOSBoxPath(_userData))
            {
                UseShellExecute = true
            };

            psi.WorkingDirectory = this._game.GetDOSBoxWorkingDirectory(psi.WorkingDirectory, _userData);

            if (StringExt.IsNullOrWhiteSpace(args) == false)
            {
                psi.Arguments = args;
            }
            return(StartProcess(psi));
        }
Ejemplo n.º 25
0
        private void Login()
        {
            var param = GetValidAccount();

            if (param == null)
            {
                return;
            }

            SaveAccount(param);
            param.PWD     = StringExt.MD5(param.PWD);
            param.Account = param.UserName;
            #region 登录验证
            ShowWaitProgress();
            Task.Factory
            .StartNew <ExeResult>(_ => CheckCompanyBegin((SYS_UserAccountParam)_), param)
            .Done(exeResult =>
            {
                if (CheckCompanyEnd(exeResult))
                {
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        var result = CheckLoginBegin((SYS_UserAccountParam)_);
                        BeginInvoke(new Action <ExeResult>(CheckLoginEnd), result);
                    }, param);
                }
            });
            #endregion
        }
Ejemplo n.º 26
0
        public ActionResult AtualizarSenha(string senhaAtual, string senhaNova, string senhaConfirmacao)
        {
            string mensagem = "Ocorreu um erro ao tentar alterar a senha.";

            if (!StringExt.IsNullOrWhiteSpace(senhaAtual, senhaNova, senhaConfirmacao))
            {
                Candidato c = Sessao.Candidato;
                if (Criptografia.ChecarSenha(senhaAtual, c.Senha))
                {
                    if (senhaNova == senhaConfirmacao)
                    {
                        c.Senha = Criptografia.RetornarHash(senhaNova);
                        Repositorio.Commit();
                        mensagem = "Senha alterada com sucesso.";
                    }
                    else
                    {
                        mensagem = "A confirmação da senha deve ser igual a senha nova.";
                    }
                }
                else
                {
                    mensagem = "A senha atual informada está incorreta.";
                }
            }
            else
            {
                mensagem = "Todos os campos são necessários para alterar a senha.";
            }
            TempData["Mensagem"] = mensagem;
            return(RedirectToAction("Perfil"));
        }
        public async Task <Option <RichFormatting> > Answer(Request request)
        {
            try
            {
                var rich       = new RichFormatting();
                var paragraphs = ReadParagraphs(path);
                if (paragraphs != null)
                {
                    await paragraphs.Where(paragraph => paragraph.Contains(request.QueryText)).ForEachAsync(paragraph =>
                    {
                        var text = new TextParagraph(
                            StringExt.HighlightWords(paragraph, request.QueryText)
                            .Select(p => new Text(p.text, emphasis: p.highlight)));
                        rich.Paragraphs.Add(text);
                    });

                    return(Option.Some(rich));
                }
            }
            catch (FileNotFoundException)
            {
                var text = "This data source looks for a custom_notes.txt file in the data directory. Currently no such file exists.";
                var rich = new RichFormatting(
                    EnumerableExt.OfSingle(
                        new TextParagraph(
                            EnumerableExt.OfSingle(
                                new Text(text)))));
                return(Option.Some(rich));
            }

            return(Option.None <RichFormatting>());
        }
Ejemplo n.º 28
0
        public ActionResult EsqueceuSenha(CandidatoEsqueceuSenhaViewModel model)
        {
            if (!StringExt.IsNullOrWhiteSpace(model.Cpf, model.Email) && Valida.CPF(model.Cpf) && Valida.Email(model.Email))
            {
                Candidato c = Candidato.ListarPorCPF(Formate.DeCPF(model.Cpf));

                if (c != null && c.Email.ToLower() == model.Email.ToLower())
                {
                    string token = Candidato.GerarTokenParaAlterarSenha(c);
                    string url   = Url.Action("AlterarSenha", "Candidato", new { codigo = token }, Request.Url.Scheme);
                    EnviarEmail.SolicitarSenha(c.Email, c.Nome, url);
                    TempData["EsqueceuSenhaMensagem"] = $"Um email com instruções foi enviado para {c.Email}.";
                    return(RedirectToAction("EsqueceuSenha"));
                }
                else
                {
                    model.Mensagem = "Não foi encontrado nenhum candidato para os dados informados.";
                }
            }
            else
            {
                model.Mensagem = "Todos os campos devem serem preenchidos com valores válidos.";
            }
            return(View(model));
        }
Ejemplo n.º 29
0
            public static void Load()
            {
                String configSource     = ConfigurationManager.AppSettings.Get("PatchableConfigSource") ?? String.Empty;
                String configSourcePath = StringExt.Resolve(configSource);

                Load(configSourcePath);
            }
Ejemplo n.º 30
0
 public void TestReverse()
 {
     Assert.AreEqual("hsilgnE", StringExt.Reverse("English"));
     Assert.AreEqual("文中hsilgnE", StringExt.Reverse("English中文"));
     Assert.AreEqual("\u0061\u0308文中hsilgnE", StringExt.Reverse("English中文\u0061\u0308"));
     Assert.AreEqual("\u0061\u0308文中hsilgnE\U0001D160", StringExt.Reverse("\U0001D160English中文\u0061\u0308"));
 }