How I use reportviewer in C# MVC3 - c#

I have a function that generates a report. It works. My problem is that I use MVC3 in C # and I can not insert a reportviewer in a file. Cshtml. Ascx I am using to try to show the report, but the following error occurs:
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil ServerExecuteHttpHandlerWrapper +'
when I call o#Html.Partial ("relatorioApontamento") in relatorio.cshtml file.
relatorio.cshtml
#{
ViewBag.Title = "relatorio";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/relatorio.js")" type="text/javascript"></script>
#using (Html.BeginForm("relatorio", "Paginas", FormMethod.Post, new { #id = "frmParametroConfigPath" }))
{
<div id="relatorio">
<h1 class="titulo">Relatório</h1>
<div class="boxRecurso">
<label id="lbl_recurso">Recurso:</label><br />
<select ID="ddl_nm_recurso" class="txtRecurso"></select>
</div>
<div class="boxDataInicial">
<label id="lbl_data_inicial">Data Inicial:</label><br />
<input type="text" id="datepicker_ida" />
</div>
<div class="boxDataFinal">
<label id="lbl_data_final">Data Final:</label><br />
<input type="text" id="datepicker_volta" />
</div>
<div id="box_btnGerar">
<input type="button" ID="btnGerar" class="botao" value="Gerar" />
</div>
</div>
#Html.Partial("relatorioApontamento");
relatorioApontamento.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="relatorioApontamento.ascx.cs" Inherits="ControleBU.Views.Paginas.relatorioApontamento" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="rv" runat="server" Height="679px" Width="1300px">
</rsweb:ReportViewer>
relatorioApontamento.ascx.cs
namespace ControleBU.Views.Paginas
{
public partial class relatorioApontamento : System.Web.Mvc.ViewUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["item"] != null)
{
rv.LocalReport.ReportPath = "Reports\\Report1.rdlc";
rv.LocalReport.DataSources.Add((ReportDataSource)Session["item"]);
rv.LocalReport.SetParameters(new ReportParameter("TotalHoras", Convert.ToInt32(Math.Truncate(((TimeSpan)Session["TotalHoras"]).TotalHours)).ToString() + ":" + ((TimeSpan)Session["TotalHoras"]).Minutes.ToString()));
rv.LocalReport.SetParameters(new ReportParameter("Ida", Convert.ToString(Session["DataInicio"])));
rv.LocalReport.SetParameters(new ReportParameter("Volta", Convert.ToString(Session["DataFim"])));
rv.LocalReport.Refresh();
}
}
}
}
function in Paginas Controller
public int gerarRelatorioRelatorio(DateTime datepicker_ida, DateTime datepicker_volta, string ddl_nm_recurso)
{
try
{
ProjectBoxDAL dalProjectBox = new ProjectBoxDAL();
Softbox.DashBordGBU.Reports.dtsReportRecurso dt = new Softbox.DashBordGBU.Reports.dtsReportRecurso();
BUProjetosDAL dalBuProjetos = new BUProjetosDAL();
int codRecurso = Convert.ToInt32(ddl_nm_recurso);
int codCliente = dalBuProjetos.retornaCodigoClienteRecurso(codRecurso);
IDataReader dr = dalProjectBox.relatorioRecurso(codCliente, datepicker_ida, datepicker_volta, codRecurso);
dt.Tables[0].Load(dr);
if (dt.Tables[0].Rows.Count > 0)
{
var total = dt.ReportRecurso.AsEnumerable().Sum(x => x.horas_ms);
TimeSpan totalHoras = TimeSpan.FromMilliseconds(total);
Microsoft.Reporting.WebForms.ReportDataSource item = new Microsoft.Reporting.WebForms.ReportDataSource();
item.Value = dt.Tables[0];
item.Name = "ReportRecurso";
ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
Session["DataInicio"] = datepicker_ida;
Session["DataFim"] = datepicker_volta;
Session["ddl"] = ddl_nm_recurso;
Session["TotalHoras"] = totalHoras;
Session["Item"] = item;
return 1;
}
else
return 2;
}
catch (Exception)
{
return 0;
}
}

You dont need new view or partial view to show your report :) just do the following :
at the end of your Paginas controller add new method call print()
and in print method define your report and print it as pdf like the following :
public void Print()
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = #"report full path [Reports/myreport.rdlc]";
//if you have parameters set your parameters here
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] rebytes = localReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("application/pdf", "attachment; filename= filename" + "." + filenameExtension);
Response.OutputStream.Write(rebytes, 0, rebytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
}

Related

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?
Because I ask question at link but I learn asp:Repeater tag article have to declare Microsoft SQL Server database in DataBind article.
I ask question to solve "How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database."
Good news : I have answer to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database.
My full source code.
https://github.com/doanga2007/CheckLoopQR
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 4; i++)
{
num += i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Item Text1 : ", "Selected Item Text2 : ", "Selected Item Text3 : " };
int a = 0;
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
a++;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a-1] + listItem.Text;
lblvalues.Font.Size = FontUnit.Large;
Label lblvalues2 = new Label();
lblvalues2.Text += texture[a-1] + listItem.Text;
lblvalues2.Font.Size = FontUnit.Large;
Label lblvalues3 = new Label();
lblvalues3.Text += texture[a-1] + listItem.Text;
lblvalues3.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues2);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues3);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}

How coding to can for loop asp:RadioButton tag same as for loop asp:Label tag?

How coding to can for loop asp:RadioButton tag same as for loop asp:Label tag , Because I can for loop asp:Label tag with tutorial website
https://asp-net-example.blogspot.com/2008/12/aspnet-for-loop-example-using-for-loop.html
but I can't for loop asp:RadioButton tag same as for loop asp:Label tag.
Sample code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QRCode_Demo.QRCode" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br /><br />
<asp:RadioButton id="CheckBox1" runat="server" Font-Size="Large"></asp:RadioButton><asp:Label ID="checker" runat="server" Font-Size="Large"></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
for (int i = 1; i < 11; i++)
{
checker.Text += " " + code + "<br>";
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
CheckBox1.Visible = false;
checker.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}
Good News , I found answer to can for loop asp:RadioButton tag same as for loop asp:Label tag (Answer code found at link).
Answer code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QRCode_Demo.QRCode" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br /><br />
<asp:RadioButtonList
ID="CheckBox1"
runat="server"
RepeatDirection="Vertical"
Border="1"
BorderColor="LightGray"
Font-Size="Large"></asp:RadioButtonList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
int i;
for (i = 1; i < 11; i++)
{
CheckBox1.Items.Add(new ListItem(" " + code));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
CheckBox1.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}

How to insert json message in modal with asp.net mvc

I'm developing a system in .NET and I need to send a json controller msg to the view and show it in modal.
The user will import a spreadsheet and the spreadsheet will be inserted in the database, at the end of the modal it should appear with the message whether it was sent or not.
Or backend is already working.
 
I need help on the front because when I import, it loads a new page with
["Sent with success"]
(the messages are in portuguese) = ["Enviado com sucesso"]
Follows the controller code.
public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = "C:/Users/70561/Documents";
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Planilha1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Planilha1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var dados = from a in excelFile.Worksheet<RETORNO_CM>(sheetName) select a;
foreach (var a in dados)
{
try
{
if (a.CM_CODIGO != null && a.CM_QM_COMPONENTE_RMA != null && a.CM_NS != null && a.CM_DESCRICAO != null &&
a.CM_DEFEITO != null && a.J_FALHA != null &&
a.CM_TIPO_DEFEITO != null && a.J_PLACA_RETRABALHO != null &&
a.J_PLACA_RESTESTADA != null && a.J_STATUS != null && a.CM_NOME_TESTE != null && a.CM_NOME_DEBUG != null)
{
RETORNO_CM CM = new RETORNO_CM();
CM.CM_CODIGO = a.CM_CODIGO;
CM.CM_QM_COMPONENTE_RMA = a.CM_QM_COMPONENTE_RMA;
CM.CM_NS = a.CM_NS;
CM.CM_DESCRICAO = a.CM_DESCRICAO;
CM.CM_DATA_REPARO = a.CM_DATA_REPARO;
CM.CM_DEFEITO = a.CM_DEFEITO;
CM.J_FALHA = a.J_FALHA;
CM.CM_TIPO_DEFEITO = a.CM_TIPO_DEFEITO;
CM.CM_COMPONENTE = a.CM_COMPONENTE;
CM.J_PLACA_RETRABALHO = a.J_PLACA_RETRABALHO;
CM.J_PLACA_RESTESTADA = a.J_PLACA_RESTESTADA;
CM.J_STATUS = a.J_STATUS;
CM.CM_NOME_TESTE = a.CM_NOME_TESTE;
CM.CM_NOME_DEBUG = a.CM_NOME_DEBUG;
db.RETORNO_CM.Add(CM);
db.SaveChanges();
}
else
{
data.Add("<ul>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
data.Add("Enviado com sucesso");
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("Apenas arquivos excel sao suportados");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
if (FileUpload == null) data.Add("Selecione um arquivo");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
my view code
<div class="box">
<div class="box-body">
<hr />
<article class="table-responsive" style="overflow:hidden">
<p class="lead">Teste de importação.</p>
<hr />
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enviar" id="btnSubmit" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>
<b>Message:</b><br>
<input class="message-edit-text" type="text" size="20">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</div>
You should not return JSON, as you are performing a full page postback. Instead, you should return a View.
If you do not want to perform a full page postback, you want to use Ajax since the beginning of the request.
For example,
View
Please make sure button is type="button" to avoid full page postback.
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" class="btn btn-primary">
Enviar
</button>
</div>
</div>
</div>
}
<script>
$(function () {
$('#btnSubmit').click(function() {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '#Url.Action("UploadExcel", "RetornoCM")',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function(result) {
alert(result);
},
error: function(err) {
alert(err.statusText);
}
});
}
});
});
</script>
Action Method
[HttpPost]
public ActionResult UploadExcel()
{
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
// Do somethig with file
}
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Source: File Upload Through JQuery AJAX In ASP.NET MVC

Expected end of MIME multipart stream. MIME multipart message is not complete

I have an Angular application, written in Typescript, with an ASP.Net Web Api backend. I am trying to use the ng-file-upload (see this link for details) directive to upload an image file.
I receive an exception in my Web API Post method:
"Unexpected end of MIME multipart stream. MIME multipart message is not complete."
I've done my research and found similar issues here - I have tried to implement Landuber Kassa's answer but without success.
Also this although my project is not MVC and in any case it did not work.
I am fresh out of ideas and would appreciate the community's thoughts. I am happy to consider any other alternatives if I can be pointed in the right direction.
Ash
My .Net Post method (implementing Landuber Kassa's idea):
[RoutePrefix("BeaufortAppStore/api/Image")]
public class ImageController : ApiController
{
#region Methods
#region Posts
[Route("UploadImage")]
[HttpPost]
public async Task<IHttpActionResult> UploadImage()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
MemoryStream tempStream = new MemoryStream();
reqStream.CopyTo(tempStream);
tempStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(tempStream);
writer.WriteLine();
writer.Flush();
tempStream.Position = 0;
StreamContent streamContent = new StreamContent(tempStream);
foreach (var header in Request.Content.Headers)
{
streamContent.Headers.Add(header.Key, header.Value);
}
// Read the form data and return an async task.
await streamContent.ReadAsMultipartAsync(provider); // FAILS AT THIS POINT
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
//Do whatever you want with filename and its binary data.
}
return Ok();
}
#endregion
#endregion
My angular controller method:
public upload(): void {
//Create config used in ng-file-upload
var config: IFileUploadConfigFile = {
data: this.file, url: "BeaufortAppStore/api/Image/UploadImage/", method: "POST" };
this._dataService.uploadImage(config).then((result: any) => {
this.thumbnail = result.data;
});
}
My angular view (partial view for a directive):
<div class="form-group">
<label for="file" class="control-label col-xs-2">Choose a file</label>
<input id="file" type="file" name="file" class="form-control" ngf-select ngf-pattern="'image/*'"
ng-model="vm.file" />
<img style="width:100px;" ngf-thumbnail="thumbnail || '/thumb.jpg'" />
<button type="submit" ng-click="vm.upload()">Upload</button>
Try this in C#:
[HttpPost]
[Route("Profile/Image")]
public Task<HttpResponseMessage> UploadImgProfile()
{
try
{
if (!ModelState.IsValid) return null;
var currentUser = _userUtils.GetCurrentUser(User);
if (currentUser == null) return null;
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
string root = HttpContext.Current.Server.MapPath("~" + Constant.Application.User_Image_Directory);
bool exists = Directory.Exists(root);
if (!exists)
Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
var finfo = new FileInfo(provider.FileData.First().LocalFileName);
string guid = Guid.NewGuid().ToString();
var fileName = guid + "_" + currentUser.IdOwin + ".jpg";
File.Move(finfo.FullName, Path.Combine(root, fileName));
return new HttpResponseMessage()
{
Content = new StringContent(Path.Combine(Constant.Application.User_Image_Directory, fileName))
};
}
);
return task;
}
catch (Exception ex)
{
_logger.LogException(ex);
return null;
}
}
Angular Controller:
//Upload Func
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
$scope.uploading = true;
// $scope.imageName = file.name;
$upload.upload({
url: enviroment.apiUrl + '/api/CurrentUser/Profile/Image',
//fields: { 'username': $scope.username },
file: file
}).progress(function (evt) {
$scope.uploading = true;
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
$scope.progress = progressPercentage;
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
$scope.imageName = data;
$scope.uploading = false;
$scope.loadSuccess = true;
vm.uploadImage = false;
//AR
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function ($scope) {
$scope.myImage = evt.currentTarget.result;
});
};
reader.readAsDataURL(files[0]);
//END AR
});
}
}
};
// Stay on Listen upload file
$scope.$watch('files', function (evt) {
$scope.upload($scope.files);
});
HTML:
<div class="row">
<!--UPLOAD-->
<div class="up-buttons">
<div class="clearfix visible-xs-block"></div>
<div class="col-md-12 col-lg-12 col-sm-12 col-xs-12 text-center box-upload-image" data-ng-show="profileCtrl.uploadImage">
<br />
<div id="imgDragDrop" ng-file-drop ng-model="files"
drag-over-class="dragover"
accept="image/*">
<div class="cropArea-bkg">
<h4>
<span class="mdi mdi-account mdi-48px"></span>
<br /><br />
Carica immagine profilo
</h4>
<p>Trascina qui la tua immagine, oppure</p>
<div ng-file-select="" ng-model="files" class="btn btn-secondary" ng-accept="'*.pdf,*.jpg,*.png'" tabindex="0">
Sfoglia sul tuo computer
</div><br>
</div>
</div>
<div ng-no-file-drop class="well bg-danger">File Drag/Drop non è supportato da questo browser</div>
<br />
<div class="text-center">
<div class="progress" ng-show="uploading">
<div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="{{ ::progress }}" aria-valuemin="0" aria-valuemax="100" style="width: {{::progress}}% ">
<span class="sr-only">{{ ::progress }}% Complete</span>
</div>
</div>
</div>
</div>
<!--END UPLOAD-->
</div>
</div>

Implement LDAP in ASP.net (C#) MVC4

I originally got this working on a ASP.net application (non MVC) but now that I have to change over to MVC I do not know how to adapt my old code. For reference, I am using the stock website you get for the application (needed to be quick and dirty) and I am also sewing in Zurb's Foundation framework. This is also C# based.
Here is the old way that worked:
LOGIN.ASPX
<form id="Login" method="post" runat="server">
<fieldset>
<legend>Please login</legend>
<asp:Label ID="errorLabel" Runat="server" ForeColor=#ff3300></asp:Label><br>
<div class="row">
<div class="large-12 columns">
<label>Domain:</label>
<asp:TextBox ID="txtDomain" Runat="server" placeholder="Human Check: Please type WORKGROUP"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Username:</label>
<asp:TextBox ID=txtUsername Runat="server" ></asp:TextBox>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Password:</label>
<asp:TextBox ID="txtPassword" Runat="server" TextMode=Password></asp:TextBox><br>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<%-- Submit--%>
<asp:Button ID="Button1" Runat="server" Text="Login" OnClick="Login_Click" CssClass="button"></asp:Button>
</div>
<div class="large-6 columns">
<br />
<asp:CheckBox ID=chkPersist Runat="server" /> Remember Me
</div>
</div>
</fieldset>
</form>
Here was the script below (Same Page) that worked.
<script runat="server">
void Login_Click(object sender, EventArgs e)
{
string adPath = "LDAP://DC03/DC=Meowmeow,dc=com"; //Path to your LDAP directory server
Legend_Forms_Manager.LdapAuthentication adAuth = new Legend_Forms_Manager.LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text,DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch(Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
</script>
LdapAuthentication.cs
using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;
namespace Legend_Forms_Manager
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd, AuthenticationTypes.SecureSocketsLayer);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
}
}
I included the following references:
~ System.DirectoryServices
I am having EXTREME difficulty finding anywhere that has any iota of consistency in a tutorial that does not date back to 2008 or so.
If you can please help me... I have everything out here and now it just needs to be translated, I think.
I added the .aspx and .cs from the old to the new, added ADConnectionString to web.config, and added tokens to the .cs and the .aspx to prevent cross-site scripting (it forced me to as per the references). You can now get to the page, fill in the info, but when you click 'Submit' it blanks the page and does nothing. Still need help.

Categories