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.
Related
My code is working, but the COUNT(*) always returns -1. I am trying to check if a user exists in my HTML/JS/ASP code. I don't think I am converting the value correctly, but I am not certain. The code I am focused on is:
#{
var userCheck = "SELECT COUNT(*) FROM USR WHERE EMAIL = #email1";
var rowCount = db.Execute(userCheck);
int temp = Convert.ToInt32(rowCount.ToString());
}
My Javascript code is: var error = ""; and error += #temp;. I don't understand why it is always returning negative one. Please assist! :-)
Here is my full code for # { }
#{
Page.Title = "Register";
var minPass = 2;
var maxPass = 100;
var email1 = "";
var pass1 = "";
var db = Database.Open("Resume");
var userCheck = "SELECT COUNT(*) FROM USR WHERE EMAIL = #email1";
var userInsert = "INSERT INTO USR (EMAIL, PSWD) VALUES (#0, #1)";
var rowCount = db.Execute(userCheck);
int temp = Convert.ToInt32(rowCount.ToString());
if(IsPost) {
email1 = Request.Form["email1"];
pass1 = Request.Form["pass1"];
db.Execute(userInsert, email1, pass1);
Response.Redirect("~/Default");
}
}
I do not have a reputation high enough to comment but what the others said is correct. You need to parameterize your first query. Check out the SqlCommand AddWithParameter method to do that.
I also saw another issue in your code. You have the rowCount variable which will store an integer that contains the amount of users in the database with a specific email, but you need to do some logic with that before you insert another user into the database.
I want to apologize for having asked such a stupid question - my approach was entirely wrong. After spending hours upon hours, I have formulated a solution: websecurity.
Below is a working solution for myself. Be sure to WebSecurity.InitializeDatabaseConnection("ResumeLink", "UserProfile", "UserId", "Email", true);
#{
var username = "";
var password = "";
var confirmPassword = "";
var regMsg = "";
var minPass = 2;
var maxPass = 5;
if (!IsPost) {
if (WebSecurity.IsAuthenticated) {
regMsg = String.Format("You are already logged in. (User name: {0})", WebSecurity.CurrentUserName);
}
}
if (IsPost){
WebSecurity.Logout();
username = Request["username"];
password = Request["password"];
confirmPassword = Request["confirmPassword"];
try {
var mail = new System.Net.Mail.MailAddress(username);
} catch {
regMsg += "Invalid email format.";
}
//Validation.Add("username", Validator.Regex(#"^[A-Za-z0-9._%+-]+##[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", regMsg += "Invalid email format."));
if (password != confirmPassword) {regMsg += "</br>Passwords don't match.";}
if (WebSecurity.UserExists(username)) {regMsg += String.Format("</br>User '{0}' already exists.", username);}
if (password.Length < minPass || password.Length > maxPass) {regMsg += "</br>Password doesn't meet length requirement.";}
if (regMsg == "") {
WebSecurity.CreateUserAndAccount(username,password,null,false);
regMsg = String.Format("{0} created.", username);
Response.Write("Registration Successful!");
Response.Redirect("~/Default.cshtml");
}
}
}
<style>header {visibility: hidden;}</style>
<body>
<div>
<h1>Register</h1>
<form method="post">
<p>
#if(regMsg != ""){
<span class="errorMessage">#Html.Raw(regMsg)</span>
}
</p>
<p>
<label for="username">Email Address:</label><br/>
<input type="text" name="username" id="username" value='#Request["username"]' />
</p>
<p>
<label for="password">Password #minPass-#maxPass Characters:</label><br/>
<input type="password" name="password" id="password" value="" />
</p>
<p>
<label for="confirmPassword">Confirm Password:</label><br/>
<input type="password" name="confirmPassword" id="confirmPassword" value="" />
</p>
<p>
<input type="submit" value="Submit" />
<input type="button" value="Cancel" onclick="javascript:location.href='Default.cshtml'" />
</p>
<p>
</p>
</form>
</div>
</body>
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>
I have generated an ASP.NET C# website with the visual studio 2013 wizard in order to get the authentication code and add it to my web app.
I have copied all files and everything looks fine except one thing...
the RegisterExternalLogin.cs file gives me an error in my web, but in the generated sample it works and I don't know why.
This is the error:
RegisterExternalLogin.aspx.cs(65,17,65,25): error CS0103: The name 'userName' does not exist in the current context
RegisterExternalLogin.aspx.cs(82,55,82,63): error CS0103: The name 'userName' does not exist in the current context
Here is the RegisterExternalLogin.aspx
<%# Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="RegisterExternalLogin.aspx.cs" Inherits="Account_RegisterExternalLogin" Async="true" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>Register with your <%: ProviderName %> account</h3>
<asp:PlaceHolder runat="server">
<div class="form-horizontal">
<h4>Association Form</h4>
<hr />
<asp:ValidationSummary runat="server" ShowModelStateErrors="true" CssClass="text-danger" />
<p class="text-info">
You've authenticated with <strong><%: ProviderName %></strong>. Please enter a user name below for the current site
and click the Log in button.
</p>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="userName" CssClass="col-md-2 control-label">User name</asp:Label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="userName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="userName"
Display="Dynamic" CssClass="text-danger" ErrorMessage="User name is required" />
<asp:ModelErrorMessage runat="server" ModelStateKey="UserName" CssClass="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" Text="Log in" CssClass="btn btn-default" OnClick="LogIn_Click" />
</div>
</div>
</div>
</asp:PlaceHolder>
</asp:Content>
and RegisterExternalLogin.aspx.cs
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Web;
using QuoteHD;
public partial class Account_RegisterExternalLogin : System.Web.UI.Page
{
protected string ProviderName
{
get { return (string)ViewState["ProviderName"] ?? String.Empty; }
private set { ViewState["ProviderName"] = value; }
}
protected string ProviderAccountKey
{
get { return (string)ViewState["ProviderAccountKey"] ?? String.Empty; }
private set { ViewState["ProviderAccountKey"] = value; }
}
protected void Page_Load()
{
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
Response.Redirect("~/Account/Login");
}
if (!IsPostBack)
{
var manager = new UserManager();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
userName.Text = loginInfo.DefaultUserName;
}
}
}
protected void LogIn_Click(object sender, EventArgs e)
{
CreateAndLoginUser();
}
private void CreateAndLoginUser()
{
if (!IsValid)
{
return;
}
var manager = new UserManager();
var user = new ApplicationUser() { UserName = userName.Text };
IdentityResult result = manager.Create(user);
if (result.Succeeded)
{
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
return;
}
result = manager.AddLogin(user.Id, loginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
return;
}
}
AddErrors(result);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
I solved the problem...
I had to wrap the entire codebehind in a namespace
QuoteHD.Account
{
}
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();
}
I am developing an ASP.Net 4.0 Web-Application and need to allow anonymous access to all of the pages, however I want to add Forms Authentication backed by Active Directory to display additional (privileged) content when the user logs in. I've scoured the Internet looking for examples of how to do this but have come up empty handed.
Here's what I have so far, but it doesn't seem to be working... When I click Login, it redirects to the main page, and I can use Cookies Manager+ to see that the cookie has been created, but it still displays the Anonymous template. I imagine I'm probably going about this all wrong... Is there anyways to fix what I have to make it work, or are there any examples of this type of authentication I work from?
LdapAuthentication.cs
public class LadpAuthentication
{
private string _path;
private string _filterAttribute;
public LadpAuthentication( string path )
{
_path = path;
}
public bool IsAuthenticated( string domain, string username, string pwd )
{
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry( _path, domainAndUsername, pwd);
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;
}
}
Login.aspx.cs
protected void Page_Load( object sender, EventArgs e )
{
if( null != Request["logout"] )
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
authCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Default.aspx");
return;
}
string username = Request["username"];
string password = Request["password"];
if( username != null && password != null )
{
LadpAuthentication ldap = new LadpAuthentication(ConfigurationManager.AppSettings["LogonServer"]);
if( ldap.IsAuthenticated("mydomain", username, password) )
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), false, null);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Default.aspx");
}
else
test.Text = "Invalid username and/or password.";
}
}
Login.aspx
<asp:Label ID="test" runat="server" />
<form action="<%= ResolveClientUrl("~/Login.aspx") %>" method="post">
<label for="username">Username</label><br />
<input type="text" id="username" name="username" /><br />
<label for="password">Password:</label><br />
<input type="password" id="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
Global.asax.cs
void Application_AuthenticateRequest( object sender, EventArgs e )
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if( null == authCookie )
return;
try {
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
GenericIdentity gid = new GenericIdentity(authTicket.Name, "LdapAuthentication");
Context.User = new GenericPrincipal(gid,null);
} catch( Exception ex ) {
}
}
Default.aspx
<asp:LoginView runat="server">
<AnonymousTemplate>
<a id="login-button" href="<%= ResolveClientUrl("~/Login.aspx") %>" class="ui-button">Login</a>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:LoginName runat="server" />
</LoggedInTemplate>
</asp:LoginView>