HTML/JS/ASP: Check If User Exists - SELECT COUNT(*) - c#

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>

Related

c# save image attachment from cshtml input tag in VS Project folder

I've got a CSHTML form in Visual Studio 2017 looking to save attachments in a folder called "YourRightsFiles" in the main project folder and store details in a database for a blog/message board for the website the form is related to. Based off of the code shown under the section "Uploading Image" in the following Microsoft tutorial - https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images - I wrote the following code for the form:
<div id="creds" style="margin-top:50px;float:right;visibility:hidden;height:0">
<form method="post" enctype="multipart/form-data">
<span style="font-weight:bold">First Name: </span><br> <input type="text" name="first name" required><br><br>
<span style="font-weight:bold">Last Name: </span><br> <input type="text" name="last name" required><br><br>
<span style="font-weight:bold">Job Title: </span><br> <input type="text" name="job title" required><br><br>
<span style="font-weight:bold">Subject: </span><br> <input type="text" name="subject" cols="30" required><br><br>
<div id="attachments">
<span style="font-weight:bold">Attachments (images and videos only): </span><br> <input type="file" accept="video/*, image/*" name="attachment0" cols="30"><br><br>
<input onclick="return add_attachment()" readonly value="Add Another Attachment" style="width:auto;background-color:lightgrey;border-color:black;border-width:1px;margin-bottom:30px;padding:3px;border-radius:6px;"><br><br>
<script>
function add_attachment() {
var count = 0;
var input_tags = document.getElementsByTagName("input");
for (var i = 0; i < input_tags.length; i++) {
if (input_tags[i].name.search("attachment") != null) {
count = count + 1;
}
}
var attach_html = "<input type=\"file\" accept=\"video/*, image/*\" name=\"attachment" + count.toString() + "\" cols=\"30\"><br><br>";
document.getElementById("attachments").innerHTML = document.getElementById("attachments").innerHTML + attach_html;
}
</script>
</div>
<span style="font-weight:bold">Message: </span><br> <textarea type="text" name="message" rows="4" cols="30" required></textarea><br><br>
<input type="submit" name="Submit" readonly value="Submit Message" style="width:auto;background-color:lightgrey;border-color:black;border-width:1px;margin-bottom:30px;padding:3px;border-radius:6px;">
</form>
</div>
#if (IsPost)
{
var connectionString = "MY CONNECTION STRING";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
if (Request.Form["Submit"] == "Submit Message")
{
var firstName = Request.Form["first name"];
var lastName = Request.Form["last name"];
var jobTitle = Request.Form["job title"];
var subject = Request.Form["subject"];
var message = Request.Form["message"];
var all_fields = Request.Form.AllKeys;
System.Diagnostics.Debug.Write(all_fields);
var insertQuery = "insert into YourRights values(#0,#1,#2,#3,#4)";
foreach(var field in all_fields) {
if (field.ToString().Contains("attachment")) {
WebImage photo = WebImage.GetImageFromRequest(field.ToString());
var newFileName = "";
var imagePath = "";
if (photo != null)
{
newFileName = Guid.NewGuid().ToString() + "_" +
Path.GetFileName(photo.FileName);
imagePath = #"YourRightsFiles\" + newFileName;
photo.Save(#"~\" + imagePath);
}
}
}
db.Execute(insertQuery, firstName, lastName, subject, message, jobTitle);
}
db.Close();
}
The code does not seem to save the file within "YourRightsFiles". I also tried just saving inside the main project folder with:
imagePath = #"\" + newFileName;
But that didn't work either. All the database insert related code is working, so there's no issue with form submission, and I am not getting any errors at all during demoing, not even in the console. I'm not sure what I'm doing wrong here

How do I refer the same button to different pages?

I am trying to refer the button order now to each different product I have in my table. What is the best possible way to deal with this kind of situation? At this moment all order now buttons refer to the first record of Product each time. But I am trying to get the data of each different column to the corresponding order now button. What is the best possible way to do this? Here you can find my corresponding Database Tables
Consoller:
public ActionResult PurchaseProduct()
{
if (Session["name"] == null)
{
return RedirectToAction("Index", "Customer");
}
var fetch = db.Products.FirstOrDefault();
Session["pid"] = fetch.P_id;
Session["pname"] = fetch.P_Name;
return View(db.Products.ToList());
}
[HttpPost]
public ActionResult Order(Product pt, Customer cr, int Quantity)
{
//available amount before order
Session["p_name"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_Name).SingleOrDefault();
Session["available_quantity"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_amount).SingleOrDefault();
//amount needed
Session["needed_quantity"] = Quantity;
int a = Convert.ToInt32(Session["needed_quantity"]);
int b = Convert.ToInt32(Session["available_quantity"]);
if ( a <= b )
{
ViewBag.Message = "Order placed.";
//quantity after the order has been placed
int final_quantity = b - a;
//total price (amount needed*price)
Session["total_price"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_price).SingleOrDefault();
int total_price = Convert.ToInt32(Session["total_price"]) * a;
//amount after the order
Session["final_quantity"] = db.Products.Where(x => x.P_id == pt.P_id).Update(x => new Product { P_amount = final_quantity });
Session["c_id"] = db.Customers.Where(x => x.C_Id == cr.C_Id).Select(x => x.C_Id).SingleOrDefault();
int c_id = Convert.ToInt32(Session["c_id"]);
Session["p_id"]= db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_id).SingleOrDefault();
int p_id = Convert.ToInt32(Session["p_id"]);
//adding record to table 'order'
string p_name = Session["p_name"].ToString();
Session["Add_Order"] = db.Orders.Add(new Order {O_name = p_name, O_Price = total_price
, O_amount = a ,C_id = c_id, P_id = p_id});
db.SaveChanges();
}
else
{
ViewBag.Message = "Order can't be placed, product amount is " + b.ToString();
}
return View();
}
Products overview page
#model IEnumerable<IMS.Models.Product>
#{
foreach (var item in Model)
{
<tr>
<td>#item.P_Name</td>
<td>#item.P_size</td>
<td>#item.P_price</td>
<td><img src="/images/#item.P_Image" width="200" height="200" /></td>
<td>Order Now</td>
</tr>
}
}
</table>
</div>
Page of each individual product after clicking order now
<div class="form-group">
#{
using (Html.BeginForm())
{
<p style="color:red;">#ViewBag.Message</p>
<div class="form-group">
<label>Product name: </label>
<input type="text" name="pname" id="pname" value="#Session["pname"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Customer id: </label>
<input type="text" name="c_id" id="c_id" value="#Session["id"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Product id: </label>
<input type="text" name="p_id" id="p_id" value="#Session["pid"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Amount: </label>
<label>Available amount: #Session["available_quantity"] </label>
<input type="text" name="Quantity" class="form-control" />
</div>
<input type="submit" value="Submit" name="submit" class="btn btn-success" />

Have a SQL statement that is executing twice on IIS but once in Visual Studio, why?

I have a SQL statement that executes twice when posted to the IIS, but it only executes once when in Visual Studio; I am not sure why it works in one but not the other.
Some other information I have a wildcard SSL that is attached to the server, and I only see one post request in the network Log. The actual code ( with some changes to protect the identity of the site. )
public void AddMenuLink(MenuLinks m)
{
string sql = "INSERT INTO MY_TABLE (Href, Target, IsF, Name, MenuGroup)" +
" VALUES (#Href, #Target, #IsF, #Name, #MenuGroup)";
ConnHelper misc = new ConnHelper();
SqlConnection Conn = null;
SqlCommand sqlCmd = null;
try
{
Conn = misc.GetDataConnection();
sqlCmd = new SqlCommand(sql, Conn);
sqlCmd.Parameters.Add("#Href", SqlDbType.VarChar).Value = m.Href;
sqlCmd.Parameters.Add("#Target", SqlDbType.VarChar).Value = m.Target;
sqlCmd.Parameters.Add("#Iswolf", SqlDbType.VarChar).Value = m.IsF;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = m.Name;
sqlCmd.Parameters.Add("#MenuGroup", SqlDbType.VarChar).Value = m.MenuGroup;
sqlCmd.ExecuteScalar();
}
catch (Exception ex)
{
}
finally
{
Conn.Close();
}
}
The code that calls it is:
if (Request.Form["Add"] == "Add")
{
MenuLinks M = new MenuLinks();
// Check if upload
int uploadFlag = 0;
if (file != null && file.ContentLength > 0)
{
uploadFlag = 1;
var fileName = Path.GetFileName(file.FileName);
string fileExt = Path.GetExtension(file.FileName);
try
{
//Original and used for viewing
string pathing = FILE_SHARE + "\\";
System.IO.Directory.CreateDirectory(pathing);
var path = Path.Combine(pathing, file.FileName);
file.SaveAs(Path.Combine(pathing, fileName));
//Backup
string pathing2 = BACKUP_SHARE + "\\";
System.IO.Directory.CreateDirectory(pathing2);
var path2 = Path.Combine(pathing2, file.FileName);
file.SaveAs(Path.Combine(pathing2, fileName));
//save path in database get ID.
M.Href = "http://MYSITE/Content/" + HttpUtility.UrlEncode(file.FileName);
}
catch (Exception ex)
{
ViewBag.error = ex.ToString();
ViewBag.error += " Saving File FAILED IN ADD";
uploadFlag = 2;
}
}
if(uploadFlag == 0)
{
//if there is no upload href get the one from link
M.Href = Request.Form["Href"];
}
M.Target = Request.Form["Target"];
M.Name = Request.Form["Name"];
M.IsF = Request.Form["IsF"];
M.MenuGroup = Request.Form["MenuGroup"];
// filter uploads
if (uploadFlag != 2)
{
DB.AddMenuLink(M);
}
}
There are three forms in the view, add/edit/delete.
In the view I have this (Add section only):
<form action="" method="post" enctype="multipart/form-data">
<p>File Upload</p>
<input type="file" name="file" id="file" /><br />
<p>Link (leave blank if uploading file)</p>
<input type="text" name="Href" id="href" /><br />
<p>Target</p>
<select name="Target" id="Target">
<option value="_self">In frame</option>
<option value="_blank">New window</option>
</select>
<br />
<p>Name</p>
<input type="text" name="Name" id="Name" /><br />
<p>Tagged For:</p>
<input type="radio" name="IsF" value="Both" checked />Both<br />
<input type="radio" name="IsF" value="0" />One<br />
<input type="radio" name="IsF" value="1" />The Other<br />
<br />
<p>Menu Group</p>
<select name="MenuGroup" id="MenuGroup">
#{
x.MenuGroup = "";
for (int i = 0; i < 10; i++)
{
x.getMenuGroup(i);
if (x.MenuGroup != "")
{
#Html.Raw("<option value='" + x.MenuGroup + "'>" + x.MenuGroup + "</option>")
x.MenuGroup = "";
}
}
}
</select>
<br />
<input type="submit" value="Add" name="Add" />
</form>
Any ideas?
This turned out to be a clean/rebuild/republish issue with IIS.

Forgot Password MVC 4

In my application I am trying to get a forgot password to work. I am trying to send an email to the user when he/she inputs his or her user name, sends them and email, they click on that link, and are brought back into the website and changes their password. Only thing is that my linq query is wrong an is not checking to see if the username exists in the database. Is this the right way to go by getting a forget password to work?
Here is my code
Controller
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgetPassword()
{
return View();
}
// Post: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ForgetPassword(ForgetPasswordModel model, string UserName)
{
string emailAddress = (from i in db.UserProfiles
where i.UserName.Equals(model.Username)
select i.Email).Single();
if (!string.IsNullOrEmpty(emailAddress))
{
string confirmationToken =
WebSecurity.GeneratePasswordResetToken(model.Username);
dynamic email = new Email("ChngPasswordEmail");
email.To = emailAddress;
email.UserName = model.Username;
email.ConfirmationToken = confirmationToken;
email.Send();
return RedirectToAction("ResetPwStepTwo");
}
return RedirectToAction("InvalidUserName");
}
Model
public class ForgetPasswordModel
{
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
}
View
#model MyFestival.Models.UserProfile
#{
ViewBag.Title = "Forgot Password";
}
<hr />
<div class="form-group">
<h3 class="panel-title">Did you forget your password?</h3>
</div>
#using (Html.BeginForm())
{
<div class="">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, null, new { #style = "color:red;" })
<hr />
<label>To reset your password, input your email address and press the Reset Password button.</label>
<br/>
<div class="form-group" >
<div class="col-md-12" >
<div class="input-group">
<span class="input-group-addon" ><i class="glyphicon glyphicon-user" ></i ></span >
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #placeholder = "Username" })
</div >
#Html.ValidationMessageFor(m => m.UserName, null, new { #style = "color:red;" })
</div>
</div>
<br/>
<br/>
<div class="form-group" >
<div class="col-md-offset-2 col-md-10" >
<input type="submit" class="btn btn-default" value="Reset Password"/ >
#Html.ActionLink("Back to Login", "Login", null, new { #class = "btn btn-info" })
</div >
</div>
</div>
}
I've just spotted that you have both ForgetPasswordModel model and string username as arguments of your controller action and later you use Username property of your model. I assume that Model Binder just initializes the stirng username instead of ForgegPasswordModel. Could you try removing stirng username - the second parameter of ForgetPassword action?
You can create your own GUID and send it with email to user.
When user click on email link check Guid and update new password of user.
Here is the sample code
Create a view to enter forgot password email
#{
ViewBag.Title = "Forgot Password";
}
<h2>Forgot Password</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<hr />
<div class="text-success">
#ViewBag.Message
</div>
<div class="form-group">
Please enter your registered email address below to receive an email containing a link, to reset your password.
</div>
<div class="form-group">
<label class="control-label col-md-2">Email Address</label>
#Html.TextBox("EmailID", "", new { #class = "form-control" })
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</div>
</div>
}
Then in your Controller get Email id from user, check if email exists and create new GUID, save it in database, send email to user.
[HttpPost]
public ActionResult ForgotPassword(string EmailID)
{
string resetCode = Guid.NewGuid().ToString();
var verifyUrl = "/Account/ResetPassword/" + resetCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
//get user details from database.
using (var context = new LoginRegistrationInMVCEntities())
{
var getUser = (from s in context.RegisterUsers where s.Email == EmailID select s).FirstOrDefault();
if (getUser != null)
{
getUser.ResetPasswordCode = resetCode;
//This line I have added here to avoid confirm password not match issue , as we had added a confirm password property
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
var subject = "Password Reset Request";
var body = "Hi " + getUser.FirstName + ", <br/> You recently requested to reset your password for your account. Click the link below to reset it. " +
" <br/><br/><a href='" + link + "'>" + link + "</a> <br/><br/>" +
"If you did not request a password reset, please ignore this email or reply to let us know.<br/><br/> Thank you";
SendEmail(getUser.Email, body, subject);
ViewBag.Message = "Reset password link has been sent to your email id.";
}
else
{
ViewBag.Message = "User doesn't exists.";
return View();
}
}
return View();
}
private void SendEmail(string emailAddress, string body, string subject)
{
using (MailMessage mm = new MailMessage("youremail#gmail.com", emailAddress))
{
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("youremail#gmail.com", "YourPassword");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
Now, when user click on the email and enter new password, check Guid with what we have saved in database and update password if guid matches.
Check for more info:
Forgot password functionality in ASP.NET MVC (Reset password by Email)

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