I'm trying to create a reset password for users in symfony 4, I have this error
No route found for "GET /change-password": Method Not Allowed (Allow:
POST)
I'm looking for help please
my Controller:
class ChangepasswordController extends Controller
{
private $oldpassword;
private $newpassword;
/**
* #Route("/change-password", name="change_password", defaults={"email=null"})
* #Method("POST")
* #param Request $request
* #param AuthenticationUtils $authenticationUtils
* #param UserPasswordEncoderInterface $passwordEncoder
* #param $email
* #return Response
*/
public function ChangepasswordAction(Request $request, UserPasswordEncoderInterface $passwordEncoder, $email)
{
$user = new User();
$form = $this->createForm(ChangepasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$user = $this->getDoctrine()->getRepository(User::class)->find($email);
} catch (ExceptionInterface $e) {
$this->addFlash('danger', "Cet email n'existe pas.");
}
//Recuperer le nouveau mot de passe tapé par l'utilisateur
$newpassword = $passwordEncoder->encodePassword($user, $user->getPassword());
//recuperer l'ancien mot de passe dans la base de donnéees
$oldpassword = $user->getPassword();
if ($newpassword = $oldpassword) {
$this->addFlash('danger', "Ce mot de passe est dejà utilisé.");
} else {
$user->setPassword($newpassword);
}
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'votre mot de passe est bien réinitialisé');
# Redirection sur la page de connexion
return $this->redirectToRoute('connexion');
}
return $this->render(
'security/changemotdepasse.html.twig',
array('form' => $form->createView())
);
}
}
You have to change #Method("POST") to #Method({"GET","POST"}), because your Action is for displaying and processing the form.
I think GET method is not good way to reset password, you can add GET in Methode annotation to fix it but it’s bad way .
The good way is just send data by POST Method and handle it in $request
#Route("/change-password", name="change_password"
Take care of your definition ... - !== _
Using Zend Framework 2 is possible to get a sql string from a tablegateway object, like this:
public function test(){
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$select->where(array('title' => 'abracadabra'));
$select->where
->NEST->
equalTo('id', 1)
->OR->
equalTo('artist', 'Tony')
->UNNEST;
$select->limit(1);
return $this->tableGateway->selectWith($select);
}
//code ignored here//
echo $sql->getSqlstringForSqlObject($select);
I was wondering if it could be possible to do the opposite, and basically set a query string and then get back a tableGateway object, the reason for this is that sometimes is needed to set a where clause dynamically, without having to know where to place/append it, example:
On a single query:
$sql = "select * from tbl_test";
if($isDynamic)
$sql .= ' where test_id=1';
But on more complex query:
$sql = "select * from tbl_test inner join (select * from tbl_test 1) x on 1=1 where test_id is not null group by test_id";
//OF COURSE IT WILL FAIL.
if($isDynamic)
$sql .= ' where test_id=1';
Using zf2 I could potentially do something like
Setting the query string to a sql object.
Then simply do $obj->where(array('test_id'=>1));
To solve this problem I overloaded method Zend\Db\Sql\Select.
For your example of a complex query, I proceed as follows:
Your query : select * from tbl_test inner join (select * from tbl_test 1) x on 1=1 where test_id is not null group by test_id
My query : SELECT * FROM (select * from tbl_test inner join (select * from tbl_test 1) x on 1=1 where test_id is not null group by test_id) tmp WHERE test_id=1;
If your complex query use alias tmp then change in the method renderTable().
Here is how my class is used (change the namespace as need):
use SbmPdf\Model\Db\Sql\Select;
$sql = "select * from tbl_test inner join (select * from tbl_test 1) x on 1=1 where test_id is not null group by test_id";
$select = new Select($sql);
$select->where(array('id' => 1));
Here is my class (change the namespace as need):
/**
* Surcharge de la classe Zend\Db\Sql\Select pour exécuter une requête complexe basée sur une chaine SQL
*
* On a ajouté la méthode setRecordSource qui permet de passer une chaine SQL complète comme source de donnée.
*
* Lorsque la chaine SQL recordSource est donnée (constructeur ou setter), elle remplace la table indiquée dans FROM.
* En définitive, la méthode from() sera ignorée si la méthode recordSource() est appelée.
* Par contre, si on n'appelle pas cette nouvelle méthode, la classe aura un comportement normal (à condition de ne
* rien passer au constructeur).
*
* Ensuite, pour exécuter la requête, il faut pratiquer de la façon suivante :
* $sqlString = $select->getSqlString($dbAdapter->getPlatform());
* $rowset = $dbAdapter->query($sqlString, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
*
* #project sbm
* #package SbmPdf/Model/Db/Sql
* #filesource Select.php
* #encodage UTF-8
* #author DAFAP Informatique - Alain Pomirol (dafap#free.fr)
* #date 19 août 2015
* #version 2015-1
*/
namespace SbmPdf\Model\Db\Sql;
use Zend\Db\Adapter\Driver\DriverInterface;
use Zend\Db\Adapter\ParameterContainer;
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\Sql\Select as ZendSelect;
class Select extends ZendSelect
{
private $recordSource;
/**
* On passe le recordSource (sql string) par le constructeur. On ne peut plus passer la table.
*
* #param string $recordSource
*/
public function __construct($recordSource = null)
{
parent::__construct();
$this->recordSource = $recordSource;
}
/**
* On peut aussi le passer par le setter
*
* #param string $recordSource
* #return \SbmPdf\Model\Db\Sql\Select
*/
public function setRecordSource($recordSource)
{
$this->recordSource = $recordSource;
return $this;
}
/**
* Surcharge de la méthode
*
* (non-PHPdoc)
*
* #see \Zend\Db\Sql\Select::processSelect()
*/
protected function processSelect(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
$expr = 1;
if (empty($this->recordSource)) {
list ($table, $fromTable) = parent::resolveTable($this->table, $platform, $driver, $parameterContainer);
} else {
list ($table, $fromTable) = $this->resolveTable($this->recordSource, $platform);
}
// process table columns
$columns = array();
foreach ($this->columns as $columnIndexOrAs => $column) {
if ($column === self::SQL_STAR) {
$columns[] = array(
$fromTable . self::SQL_STAR
);
continue;
}
$columnName = $this->resolveColumnValue(array(
'column' => $column,
'fromTable' => $fromTable,
'isIdentifier' => true
), $platform, $driver, $parameterContainer, (is_string($columnIndexOrAs) ? $columnIndexOrAs : 'column'));
// process As portion
if (is_string($columnIndexOrAs)) {
$columnAs = $platform->quoteIdentifier($columnIndexOrAs);
} elseif (stripos($columnName, ' as ') === false) {
$columnAs = (is_string($column)) ? $platform->quoteIdentifier($column) : 'Expression' . $expr ++;
}
$columns[] = (isset($columnAs)) ? array(
$columnName,
$columnAs
) : array(
$columnName
);
}
// process join columns
foreach ($this->joins as $join) {
$joinName = (is_array($join['name'])) ? key($join['name']) : $join['name'];
$joinName = parent::resolveTable($joinName, $platform, $driver, $parameterContainer);
foreach ($join['columns'] as $jKey => $jColumn) {
$jColumns = array();
$jFromTable = is_scalar($jColumn) ? $joinName . $platform->getIdentifierSeparator() : '';
$jColumns[] = $this->resolveColumnValue(array(
'column' => $jColumn,
'fromTable' => $jFromTable,
'isIdentifier' => true
), $platform, $driver, $parameterContainer, (is_string($jKey) ? $jKey : 'column'));
if (is_string($jKey)) {
$jColumns[] = $platform->quoteIdentifier($jKey);
} elseif ($jColumn !== self::SQL_STAR) {
$jColumns[] = $platform->quoteIdentifier($jColumn);
}
$columns[] = $jColumns;
}
}
if ($this->quantifier) {
$quantifier = ($this->quantifier instanceof ExpressionInterface) ? $this->processExpression($this->quantifier, $platform, $driver, $parameterContainer, 'quantifier') : $this->quantifier;
}
if (! isset($table)) {
return array(
$columns
);
} elseif (isset($quantifier)) {
return array(
$quantifier,
$columns,
$table
);
} else {
return array(
$columns,
$table
);
}
}
protected function resolveTable($table, PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
$alias = null;
if (is_array($table)) {
$alias = key($table);
$table = current($table);
} else {
$alias = 'tmp';
}
$fromTable = $platform->quoteIdentifier($alias);
$table = $this->renderTable($table, $fromTable, false);
if ($alias) {} else {
$fromTable = $table;
}
if ($this->prefixColumnsWithTable && $fromTable) {
$fromTable .= $platform->getIdentifierSeparator();
} else {
$fromTable = '';
}
return array(
$table,
$fromTable
);
}
protected function renderTable($table, $alias = null, $parent = true)
{
if ($parent) {
return parent::renderTable($table, $alias);
} else {
if (empty($alias)) {
$alias = 'tmp';
}
return "($table) AS $alias";
}
}
}
You can use directly where clause with your cording.
public function test(){
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$select->where(array('title' => 'abracadabra'));
$select->where
->NEST->
equalTo('id', 1)
->OR->
equalTo('artist', 'Tony')
->UNNEST;
if($isDynamic){
$select->where(array('test_id' => '1'));
}
$select->limit(1);
return $this->tableGateway->selectWith($select);
}
You can use SQL like this
I'm developing ASP.NET MVC5 (Razor) project. I would like to render partial view into a DIV when Test ActionLink clicked, so code for Controller is this:-
public ActionResult Accion(string vista)
{
if (string.IsNullOrEmpty(vista) || !Request.IsAjaxRequest())
return View();
else
{
object vistaModelo = null;
if (vista.Contains("Usuarios"))
vistaModelo = new UsuariosVistaModelo();
string render = PartialView(vista, vistaModelo).RenderToString();
return Json(new { data = render });
}
}
Code for cshtml:-
<div class="menu">
#Html.ActionLink("Test","Accion","Navigation",new { vista = "~/Views/Soporte/Usuarios.cshtml" }, new { #class = "accion" })
<script>
//Dispara la acción en el controlador del servidor
$('.accion').live("click", function () {
$.ajax({
url:this.href,
type:'post',
success:function(data)
{
//data contiene el resultado devuelto por el servidor
$('.content').html(data);
},
error: function (req, status, error) {
alert(error);
}
});
//Se retorna falso para prevenir reenviar a otra pagina
return false;
});
</script>
</div>
<div class="content">
</div>
When I click on Test ActionLink, $('.accion').live("click" ... event is not triggered and go straighforward to Accion into controller. Please need help. Thanks
Some modifications in your code to make it working
** Modify your action to
#Html.ActionLink("Test","Accion","Navigation",new { vista = "~/Views/Soporte/Usuarios.cshtml" }, new { #class = "accion", onclick = "javascript:return false;" })
Now anchor default behaviour would not work.
** Now modify your Jquery like
//Dispara la acción en el controlador del servidor
$('.accion').click(function () {
$.ajax({
url:this.href,
type:'post',
data : {"vista" : "~/Views/Soporte/Usuarios.cshtml"},
success:function(data)
{
//data contiene el resultado devuelto por el servidor
$('.content').html(data);
},
error: function (req, status, error) {
alert(error);
}
});
//Se retorna falso para prevenir reenviar a otra pagina
return false;
});
//Add Post on the top of action
[HttpPost]
public ActionResult Accion(string vista)
{
if (string.IsNullOrEmpty(vista) || !Request.IsAjaxRequest())
return View();
else
{
object vistaModelo = null;
if (vista.Contains("Usuarios"))
vistaModelo = new UsuariosVistaModelo();
string render = PartialView(vista, vistaModelo).RenderToString();
return Json(new { data = render });
}
}
Also use on/click instead of live
Some modification on Jquery level
// code
success:function(data)
{
$('.content').html(data.data);
},
error: function (req, status, error) {
alert(error);
}
// code
try to replace
$('.content').html(data); to $('.content').html(data.data); Here 2nd data is the parameter which holds the value on controller.
I am trying to reuse "Competencia" as a partial view in another page. Just like the old web controls.
When I run as a "normal page", saying, typing
http://mydomain/Competencia
the control works fine. When I use is as a partial view, it does not render
#section Scripts {
<script src="#Url.Content("~/ViewScripts/Competencia/Index.js")" type="text/javascript"></script>
}
and obviously, can't find the method PopularGridArquivo inside it.
Here are the codes:
Competencia/Index.js
/// <reference path="Competencia.js" />
function PopularGridArquivo(mes) {
if (mes != "") {
$.ajax({
url: '/Competencia/ListarArquivosCompetencia',
type: 'post',
data: {
competencia: mes,
caminhoArquivo: $("#path").val()
},
success: function (html) {
$("#divDetalhe").html(html);
},
error: function (a, b, c) {
alert(c);
}
});
}
else {
$("#divdetalhe").html('');
}
}
CompetenciaController:
public class CompetenciaController : Controller
{
//
// GET: /Competencia/
public ActionResult Index()
{
Competencia compet = new Competencia();
compet.pathCompetencias = #"c:\temp\MUMPS\";
ViewBag.Competencia = compet;
return View(compet);
}
[HttpPost]
//public PartialViewResult ListarArquivosCompetencia(string competencia, string caminhoArquivo)
public PartialViewResult ListarArquivosCompetencia(string competencia, string caminhoArquivo)
{
IList<FileInfo> listaArquivos = null;
IList<CargaArquivos> listaCargaArquivos = new List<CargaArquivos>();
CargaArquivos oCargaArquivos = null;
//Popular combo de meses
//caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//DateTime data = new DateTime(DateTime.Now.Year, mes, 1);
caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, competencia);
listaArquivos = PastaArquivo.ListarArquivosDiretorio(caminhoArquivo);
if (listaArquivos.Count > 0)
{
foreach (var item in listaArquivos)
{
oCargaArquivos = new CargaArquivos();
oCargaArquivos.CaminhoArquivo = item.DirectoryName;
oCargaArquivos.NomeArquivo = item.Name;
listaCargaArquivos.Add(oCargaArquivos);
}
ViewBag.listaCargaArquivos = listaCargaArquivos;
}
//return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
}
}
/Views/Competencia/Index.cshtml
#model IcatuValor.Models.Competencia
#section Scripts {
<script src="#Url.Content("~/ViewScripts/Competencia/Index.js")" type="text/javascript"></script>
}
<fieldset>
<div class="left-column">
#Html.Hidden("path", Model.pathCompetencias)
<label class="control-label"> Competência: #Html.DropDownList("ddMeses", new SelectList(Model.Competencias, "Key", "Value"), "Selecione", new { onChange = "JavaScript: PopularGridArquivo(this.value);", #class = "dropdown" })</label>
</div>
<div id="divDetalhe"></div>
#{
if (Model.arquivos != null)
{
Html.RenderPartial("_DetalheCarga", (IList<ViewModels.CargaArquivos>)ViewBag.listaCargaArquivos);
//Html.Partial("_DetalheCarga");
}
}
</fieldset>
Model Competencia:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace IcatuValor.Models
{
public class Competencia
{
public string pathCompetencias { get; set; }
public string pathSubDir { get; set; }
public IEnumerable<KeyValuePair<string, string>> Competencias
{
get
{
//Expressão regular para validar o nome da pasta como formato MMYYYY
var re = new Regex(#"^(0[1-9]|1[0-2])(19|2[0-1])\d{2}$");
DirectoryInfo dirInfo = new DirectoryInfo(pathCompetencias);
foreach (DirectoryInfo dir in dirInfo.GetDirectories())
{
//Somente entram na listagem diretórios que satisfizerem o formato MMYYYY
if (re.IsMatch(dir.Name))
yield return new KeyValuePair<string, string>
(
dir.Name,
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Convert.ToInt16(dir.Name.Substring(0, 2))) + "/" + dir.Name.Substring(2)
);
}
}
}
public IList<DirectoryInfo> Subdiretorios
{
get
{
DirectoryInfo di = new DirectoryInfo(pathSubDir);
return di.GetDirectories();
}
}
public IList<FileInfo> arquivos
{
get;
set;
}
}
}
And finally, the another page, which will use "Competencia" inside it:
Cargamumps/Index.cshtml
#section Scripts {
<script src="#Url.Content("~/ViewScripts/CargaMumps/Index.js")" type="text/javascript"></script>
}
<fieldset>
<legend>Carregar Arquivos</legend>
#*<div class="input-append date datepicker" data-date-format="dd/mm/yyyy">
<label class="lbl">Data início</label>
<input type="text" class="datePicker" name="DataInicio" id="DataInicio" style="width: auto">
</div>*#
<div class="input-append" id="divArquivos">
<div class="input-append">
<label class="control-label">LF02 (LF02AAAAMM.TXT):</label>
#Html.TextBox("filLF02", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">LF03 (LF03AAAAMM.TXT):</label>
#Html.TextBox("filLF03", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">Pendência Atual (PendentesAAAAMM.txt):</label>
#Html.TextBox("filPendentes", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">Pendência Anterior (PendentesAAAAMM.txt):</label>
#Html.TextBox("filPendentesAnterior", null, new { type = "file", #class = "input-large" })
</div>
<br />
<div class="input-append">
<button type="submit" class="btn btn-primary" id="btnSubmit">Executar Matemática</button>
</div>
</div>
</fieldset>
<fieldset>
#{
//RENDERS OK
Html.RenderPartial("~/Views/Competencia/Index.cshtml", (IcatuValor.Models.Competencia)ViewBag.Competencia);
}
</fieldset>
CargamumpsController.cs
using System.Web.Mvc;
using System;
using DAL.Repository;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using ViewModels;
using DAL;
using System.Text.RegularExpressions;
using System.Management;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;
using System.Collections;
using System.Diagnostics;
using IcatuValor.Utils;
using IcatuValor.Models;
namespace IcatuValor.Controllers
{
public class CargaMumpsController : Controller
{
#region Actions
private Dictionary<string, string> dictionary = new Dictionary<string, string>();
public enum ELivro
{
LF02 = 1,
LF03 = 2,
Pendentes = 3,
PendentesAnterior = 4
}
public ActionResult Index()
{
//Pega o mês anterior ultimo fechamento
DateTime now = DateTime.Now.AddMonths(-1);
Competencia compet = new Competencia();
compet.pathCompetencias = #"c:\temp\MUMPS\";
ViewBag.Competencia = compet;
return View();
//ListarArquivosMes(now.Month);
//return View();
}
[HttpPost]
public string Upload(FormCollection form)
{
try
{
ProcedureRepository procedureRepository = new ProcedureRepository();
DataTable dtResultado = null;
double somaEmissoes, somaCancelamentos, somaPagos, somaPendente, somaPendenteAnterior;
Stopwatch st = new Stopwatch();
st.Start();
string pathLF02 = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo1"]);
string pathLF03 = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo2"]);
string pathPendentes = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo3"]);
string pathPendentesAnterior = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo4"]);
//Pegar mes atual e anterior com base no mes e ano dos nomes dos arquivos.
FileInfo fi = new FileInfo(pathLF02);
int ano, mes;
if (!int.TryParse(fi.Name.Substring(4, 4), out ano) || !int.TryParse(fi.Name.Substring(8, 2), out mes))
throw new Exception("O nome do arquivo LF02 deve estar no formato 'LF02AAAAMM.TXT'.\n\nAAAA - Ano com 4 digitos\nMM - Mês com 2 dígitos.");
DateTime dataFechamento = new DateTime(ano, mes, 1);
//DateTime dataFechamento = Convert.ToDateTime(form["dtInicio"]);
IDataReader dr;
#region LF02
if (!string.IsNullOrEmpty(pathLF02))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathLF02);
//AjustarColunas(dtResultado, ELivro.LF02);
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathLF02);
procedureRepository.TruncarTabela("dbo.LivroMumps_LF02");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_LF02");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_LF02");
//dtResultado.Clear();
}
#endregion
#region LF03
if (!string.IsNullOrEmpty(pathLF03))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathLF03);
//AjustarColunas(dtResultado, ELivro.LF03);
//procedureRepository.TruncarTabela("dbo.LivroMumps_LF03");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_LF03");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathLF03);
procedureRepository.TruncarTabela("dbo.LivroMumps_LF03");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_LF03");
}
#endregion
#region Pendentes
if (!string.IsNullOrEmpty(pathPendentes))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathPendentes);
//AjustarColunas(dtResultado, ELivro.Pendentes);
//procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_Pendentes");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathPendentes);
procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_Pendentes");
}
#endregion
#region Pendentes Mês Anterior
if (!string.IsNullOrEmpty(pathPendentesAnterior))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathPendentesAnterior);
//AjustarColunas(dtResultado, ELivro.PendentesAnterior);
//procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes_Anterior");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_Pendentes_Anterior");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathPendentesAnterior);
procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes_Anterior");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_Pendentes_Anterior");
}
#endregion
dtResultado = procedureRepository.CalcularFechamentoMumps(dataFechamento, out somaEmissoes, out somaCancelamentos, out somaPagos, out somaPendente, out somaPendenteAnterior);
GerarPlanilhaExcel(dtResultado, dataFechamento, somaEmissoes, somaCancelamentos, somaPagos, somaPendente, somaPendenteAnterior);
//TODO - VERIFICAR NECESSIDADE DE ENVIAR E-MAIL.
//EnviarEmail(dataFechamento);
st.Stop();
return "Calculo executado com sucesso.\n\nTempo de execução: " + st.Elapsed.ToString();
}
catch (Exception ex)
{
PastaArquivo.EscreveLog(ex.ToString());
return ex.ToString();
}
}
private void EnviarEmail(DateTime dtCompetencia)
{
string emailPara = System.Configuration.ConfigurationManager.AppSettings["EmailPara"].ToString();
string mesAnoCompetencia = dtCompetencia.ToString("MM/yyyy");
string msgEmail = "Fechamento de prêmios (MUMPS) referente a " + mesAnoCompetencia + " concluído com sucesso!";
string assuntoEmail = "Fechamento " + mesAnoCompetencia + " - MUMPS";
string emailDe = System.Configuration.ConfigurationManager.AppSettings["EmailDe"].ToString();
if (!string.IsNullOrEmpty(emailPara) && !string.IsNullOrEmpty(emailDe))
Utils.Email.EnviarEmail(emailDe, emailPara, msgEmail + "\n \n", assuntoEmail);
}
private void GerarPlanilhaExcel(DataTable dtResultado, DateTime dataFechamento, double somaEmissoes, double somaCancelamentos, double somaPagos, double somaPendente, double somaPendenteAnterior)
{
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//Pega o caminho onde será salvo o nosso arquivo
string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//Criar uma pasta para identificar o mes referencia
caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, dataFechamento);
Utils.PastaArquivo.VerificaExistenciaECriaPasta(caminhoArquivo);
string filename = string.Format(#"{0}\Pend_{1:MMyyyy}.xls", caminhoArquivo, dataFechamento);
// Verifica se existe algum arquivo com o mesmo nome e caminho de destino, se existir exclui
if (System.IO.File.Exists(filename)) System.IO.File.Delete(filename);
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(Server.MapPath("~/LivrosMumps/Template.xls"), 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, false, false, false);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.get_Range("A2").Value = string.Format("CONTROLE DE RELATÓRIOS - {0:MM/yyyy}", dataFechamento);
xlWorkSheet.get_Range("B6;B35;B67;B97;B128").Value = string.Format("{0:MM/yyyy}", dataFechamento.AddMonths(-1));
xlWorkSheet.get_Range("F6;F35;F67;F97;F128").Value = string.Format("{0:MM/yyyy}", dataFechamento);
InserirValores(dtResultado, xlWorkSheet);
xlWorkBook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(false, filename, misValue);
xlApp.Quit();
Utils.PastaArquivo.liberarObjetos(xlWorkSheet);
Utils.PastaArquivo.liberarObjetos(xlWorkBook);
Utils.PastaArquivo.liberarObjetos(xlApp);
}
/// <summary>
/// Insere os valores na planilha template
/// </summary>
/// <param name="dtResultado">Datatable com os valores do livro</param>
/// <param name="xlWorkSheet">Planilha</param>
private void InserirValores(DataTable dtResultado, Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet)
{
List<string> result;
ProcedureRepository pr = new ProcedureRepository();
foreach (DataRow dr in dtResultado.Rows)
{
result = pr.ObterValoresLivroMumps(Convert.ToInt16(dr["COD_RAMO"].ToString()), dr["SUCURSAL"].ToString());
if (result.Count > 0)
{
xlWorkSheet.get_Range(result[0]).Value = Convert.ToDouble(dr["PREMIO_PENDENTE_ANT"].ToString());
xlWorkSheet.get_Range(result[1]).Value = Convert.ToDouble(dr["PREMIO_EMITIDO"].ToString());
xlWorkSheet.get_Range(result[2]).Value = Convert.ToDouble(dr["PREMIO_CANCELADO"].ToString());
xlWorkSheet.get_Range(result[3]).Value = Convert.ToDouble(dr["PREMIO_PAGO"].ToString());
xlWorkSheet.get_Range(result[4]).Value = Convert.ToDouble(dr["PREMIO_PENDENTE"].ToString());
}
}
}
[HttpPost]
public ActionResult AbrirArquivoExcel(CargaArquivos cargaArquivos)
{
Utils.PastaArquivo.ExportarCSV(cargaArquivos.CaminhoArquivo + #"\" + cargaArquivos.NomeArquivo);
return View();
}
[HttpPost]
//public PartialViewResult ListarArquivosMes(int mes)
//{
// IList<FileInfo> listaArquivos = null;
// IList<CargaArquivos> listaCargaArquivos = new List<CargaArquivos>();
// CargaArquivos oCargaArquivos = null;
// //Popular combo de meses
// ViewBag.ListaMeses = Model.AllMonths;
// string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
// DateTime data = new DateTime(DateTime.Now.Year, mes, 1);
// caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, data);
// listaArquivos = Utils.PastaArquivo.ListarArquivosDiretorio(caminhoArquivo);
// if (listaArquivos.Count > 0)
// {
// foreach (var item in listaArquivos)
// {
// oCargaArquivos = new CargaArquivos();
// oCargaArquivos.CaminhoArquivo = item.DirectoryName;
// oCargaArquivos.NomeArquivo = item.Name;
// listaCargaArquivos.Add(oCargaArquivos);
// }
// ViewBag.listaCargaArquivos = listaCargaArquivos;
// }
// return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
//}
#endregion
#region Métodos privados
/// <summary>
/// Faz o de-para das colunas do TXT para as colunas da Base de Dados
/// </summary>
/// <param name="dtResultado"></param>
/// <param name="livro"></param>
private void AjustarColunas(DataTable dtResultado, ELivro livro)
{
dictionary.Clear();
switch (livro)
{
case ELivro.LF02:
LerDictionaryLF02();
break;
case ELivro.LF03:
LerDictionaryLF03();
break;
case ELivro.Pendentes:
case ELivro.PendentesAnterior:
LerDictionaryPendentes();
break;
}
foreach (DataColumn dc in dtResultado.Columns)
{
if (dictionary.FirstOrDefault(x => x.Key == dc.ColumnName).Value == null)
throw new Exception(string.Format("Coluna: {0} inválida no livro {1}.", dc.ColumnName, livro.ToString()));
dc.ColumnName = dictionary[dc.ColumnName];
}
}
private void LerDictionaryLF02()
{
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("ramo", "Ramo");
dictionary.Add("data emissao", "DataEmissao");
dictionary.Add("numero da cobranca", "Numero_da_Cobranca");
dictionary.Add("numero da apolice", "Numero_da_Apolice");
dictionary.Add("segurado ou estipulante", "Segurado_ou_Estipulante");
dictionary.Add("inicio seguro", "Inicio_Seguro");
dictionary.Add("termino seguro", "Termino_Seguro");
dictionary.Add("parcela/fatura", "Parcela_Fatura");
dictionary.Add("premio da lider", "Premio_da_Lider");
dictionary.Add("premio das cosseguradoras", "Premio_das_Cosseguradoras");
dictionary.Add("custo de emissao", "Custo_de_Emissao");
dictionary.Add("iof", "IOF");
dictionary.Add("premio total", "Premio_Total");
dictionary.Add("risco", "Risco");
dictionary.Add("produto", "Produto");
dictionary.Add("data venc fat", "Data_Venc_Fat");
dictionary.Add("data pagto fat", "Data_Pagto_Fat");
dictionary.Add("data emissao_", "Data_Emissao_Cancelamento");
dictionary.Add("quantidade de vidas", "Quantidade_de_Vidas");
dictionary.Add("descricao da periodicidade de pagamento", "Descr_Period_Pagamento");
dictionary.Add("tipo de apolice", "Tipo_de_Apolice");
dictionary.Add("competencia inicial", "Competencia_Inicial");
dictionary.Add("competencia final", "Competencia_Final");
dictionary.Add("data da arrecadacao", "Data_da_Arrecadacao");
dictionary.Add("ipd", "IPD");
dictionary.Add("idade", "Idade");
dictionary.Add("data de nascimento", "Data_de_Nascimento");
dictionary.Add("codigo da periodicidade de pagamento", "Codigo_Period_Pagamento");
dictionary.Add("matricula", "Matricula");
dictionary.Add("taxa", "Taxa");
dictionary.Add("importancia segurada", "Importancia_Segurada");
dictionary.Add("canal", "Canal");
dictionary.Add("ccusto", "CCusto");
dictionary.Add("unidprod", "UnidProd");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("pro-labore", "Pro_labore");
dictionary.Add("keyaccount", "KeyAccount");
}
private void LerDictionaryLF03()
{
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("ramo", "Ramo");
dictionary.Add("data de emissão", "Data_Emissao");
dictionary.Add("data de emiss?", "Data_Emissao");
dictionary.Add("ordem da apolice", "Ordem_Apolice");
dictionary.Add("numero da apolice", "Numero_Apolice");
dictionary.Add("parcela", "Parcela");
dictionary.Add("segurado/estipulante", "Segurado_Estipulante");
dictionary.Add("produto", "Produto");
dictionary.Add("ini seguro", "InicioSeguro");
dictionary.Add("prem/juros", "Prem_Juros");
dictionary.Add("premio da lider", "PremioLider");
dictionary.Add("custo de emissao", "Custo_Emissao");
dictionary.Add("iof", "IOF");
dictionary.Add("premio total", "PremioTotal");
dictionary.Add("fatura", "Fatura");
dictionary.Add("a/r", "AR");
dictionary.Add("risco", "Risco");
dictionary.Add("dt ef cob", "Dt_Ef_Cob");
dictionary.Add("cpf/cnpj", "CPF_CNPJ");
dictionary.Add("fim seguro", "Fim_Seguro");
dictionary.Add("juros da lider", "Juros_Lider");
dictionary.Add("juros cossegur.", "Juros_Cosseguro");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("pro-labore", "ProLabore");
dictionary.Add("comp inicial", "CompInicial");
}
private void LerDictionaryPendentes()
{
dictionary.Add("unidade produtora", "Unidade_Produtora");
dictionary.Add("ramo", "Ramo");
dictionary.Add("produto", "Produto");
dictionary.Add("data emissao", "Data_Emissao");
dictionary.Add("cobranca", "Cobranca");
dictionary.Add("apolice", "Apolice");
dictionary.Add("estipulante", "Estipulante");
dictionary.Add("vigencia", "Vigencia");
dictionary.Add("data vencimento", "Data_Vencimento");
dictionary.Add("valor bruto emitido", "Valor_Bruto_Emitido");
dictionary.Add("fatura", "Fatura");
dictionary.Add("cod ramo_produto", "Cod_Ramo_Produto");
dictionary.Add("descricao", "Descricao");
dictionary.Add("cod canal", "Cod_Canal");
dictionary.Add("descricao_", "Descricao_Canal");
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("centro de custo", "CCusto");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("prolabore", "Prolabore");
dictionary.Add("keyaccount", "KeyAccount");
dictionary.Add("vl_iof", "Vl_IOF");
}
#endregion
}
}
If I'm understanding you correctly, you have a strongly-typed view that you would like to use on multiple pages (Cargamumps/Index and Competencia/Index.cshtml). These two Index pages both share the same ViewModel type Competencia.
If this is the case, I would suggest extracting the common content into a partial view under Shared/EditorTemplates or Shared/DisplayTemplates. Then in the two index views, do a call to EditorFor or DisplayFor.
Html.EditorFor(m => m);
or
Html.DisplayFor(m => m);
If your ViewData.Model is type Competencia, this will locate the proper editor/display template and render it inline, as well as properly construct the id/name of any controls so that model binding works out of the box.