/// <summary> /// Cria a estrutura do token. /// </summary> /// <param name="authResult"></param> /// <returns></returns> internal static SecurityTokenDescriptor CreateSecurityTokenDescriptor(AuthResult authResult) { if (_securityKey == null) { _securityKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ParameterCache.Get("TOKEN_SYMETRIC_KEY"))); } int maxRole = authResult.UserRoles.Max(r => (int)r); var claimList = new List <System.Security.Claims.Claim>() { new System.Security.Claims.Claim(ClaimTypes.Sid, authResult.UserId.ToString()), new System.Security.Claims.Claim(ClaimTypes.Role, maxRole.ToString()) }; string smymetricKey = ParameterCache.Get("TOKEN_SYMETRIC_KEY"); var now = DateTime.UtcNow; System.Security.Claims.Claim[] claims = claimList.ToArray(); return(new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), TokenIssuerName = TOKEN_ISSUER, AppliesToAddress = TOKEN_AUDIENCE, Lifetime = new Lifetime(now, now.AddHours(TOKEN_EXPIRATION_HOURS)), SigningCredentials = new SigningCredentials(_securityKey, "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"), }); }
/// <summary> /// Reseta a senha de um usuário /// </summary> /// <param name="ResetPwdRequest"></param> /// <returns>Token de autenticação em caso de sucesso.</returns> public static AuthResult ResetPassword(LoginRequest ResetPwdRequest) { AuthResult authResult = new AuthResult(); try { UserAccountEntity user = AccountRepository.Instance.FindByUserName(ResetPwdRequest.UserName != null ? ResetPwdRequest.UserName.ToLower() : null); if (user == null) { authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS; return(authResult); } UserProfileEntity profile = AccountRepository.Instance.GetProfileById(user.Id); if (profile == null) { authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS; return(authResult); } Random rnd = new Random(); string newPwd = rnd.Next().ToString(); //"PWD" + rnd.Next(); NewRequest request = new NewRequest(); request.Email = user.UserName; request.Username = user.UserName; request.Password = newPwd; UpdateUser(request); string EmailBody = "Olá! sua nova senha para acessar a plataforma do Gamific é: " + newPwd; string EmailTo = ParameterCache.Get("RESET_PASSWORD_EMAIL"); var result = EmailDispatcher.SendEmail(EmailTo, "Nova Senha Gamific", new List <string>() { user.UserName }, EmailBody); if (result) { authResult.AuthStatus = AuthStatus.OK; } else { authResult.AuthStatus = AuthStatus.ERROR; } } catch (Exception ex) { authResult.AuthStatus = AuthStatus.ERROR; } return(authResult); }
private void Send(EmailSupportDTO email, string emailTo, MemoryStream ms, string fileName) { string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); bool result = EmailDispatcher.SendEmail(emailFrom, email.Subject, new List <string>() { emailTo }, email.Msg, ms, fileName); }
public void Set_ValidatesParameters() { var cache = new ParameterCache(); Should.Throw <ArgumentNullException>(() => cache.Set(null, new ParameterInfo(new List <PropertyInfo>(), new List <PropertyInfo>()))); Should.Throw <ArgumentNullException>(() => cache.Set(typeof(ParameterCacheTests), null)); }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); ccSuplyAnalysis.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Column, SeriesChartType.Bar }; if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = true, AllowNegativeValuesOnYAxis = true, ShowGraphLinkingButton = true, ShowingSeriesInformation = false, ShowWeeklyMinimum = true, SeriesDrawingStyle = "Cylinder", LightXAxisLineColour = Color.LightGray, NegativeValuesColour = Color.Red, DataPointsYAxisTooltip = "#VALY{0,0}", DataPointsXAxisTooltip = "#VALX (day #INDEX)", XAxisDateFormat = "dd/MM (ddd)", YAxisNumberFormat = "#,##0", LabelFormat = "#,##0", ChartDescription = LocalizedReportPages.SupplyAnalysisDescription, ChartName = LocalizedReportPages.SupplyAnalysisReportName, GraphLinkingText = LocalizedReportPages.SupplyAnalysisToFutureTrendText, GraphLinkingPage = "~/App.Site/Sizing/FutureTrend/FutureTrend.aspx", ReportParameters = this.GetDefaultParameters() }; } GraphInformation.ShowLabelSeriesNames.Add("Weekly Minimum Supply"); GeneralParams.ReportTypeControl.ShowFleetPlanParameter = true; GeneralParams.ReportTypeControl.ShowTimeZoneParameter = true; GeneralParams.ReportTypeControl.ShowForecastTypeParameter = true; ccSuplyAnalysis.GraphInformation = GraphInformation; var dynamicParams = Session["FutureTrendSupplyAnalysisDynamicParams"] as List <ReportParameter>; if (dynamicParams != null) { GraphInformation.ReportParameters = dynamicParams; GraphInformation.RefreshData = true; Session["FutureTrendSupplyAnalysisDynamicParams"] = null; } GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GeneralParams.ExportType = 1; }
protected void PageLoadComplete(object sender, EventArgs e) { if (!string.IsNullOrEmpty(DynamicParameters.QuickSelectedValue)) { var branches = ParameterCache.GetAllBranches(); this.CheckQuickBranchSelected(branches, DynamicParameters.QuickSelectedValue , DynamicParameters.SelectedParameters, BufferInformation.ReportParameters, BufferInformation.CmsOpsLogic); } }
public void SetUp() { DatabaseProviderFactory factory = new DatabaseProviderFactory(new TestConfigurationContext()); this.db = factory.CreateDefaultDatabase(); storedProcedure = db.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI"); connection = db.GetConnection(); connection.Open(); storedProcedure.Command.Connection = connection; cache = new ParameterCache(); }
public void Get_GetsCachedEntry() { var type = typeof(ParameterCacheTests); var parameterInfo = new ParameterInfo(new List <PropertyInfo>(), new List <PropertyInfo>()); var cache = new ParameterCache(); cache.Set(type, parameterInfo); cache.Get(type).ShouldBeSameAs(parameterInfo); }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); Page.LoadComplete += PageLoadComplete; ccSiteComparison.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Column, SeriesChartType.Bar, SeriesChartType.Pie, SeriesChartType.Doughnut }; if (FleetComparisonGraphData == null) { CurrentKey = CountryKey; FleetComparisonGraphData = new Dictionary <string, List <GraphSeries> > { { CountryKey, null }, { CarSegmentKey, null }, { CarClassGroupKey, null }, { CarClassKey, null } }; } if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = false, AllowNegativeValuesOnYAxis = true, HideSeriesInfo = true, SeriesDrawingStyle = "Cylinder", DataPointsXAxisTooltip = "#VALX", DataPointsYAxisTooltip = "#VALY{0,0}", XAxisDateFormat = "dd/MM (ddd)", ChartDescription = LocalizedReportPages.FleetComparisonDescription, ChartName = LocalizedReportPages.FleetComparisonReportName, BranchForDrilldown = 2, ReportParameters = this.GetDefaultParameters() }; } GraphInformation.ReportParameters.First(p => p.Name == ParameterNames.CarClass).ParameterDropDownList.Enabled = false; ccSiteComparison.GraphInformation = GraphInformation; GeneralParams.ReportTypeControl.ShowFleetPlanParameter = true; GeneralParams.ReportTypeControl.ShowTopicParameter = true; GeneralParams.DynamicReportParametersControl.ShowQuickLocationGroupBox = true; GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GraphInformation.AllowDrillDown = true; GeneralParams.ExportType = 2; }
public void TestInitialize() { DatabaseProviderFactory factory = new DatabaseProviderFactory(TestConfigurationSource.CreateConfigurationSource()); db = factory.Create("OracleTest"); storedProcedure = db.GetStoredProcCommand("CustOrdersOrders"); connection = db.CreateConnection(); connection.Open(); storedProcedure.Connection = connection; cache = new ParameterCache(); baseFixture = new ParameterDiscoveryFixture(storedProcedure); }
public void SetUp() { DatabaseProviderFactory factory = new DatabaseProviderFactory(TestConfigurationSource.CreateConfigurationSource()); db = factory.CreateDefault(); storedProcedure = db.GetStoredProcCommand("CustOrdersOrders"); connection = db.CreateConnection(); connection.Open(); storedProcedure.Connection = connection; cache = new ParameterCache(); baseFixture = new ParameterDiscoveryFixture(storedProcedure); }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); ccFutureTrend.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Line, SeriesChartType.StepLine, SeriesChartType.Spline, }; if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = true, ShowGraphLinkingButton = true, XAxisDateFormat = "dd/MM (ddd)", YAxisNumberFormat = "#,##0", LabelFormat = "#,##0", DataPointsXAxisTooltip = "#VALX (day #INDEX)", DataPointsYAxisTooltip = "#VALY{0,0}", GraphLinkingPage = "~/App.Site/Sizing/SupplyAnalysis/SupplyAnalysis.aspx", YAxisZoom = "75", ChartDescription = LocalizedReportPages.FutureTrendDescription, GraphLinkingText = LocalizedReportPages.FutureTrendToSupplyAnalysisText, ChartName = LocalizedReportPages.FutureTrendReportName, ReportParameters = this.GetDefaultParameters() }; } GeneralParams.ReportTypeControl.ShowFleetPlanParameter = true; GeneralParams.ReportTypeControl.ShowTimeZoneParameter = true; GeneralParams.ReportTypeControl.ShowForecastTypeParameter = true; var dynamicParams = Session["FutureTrendSupplyAnalysisDynamicParams"] as List <ReportParameter>; if (dynamicParams != null) { GraphInformation.ReportParameters = dynamicParams; GraphInformation.RefreshData = true; Session["FutureTrendSupplyAnalysisDynamicParams"] = null; } GeneralParams.DynamicReportParametersControl.ShowQuickLocationGroupBox = true; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; ccFutureTrend.GraphInformation = GraphInformation; GeneralParams.ExportType = 1; }
public void TestInitialize() { EnvironmentHelper.AssertOracleClientIsInstalled(); DatabaseProviderFactory factory = new DatabaseProviderFactory(OracleTestConfigurationSource.CreateConfigurationSource()); db = factory.Create("OracleTest"); storedProcedure = db.GetStoredProcCommand("NWND_CustOrdersOrders"); connection = db.CreateConnection(); connection.Open(); storedProcedure.Connection = connection; cache = new ParameterCache(); baseFixture = new ParameterDiscoveryFixture(storedProcedure); }
public static void Send(EmailSupportDTO email, string emailTo, string gameId = "", string episodeId = "", string playerId = "") { string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); bool result = EmailDispatcher.SendEmail(emailFrom, email.Subject, new List <string>() { emailTo }, email.Msg); EmailLogRepository.Instance.Create(new EmailLogEntity { Description = email.Subject, GameId = gameId, EpisodeId = episodeId, PlayerId = playerId, To = emailTo, Message = email.Msg, }); }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); ccForecast.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Line, SeriesChartType.StepLine, SeriesChartType.Spline, }; if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = true, XAxisDateFormat = "dd/MM (ddd)", YAxisNumberFormat = "#,##0", DataPointsXAxisTooltip = "#VALX (day #INDEX)", DataPointsYAxisTooltip = "#VALY{0,0}", LabelFormat = "#,##0", ChartDescription = LocalizedReportPages.ForecastDescription, ChartName = LocalizedReportPages.ForecastReportName, YAxisZoom = "0", ChartLineWidth = 2, ReportParameters = this.GetDefaultParameters() }; GraphInformation.HiddenSeriesNames.Add("Top Down"); GraphInformation.HiddenSeriesNames.Add("On Rent LY"); GraphInformation.HiddenSeriesNames.Add("Bottom Up 1"); GraphInformation.HiddenSeriesNames.Add("Bottom Up 2"); GraphInformation.HiddenSeriesNames.Add("Reconciliation"); } GeneralParams.ReportTypeControl.ShowTimeZoneParameter = true; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; GeneralParams.DynamicReportParametersControl.DateRangePickerControl.DefaultDateRangeValueSelected = "90"; ccForecast.GraphInformation = GraphInformation; GeneralParams.ExportType = 1; }
private void SaveParameter() { ParameterInfo parameter; ParameterInfo[] parameterInfos = this.methodInfo.GetParameters(); ParameterWrapContext parameterWrap; for (int i = 0; i < parameterInfos.Length; i++) { parameter = parameterInfos[i]; parameterWrap = ParameterWrapContext.GetContext(this, parameter); ParameterCache.Add(parameterWrap); } ParameterCache.ForEach(x => { x.CreateBind(); }); }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); ccKPI.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Line, SeriesChartType.StepLine, SeriesChartType.Spline, SeriesChartType.Column, SeriesChartType.Point }; if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = true, XAxisDateFormat = "dd/MM (ddd)", AllowNegativeValuesOnYAxis = true, LabelFormat = "0%", YAxisNumberFormat = "0%", ChartDescription = LocalizedReportPages.KpiDescription, DataPointsXAxisTooltip = "#VALX", DataPointsYAxisTooltip = "#VALY{0%}", ChartName = LocalizedReportPages.KpiReportName, YAxisZoom = "75", ReportParameters = this.GetDefaultParameters() }; GraphInformation.ShowLabelSeriesNames.Add(KpiDataAccess.KpiSeriesName); GeneralParams.ReportTypeControl.SelectedTimeZone.SelectedIndex = 1; //Default to Frozen Zone } GeneralParams.ReportTypeControl.ShowKpiParameter = true; GeneralParams.ReportTypeControl.ShowTimeZoneParameter = true; GeneralParams.DynamicReportParametersControl.ShowQuickLocationGroupBox = true; ccKPI.GraphInformation = GraphInformation; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; }
protected void Page_Init(object sender, EventArgs e) { _locationGroupData = ParameterCache.GetAllLocationGroups(); ccBenchmark.GraphTypesAllowed = new List <SeriesChartType> { SeriesChartType.Line, SeriesChartType.StepLine, SeriesChartType.Spline, }; if (GraphInformation == null) { GraphInformation = new GraphData { IsXValueDate = true, XAxisDateFormat = "dd/MM (ddd)", YAxisNumberFormat = "#,##0", DataPointsXAxisTooltip = "#VALX (day #INDEX)", DataPointsYAxisTooltip = "#VALY{0,0}", LabelFormat = "#,##0", ChartDescription = LocalizedReportPages.BenchmarkReportDescription, ChartName = LocalizedReportPages.BenchmarkReportName, YAxisZoom = "75", ChartLineWidth = 1, ShowGraphLinkingButton = true, GraphLinkingText = LocalizedReportPages.BenchmarkShowUnconstrained, GraphLinkingPage = "", ReportParameters = this.GetDefaultParameters() }; } GeneralParams.ReportTypeControl.ShowForecastTypeParameter = true; GeneralParams.ParamsHolder = GraphInformation.ReportParameters; GeneralParams.SelectedParameters = GraphInformation.SelectedParameters; GeneralParams.ReportTypeControl.HideAlreadyBooked = true; ccBenchmark.GraphInformation = GraphInformation; GeneralParams.ExportType = 1; }
/// <summary> /// Create or retrieves from cache a parameter using the classes supplied parameter prefix. /// The name is autogenerated. Use the ParameterName property of the returned param in your queries. /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual IDataParameter CreateParameter <TValue>(TValue value) { ///if TValue is System.Object we need to expand it to generate the correct parameter type if (typeof(TValue) == typeof(object) && value.GetType() != typeof(object)) { return(CreateParameterFromObject(value)); } object key = value; if (Equals(null, value)) { key = new NullValue <TValue>(); } if (ParameterCache.ContainsKey(key)) { return(ParameterCache[key]); } IDataParameter p; if (value is IGeometry) { p = Provider.DbUtility.CreateParameter(string.Format("iparam{0}", ParameterCache.Count), ((IGeometry)value).AsBinary(), ParameterDirection.Input); } else { p = Provider.DbUtility.CreateParameter(string.Format("iparam{0}", ParameterCache.Count), value, ParameterDirection.Input); } ParameterCache.Add(key, p); return(p); }
public ActionResult Send(EmailSupportDTO email) { string emailTo = ParameterCache.Get("SUPPORT_EMAIL"); bool result = EmailDispatcher.SendEmail(emailTo, email.Subject, new List <string>() { emailTo }, email.Category + " - " + email.Msg); if (result) { Success("Email enviado com sucesso."); } else { Error("Ocorreu um erro ao enviar sua mensagem."); } ViewBag.Categories = GetCategories(); return(View("Index")); }
/// <summary> /// Salva as informações do resultado via arquivo /// </summary> /// <param name="goalArchive"></param> /// <param name="episodeId"></param> /// <returns></returns> private ActionResult SaveGoalArchiveDefault(HttpPostedFileBase goalArchive, string episodeId) { string errors = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>"; int line = 1; int countErrors = 0; int countEmptyLines = 0; try { goalArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), goalArchive.FileName)); string path = Path.Combine(Server.MapPath("~/App_Data"), goalArchive.FileName); var archive = new ExcelQueryFactory(path); var rows = from x in archive.WorksheetRange("A1", "D" + rowsCount, "Goals") select x; foreach (var row in rows) { line++; if (countEmptyLines >= 3) { break; } if (row[0] == null || row[0].ToString().Equals("") || row[1] == null || row[1].ToString().Equals("")) { countEmptyLines++; continue; } countEmptyLines = 0; if (row[3].ToString().Equals("0")) { continue; } MetricEngineDTO metric = new MetricEngineDTO(); TeamEngineDTO team = new TeamEngineDTO(); RunEngineDTO run = new RunEngineDTO(); try { metric = MetricEngineService.Instance.GetDTOByGameAndName(CurrentFirm.ExternalId, row[1].ToString()); } catch (Exception e) { errors += "Erro na coluna 2 da linha " + line + "<br/>"; countErrors++; continue; } UserProfileEntity user = UserProfileRepository.Instance.GetByEmail(row[0].Value.ToString()); if (user == null) { errors += "Erro na coluna 1 da linha " + line + "<br/>"; countErrors++; continue; } WorkerEntity worker = WorkerRepository.Instance.GetByUserId(int.Parse(user.Id.ToString())); if (worker == null) { errors += "Erro na coluna 1 da linha " + line + "<br/>"; countErrors++; continue; } try { team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episodeId, row[2].Value.ToString()); } catch (Exception e) { errors += "Erro na coluna 3 da linha " + line + "<br/>"; countErrors++; continue; } try { run = RunEngineService.Instance.GetRunByPlayerAndTeamId(worker.ExternalId, team.Id); } catch (Exception e) { errors += "Jogador " + user.Name + " não está cadastrado no time " + team.Nick + ". Linha: " + line + "<br/>"; countErrors++; continue; } if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString())) { GoalEngineDTO goalEngineDTO; try { goalEngineDTO = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metric.Id); goalEngineDTO.Goal = float.Parse(row[3].Value.ToString()); } catch (Exception e) { goalEngineDTO = new GoalEngineDTO { RunId = run.Id, MetricId = metric.Id, MetricIcon = metric.Icon, MetricName = metric.Name, Goal = float.Parse(row[3].Value.ToString()), ItemId = "", Percentage = 0 }; } goalEngineDTO.Goal = float.Parse(row[3].Value.ToString()); goalEngineDTO = GoalEngineService.Instance.CreateOrUpdate(goalEngineDTO); } } errors = string.Format(errors, countErrors, line); string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); string subject = countErrors >= 1 ? "Erros ao subir planilha de metas" : "O lançamento de metas foi um sucesso."; subject = CurrentFirm.FirmName + ": " + subject; bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>() { emailFrom, CurrentUserProfile.Email }, errors); return(Json(new { Success = true }, JsonRequestBehavior.DenyGet)); } catch (Exception ex) { Logger.LogException(ex); return(Json(new { Success = false }, JsonRequestBehavior.DenyGet)); } }
/// <summary> /// Salva as informações do resultado via arquivo /// </summary> /// <param name="resultsArchive"></param> /// <returns></returns> //[Route("salvarResultadoArquivo")] //[HttpPost] //[CustomAuthorize(Roles = "WORKER,ADMINISTRADOR,SUPERVISOR DE CAMPANHA,SUPERVISOR DE EQUIPE")] private ActionResult SaveResultArchiveSyngenta(HttpPostedFileBase resultsArchive) { string errors = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>"; int line = 1; int countErrors = 0; int countEmptyLines = 0; string gameId = CurrentFirm.ExternalId; int CODIGO_TERRITORIO = 0; int RESPONSAVEL = 1; int EMAIL = 2; int REG = 3; int PROMOxISNT = 4; int DIA = 5; int CULTURA = 6; int NOME_PADRAO = 7; int TOTAL = 8; try { resultsArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), resultsArchive.FileName)); string path = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(resultsArchive.FileName)); var archive = new ExcelQueryFactory(path); var rows = from x in archive.WorksheetRange("A1", "I" + rowsCount, "REALIZADO") select x; foreach (var row in rows) { line++; if (countEmptyLines >= 3) { break; } if (row[0] == null || row[0].ToString().Equals("") || row[1] == null || row[1].ToString().Equals("")) { countEmptyLines++; continue; } countEmptyLines = 0; if (row[TOTAL].ToString().Equals("0")) { continue; } RunMetricEngineDTO result = new RunMetricEngineDTO(); MetricEngineDTO metric = new MetricEngineDTO(); TeamEngineDTO team = new TeamEngineDTO(); RunEngineDTO run = new RunEngineDTO(); try { metric = MetricEngineService.Instance.GetDTOByGameAndName(gameId, row[NOME_PADRAO].ToString()); } catch (Exception e) { errors += "Erro na coluna " + (NOME_PADRAO + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } UserProfileEntity user = UserProfileRepository.Instance.GetByEmail(row[EMAIL].ToString()); if (user == null) { errors += "Erro na coluna " + (EMAIL + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } WorkerEntity worker = WorkerRepository.Instance.GetByUserId((int)user.Id); if (worker == null) { errors += "Erro na coluna " + (EMAIL + 1) + " 1 da linha " + line + "<br/>"; countErrors++; continue; } EpisodeEngineDTO episode; try { episode = EpisodeEngineService.Instance.FindByGameIdAndName(gameId, row[CULTURA]); } catch (Exception e) { errors += "Erro na coluna " + (CULTURA + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } try { team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episode.Id, row[REG]); } catch (Exception e) { errors += "Erro na coluna " + (REG + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } try { run = RunEngineService.Instance.GetRunByPlayerAndTeamId(worker.ExternalId, team.Id); } catch (Exception e) { errors += "Jogador " + user.Name + " não está cadastrado no time " + team.Nick + ". Linha: " + line + "<br/>"; countErrors++; continue; } float oldResult; try { oldResult = RunMetricEngineService.Instance.findByRunIdAndMetricId(run.Id, metric.Id, 0, 100000).List.runMetric.Sum(x => x.Points); } catch (Exception e) { oldResult = 0; } if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString())) { try { result.Ceiling = metric.Ceiling; result.Date = Convert.ToDateTime(row[DIA].ToString()).Ticks; result.Description = metric.Description; result.Floor = metric.Floor; result.MetricId = metric.Id; result.Multiplier = metric.Multiplier; result.Name = metric.Name; result.Points = float.Parse(row[TOTAL].ToString()) - oldResult; result.Score = 0; result.Xp = metric.Xp; result.RunId = run.Id; result.PlayerId = worker.ExternalId; if (result.Points > 0) { RunMetricEngineService.Instance.CreateOrUpdate(result); } } catch (Exception e) { errors += "O formato das colunas 'Periodo' ou 'Resultado' estão errados. Linha: " + line + "<br/>"; countErrors++; continue; } } } errors = string.Format(errors, countErrors, line); string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); string subject = countErrors >= 1 ? "Erros ao subir planilha de resultados" : "O lançamento de resultados foi um sucesso."; subject = CurrentFirm.FirmName + ": " + subject; bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>() { emailFrom, CurrentUserProfile.Email }, errors); return(Json(new { Success = true }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Logger.LogException(ex); //ModelState.AddModelError("", "Ocorreu um erro ao tentar salvar os resultados."); return(Json(new { Success = false, Exception = ex.Message }, JsonRequestBehavior.DenyGet)); } }
public override UnrealParameterInfo Create(IMemberInfo declaringMember, UnrealTypeInfo declaringType, ParameterInfo parameterInfo) { return(ParameterCache.GetOrAdd(parameterInfo, p => new UnrealParameterInfo(this, declaringMember, declaringType, p))); }
public void Get_ValidatesParameters() { var cache = new ParameterCache(); Should.Throw <ArgumentNullException>(() => cache.Get(null)); }
//Sol bebidas /// <summary> /// Salva as informações do resultado via arquivo /// </summary> /// <param name="resultsArchive"></param> /// <param name="episodeId"></param> /// <returns></returns> //[Route("salvarResultadoArquivo")] //[HttpPost] //[CustomAuthorize(Roles = "WORKER,ADMINISTRADOR,SUPERVISOR DE CAMPANHA,SUPERVISOR DE EQUIPE")] public ActionResult SaveResultArchiveSolBebidas(HttpPostedFileBase resultsArchive, string episodeId) { int ANO = 0; int MES = 1; int REPRESENTANTE = 2; int EMAIL = 3; int CLIENTE = 4; int COD_PRODUTO = 5; int PRODUTO = 6; int QTDE_OBJ = 7; int QTDE_REAL = 8; int PERCENT_QTDE = 9; int VLR_OBJ = 10; int VLR_BRUTO_REAL = 11; int PERCENT_VALOR = 12; int VLR_MEDIO_OBJETIVO = 13; int VLR_MEDIO_REAL = 14; int TIPO_PRODUTO = 15; EpisodeEngineDTO episode = EpisodeEngineService.Instance.GetById(episodeId); string gameId = CurrentFirm.ExternalId; string errors = "Erros: {0}<br/>"; List <GoalEngineDTO> goalsTotalFat = new List <GoalEngineDTO>(); List <GoalEngineDTO> goalsTotalVol = new List <GoalEngineDTO>(); MetricEngineDTO metricFat; MetricEngineDTO metricVol; int line = 1; int errorsCount = 0; string productType = resultsArchive.FileName.Split(' ')[0]; try { metricFat = MetricEngineService.Instance.GetDTOByGameAndName(gameId, productType + " FATURAMENTO"); } catch (Exception e) { errors += "Metrica (Faturamento) não encontrado.<br/>"; errorsCount++; metricFat = new MetricEngineDTO(); Debug.Print("Error metric: " + e.Message); } try { metricVol = MetricEngineService.Instance.GetDTOByGameAndName(gameId, productType + " VOLUME"); } catch (Exception e) { errors += "Metrica (Volume) não encontrado.<br/>"; errorsCount++; metricVol = new MetricEngineDTO(); Debug.Print("Error metric: " + e.Message); } try { //EpisodeEngineService.Instance.DeleteAllScoreByEpisodeId(episodeId); resultsArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), resultsArchive.FileName)); var archive = new ExcelQueryFactory(Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(resultsArchive.FileName))); var rows = from x in archive.WorksheetRange("A1", "O" + rowsCount, "Plan1") select x; float points; foreach (var row in rows) { line++; PlayerEngineDTO player; RunEngineDTO run; if (row[PRODUTO].ToString().ToLower().Contains("uvinha")) { continue; } try { player = PlayerEngineService.Instance.GetByEmail(row[EMAIL].ToString().Trim().ToLower()); } catch (Exception e) { Debug.Print("Error player: " + e.Message); errors += "(Linha -> " + line + "°, Coluna -> 'Representante') " + "Jogador: " + row[EMAIL].ToString().Trim() + " não encontrado.<br/>"; errorsCount++; continue; } try { run = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(episodeId, player.Id); } catch (Exception e) { Debug.Print("Error run: " + e.Message); errors += "(Linha -> " + line + "°, Coluna -> 'Email') " + "Jogador: " + row[EMAIL].ToString().Trim() + " não participa desta campanha.<br/>"; errorsCount++; continue; } float.TryParse(row[VLR_OBJ].ToString(), out points); if (goalsTotalFat.Find(x => x.RunId == run.Id) != null) { goalsTotalFat.Find(x => x.RunId == run.Id).Goal += points; } else { GoalEngineDTO goalFat; try { goalFat = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metricFat.Id); goalFat.Goal = points; } catch (Exception e) { goalFat = new GoalEngineDTO { Goal = points, MetricIcon = metricFat.Icon, MetricId = metricFat.Id, MetricName = metricFat.Name, Percentage = 0, RunId = run.Id }; Debug.Print("Goal faturamento: " + e.Message); } goalsTotalFat.Add(goalFat); } float.TryParse(row[QTDE_OBJ].ToString(), out points); if (goalsTotalVol.Find(x => x.RunId == run.Id) != null) { goalsTotalVol.Find(x => x.RunId == run.Id).Goal += points; } else { GoalEngineDTO goalVol; try { goalVol = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metricVol.Id); goalVol.Goal = points; } catch (Exception e) { goalVol = new GoalEngineDTO { Goal = points, MetricIcon = metricVol.Icon, MetricId = metricVol.Id, MetricName = metricVol.Name, Percentage = 0, RunId = run.Id }; Debug.Print("Goal volume: " + e.Message); } goalsTotalVol.Add(goalVol); } ItemEngineDTO item = new ItemEngineDTO { GameId = gameId, Name = row[PRODUTO].ToString().Trim() }; try { item = ItemEngineService.Instance.FindByNameAndGameId(item.Name, item.GameId); } catch (Exception e) { item = ItemEngineService.Instance.CreateOrUpdate(item); Debug.Print("Error metric: " + e.Message); } float.TryParse(row[VLR_BRUTO_REAL].ToString(), out points); RunMetricEngineDTO resultFaturamento = new RunMetricEngineDTO { Ceiling = metricFat.Ceiling, Description = metricFat.Description, Floor = metricFat.Floor, MetricId = metricFat.Id, Multiplier = metricFat.Multiplier, Name = metricFat.Name, Xp = 0, Score = 0, Points = (int)points, Date = DateTime.Now.Ticks, PlayerId = player.Id, ItemId = item.Id, ItemName = item.Name, RunId = run.Id }; float.TryParse(row[QTDE_REAL].ToString(), out points); RunMetricEngineDTO resultVolume = new RunMetricEngineDTO { Ceiling = metricVol.Ceiling, Description = metricVol.Description, Floor = metricVol.Floor, MetricId = metricVol.Id, Multiplier = metricVol.Multiplier, Name = metricVol.Name, Xp = 0, Score = 0, Points = (int)points, Date = DateTime.Now.Ticks, PlayerId = player.Id, ItemId = item.Id, ItemName = item.Name, RunId = run.Id }; RunMetricEngineService.Instance.CreateOrUpdate(resultFaturamento); RunMetricEngineService.Instance.CreateOrUpdate(resultVolume); } foreach (GoalEngineDTO goal in goalsTotalVol) { GoalEngineService.Instance.CreateOrUpdate(goal); } foreach (GoalEngineDTO goal in goalsTotalFat) { GoalEngineService.Instance.CreateOrUpdate(goal); } errors = string.Format(errors, errorsCount); string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); string subject = errorsCount >= 1 ? "Erros ao subir planilha de resultados" : "O lançamento de resultados foi um sucesso."; subject = CurrentFirm.FirmName + ": " + subject; bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>() { emailFrom, CurrentUserProfile.Email }, errors); return(Json(new { Success = true }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Debug.Print("Geral Error: " + e.Message); return(Json(new { Success = false, Exception = e.Message }, JsonRequestBehavior.DenyGet)); } }
public override CXXParameterInfo Create(IMemberInfo declaringMember, CXXTypeInfo declaringType, System.Reflection.ParameterInfo parameterInfo) { return(ParameterCache.GetOrAdd(parameterInfo, p => new CXXParameterInfo(this, declaringMember, declaringType, p))); }
/// <summary> /// Salva as informações do resultado via arquivo /// </summary> /// <param name="resultsArchive"></param> /// <returns></returns> //[Route("salvarResultadoArquivo")] //[HttpPost] //[CustomAuthorize(Roles = "WORKER,ADMINISTRADOR,SUPERVISOR DE CAMPANHA,SUPERVISOR DE EQUIPE")] private ActionResult SaveResultArchiveStandard(HttpPostedFileBase resultsArchive, string episodeId) { string errors = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>"; int line = 1; int countErrors = 0; int countEmptyLines = 0; string gameId = CurrentFirm.ExternalId; try { resultsArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), resultsArchive.FileName)); string path = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(resultsArchive.FileName)); var archive = new ExcelQueryFactory(path); var rows = from x in archive.WorksheetRange("A1", "F" + rowsCount, "Results") select x; foreach (var row in rows) { line++; if (countEmptyLines >= 3) { break; } if (row[0] == null || row[0].ToString().Equals("") || row[1] == null || row[1].ToString().Equals("")) { countEmptyLines++; continue; } countEmptyLines = 0; if (row[3].ToString().Equals("0")) { continue; } RunMetricEngineDTO result = new RunMetricEngineDTO(); MetricEngineDTO metric = new MetricEngineDTO(); TeamEngineDTO team = new TeamEngineDTO(); RunEngineDTO run = new RunEngineDTO(); try { metric = MetricEngineService.Instance.GetDTOByGameAndName(CurrentFirm.ExternalId, row[1].ToString()); } catch (Exception e) { errors += "Erro na coluna 2 da linha " + line + "<br/>"; countErrors++; continue; } UserProfileEntity user = UserProfileRepository.Instance.GetByEmail(row[0].ToString()); if (user == null) { errors += "Erro na coluna 1 da linha " + line + "<br/>"; countErrors++; continue; } WorkerEntity worker = WorkerRepository.Instance.GetByUserId((int)user.Id); if (worker == null) { errors += "Erro na coluna 1 da linha " + line + "<br/>"; countErrors++; continue; } try { team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episodeId, row[4]); } catch (Exception e) { errors += "Erro na coluna 5 da linha " + line + "<br/>"; countErrors++; continue; } try { run = RunEngineService.Instance.GetRunByPlayerAndTeamId(worker.ExternalId, team.Id); } catch (Exception e) { errors += "Jogador " + user.Name + " não está cadastrado no time " + team.Nick + ". Linha: " + line + "<br/>"; countErrors++; continue; } ItemEngineDTO item = new ItemEngineDTO { GameId = gameId, Name = Regex.Replace(row[5].ToString().Trim(), "[^0-9a-zA-Z]+", " ") }; try { item = ItemEngineService.Instance.FindByNameAndGameId(item.Name, item.GameId); } catch (Exception e) { if (item.Name != "") { item = ItemEngineService.Instance.CreateOrUpdate(item); } } if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString())) { try { result.Ceiling = metric.Ceiling; result.Date = Convert.ToDateTime(row[2].ToString()).Ticks; result.Description = metric.Description; result.Floor = metric.Floor; result.MetricId = metric.Id; result.Multiplier = metric.Multiplier; result.Name = metric.Name; result.Points = float.Parse(row[3].ToString()); result.Score = 0; result.Xp = metric.Xp; result.RunId = run.Id; result.PlayerId = worker.ExternalId; result.ItemId = item.Id; result.ItemName = item.Name; RunMetricEngineService.Instance.CreateOrUpdate(result); } catch (Exception e) { errors += "O formato das colunas 'Periodo' ou 'Resultado' estão errados. Linha: " + line + "<br/>"; countErrors++; continue; } } } errors = string.Format(errors, countErrors, line); string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); string subject = countErrors >= 1 ? "Erros ao subir planilha de resultados" : "O lançamento de resultados foi um sucesso."; subject = CurrentFirm.FirmName + ": " + subject; bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>() { emailFrom, CurrentUserProfile.Email }, errors); return(Json(new { Success = true }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Logger.LogException(ex); //ModelState.AddModelError("", "Ocorreu um erro ao tentar salvar os resultados."); return(Json(new { Success = false, Exception = ex.Message }, JsonRequestBehavior.DenyGet)); } }
/// <summary> /// Salva as informações do resultado via arquivo /// </summary> /// <param name="goalArchive"></param> /// <param name="episodeId"></param> /// <returns></returns> private ActionResult SaveGoalArchiveSyngenta(HttpPostedFileBase goalArchive) { string errors = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>"; int line = 1; int countErrors = 0; int countEmptyLines = 0; string gameId = CurrentFirm.ExternalId; int CODIGO_TERRITORIO = 0; int RESPONSAVEL = 1; int EMAIL = 2; int REG = 3; int PROMOxISNT = 4; int DIA = 5; int CULTURA = 6; int NOME_PADRAO = 7; int TOTAL = 8; try { goalArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), goalArchive.FileName)); string path = Path.Combine(Server.MapPath("~/App_Data"), goalArchive.FileName); var archive = new ExcelQueryFactory(path); var rows = from x in archive.WorksheetRange("A1", "I" + rowsCount, "META") select x; foreach (var row in rows) { line++; if (countEmptyLines >= 3) { break; } if (row[0] == null || row[0].ToString().Equals("") || row[1] == null || row[1].ToString().Equals("")) { countEmptyLines++; continue; } countEmptyLines = 0; if (row[TOTAL].ToString().Equals("0")) { continue; } MetricEngineDTO metric = new MetricEngineDTO(); TeamEngineDTO team = new TeamEngineDTO(); RunEngineDTO run = new RunEngineDTO(); try { metric = MetricEngineService.Instance.GetDTOByGameAndName(gameId, row[NOME_PADRAO].ToString()); } catch (Exception e) { errors += "Erro na coluna " + (NOME_PADRAO + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } PlayerEngineDTO player; try { player = PlayerEngineService.Instance.GetByEmail(row[EMAIL].Value.ToString()); } catch (Exception e) { errors += "Erro na coluna " + (EMAIL + 1) + " da linha " + line + "<br/>"; countErrors++; continue; } EpisodeEngineDTO episode; try { episode = EpisodeEngineService.Instance.FindByGameIdAndName(gameId, row[CULTURA]); } catch (Exception e) { errors += "Erro na coluna 5 da linha " + line + "<br/>"; countErrors++; continue; } try { team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episode.Id, row[REG].Value.ToString()); } catch (Exception e) { errors += "Erro na coluna 3 da linha " + line + "<br/>"; countErrors++; continue; } try { run = RunEngineService.Instance.GetRunByPlayerAndTeamId(player.Id, team.Id); } catch (Exception e) { errors += "Jogador " + player.Nick + " não está cadastrado no time " + team.Nick + ". Linha: " + line + "<br/>"; countErrors++; continue; } if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString())) { GoalEngineDTO goalEngineDTO; try { goalEngineDTO = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metric.Id); goalEngineDTO.Goal = Int32.Parse(row[TOTAL].Value.ToString()); } catch (Exception e) { goalEngineDTO = new GoalEngineDTO { RunId = run.Id, MetricId = metric.Id, MetricIcon = metric.Icon, MetricName = metric.Name, Goal = Int32.Parse(row[TOTAL].Value.ToString()), ItemId = "", Percentage = 0 }; } goalEngineDTO = GoalEngineService.Instance.CreateOrUpdate(goalEngineDTO); } } errors = string.Format(errors, countErrors, line); string emailFrom = ParameterCache.Get("SUPPORT_EMAIL"); string subject = countErrors >= 1 ? "Erros ao subir planilha de metas" : "O lançamento de metas foi um sucesso."; subject = CurrentFirm.FirmName + ": " + subject; bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>() { emailFrom, CurrentUserProfile.Email }, errors); return(Json(new { Success = true }, JsonRequestBehavior.DenyGet)); } catch (Exception ex) { Logger.LogException(ex); return(Json(new { Success = false }, JsonRequestBehavior.DenyGet)); } }
/// <summary> /// Valida um token. /// </summary> /// <returns></returns> internal static AuthResult ValidateToken() { if (_securityKey == null) { _securityKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(ParameterCache.Get("TOKEN_SYMETRIC_KEY"))); } AuthResult result = new AuthResult(); string accessToken = ReadTokenFromRequest(); if (!string.IsNullOrWhiteSpace(accessToken)) { TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = TOKEN_AUDIENCE, ValidIssuer = TOKEN_ISSUER, IssuerSigningKey = _securityKey }; SecurityToken jwtToken = null; try { result.TokenClaims = _tokenHandler.ValidateToken(accessToken, validationParameters, out jwtToken); } catch (SecurityTokenExpiredException) { result.AuthStatus = AuthStatus.TOKEN_EXPIRED; } catch { result.AuthStatus = AuthStatus.UNAUTHORIZED; } } else { result.AuthStatus = AuthStatus.ANONYMOUS; } return(result); }