I need some help on retrieving a user with distinguishedName in asp.net mvc project. I have a search function that has 2 properties to load, "displayName" and "distinguishedName". Once I find, I return a view with a list containing these two parameters for each user found. Then I want to be able to click on a user and immediately show their information. So how do I load the information about the user once I only have these two parameters passed through?
Here is the function that initially searches:
public List<string> SearchUserByName(string name){
try{
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("distinguishedName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
if (sResult.Properties["distinguishedName"][0].Equals(null) ||
sResult.Properties["displayName"][0].Equals(null))
continue;
displayName.Add(sResult.Properties["distinguishedName"][0].ToString());
displayName.Add(sResult.Properties["displayName"][0].ToString());
}
}
ldapConnection.Close();
ldapConnection.Dispose();
search.Dispose();
return displayName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
Now my view:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Résultat de recherche d'utilisateurs</title>
</head>
<body>
<h2> Résultat de recherche d'utilisateurs</h2>
#{
var incLoop = 0;
var incArr = 0;
var list = (List<string>)ViewData["Names"];
var size = list.Count();
string[] objSID = new string[size];
foreach (var link in list)
{
if (incLoop % 2 == 0)
{
objSID[incArr] = link;
incArr++;
}
else
{
#link<br/>
}
incLoop++;
}
}
</body>
</html>
If you click on #link in the tag, you get the information, which is shown in the next view. I've also split my list to not show the distinguishedName in the search result view.
What I have done for now, is researching the Active Directory when you click on the link, but it seems like bad practice (searching twice for one result). Any ideas?
Thank you, hope it's clear
Related
I try to use alaSQL, but not working well for me.
My scenario is create a localstorage db when is not exists.
In this case i "init" the database.
It means i create all tables and insert some records.
Finally i select some data and send to the "display".
First run is everything ok,
but next time (when i click the browser's refresh button) i get an error message. "Error: Table does not exist: cities", but i created erlier.
Why can i get this message?
Please check my example:
<!DOCTYPE html>
<html>
<head>
<title>ALASQL</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/alasql"></script>
<script>
var db;
function log(msg) {
console.log("log: "+msg);
};
function initDB() {
log("initDB");
alasql.options.autocommit = true;
alasql("CREATE localStorage DATABASE IF NOT EXISTS lsdb");
alasql("ATTACH localStorage DATABASE lsdb AS db");
db = alasql.Database("db");
try {
db.exec("CREATE TABLE params (par string, val string)");
log("creDB");
db.exec("insert into params values ('db','1.0')");
db.exec("CREATE TABLE cities (id number, city string, pop number)");
db.exec("INSERT INTO cities VALUES (1,'Paris',2249975),(2,'Berlin',3517424),(3,'Madrid',3041579)");
}
catch (err) {
log(err);
};
};
function getData(sql) {
log("getData");
res = db.exec(sql);
return res;
};
function onLoad() {
initDB();
try {
res = getData("SELECT * FROM cities WHERE pop > 3500000 ORDER BY pop DESC");
document.getElementById("res").textContent = JSON.stringify(res, null, 2);
}
catch (err) {
document.getElementById("res").textContent = err;
};
};
</script>
</head>
<body onload="onLoad()">
<xmp id="res"></xmp>
</body>
</html>
Thanks for any advice.
Joe
This is for a school project, and I don't really understand exactly what I'm supposed to do, so I'll explain what the teacher told me and what I did so far, hope you guys can help.
To examine the success of a program, the teacher wants to manually add a number to the url of the page.
I need to take that number, extract it from the url, then implant it in a method so that it will decrypt a message with the same ID number (I have no idea how he intends to do it or activate said method).
Here is what I wrote:
In the DataModel:
public static void GetMessage (int? MesNum, out string MesSuc)
{
SqlConnection cnctn = new SqlConnection(cnctnstrng);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnctn;
cmd.CommandText = "GetMessage";
cmd.Parameters.Add("#LineNum", SqlDbType.Int);
SqlDataReader rd;
try
{
cnctn.Open();
cmd.Parameters["#LineNum"].Value = MesNum;
rd = cmd.ExecuteReader();
byte[] Message = (byte[])rd["MessageText"];
if (Message != null)
{
MesSuc = chat.Models.DomainModels.Security.DecryptStringFromBytes(Message);
}
else
{
MesSuc = "Unable to decrypt Message";
}
}
catch
{
MesSuc = "Unable to decrypt Message";
}
finally
{
cnctn.Close();
}
}
In the Controller:
public ActionResult singlmsgdecrptn()
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(*?*, out MesSuc);
return View(MesSuc);
}
The ? is where the number is supposed to come in.
In the View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>singlmsgdecrptn</title>
</head>
<body>
<div>
#ViewBag.MesSuc
</div>
</body>
</html>
The default routing for MVC takes and ID optional parameter. Check the RouteConfig.cs in the App_Start folder.
So you should just be able to add it as a parameter to your controllers action result.
public ActionResult singlmsgdecrptn(int? id)
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(id, out MesSuc);
return View(MesSuc);
}
Also, not sure why you're using a nullable int here, but I followed suit. Hope this helps, good luck.
Can anyone help me to create a cookie to save the users current URL with location.href when they click a button, in effect a "save progress" button. Then have another load button to take the user to what had been saved in this cookie,
<!DOCTYPE html>
<html>
<head>
<script>
function newDoc()
{
window.location.assign(location.href)
}
</script>
</head>
<body>
<input type="button" value="Load Progress" onclick="newDoc()">
</body>
</html>
is this possible?
Many thanks.
You can create cookie using javascript.
You can use following function to make it easy.
You can read, right, delete cookies by using following functions.
/***create cookie using createCookie later you can read it eg. var url = readCookie("currenturl");***/
function newDoc(){ createCookie("currenturl", document.URL, 1);
}
function createCookie(name,value,days) { if (days) { var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) { createCookie(name,"",-1);
}
I am following the sample code/tutorial for ASP.NET MVC and JSONP blog post: http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
I have taken the code sample and have modified it for my own consumption.
When I hit the page, it fires off my controller's action but the $.getJSON(call, function (rsp).. is not firing at all.
Controller action
[JsonpFilter]
public JsonpResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
HTML Page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var url = "http://localhost/MySite.ContentDelivery/MyController/GetMyObjects/?";
function getObjects() {
//
// build the URL
//
debugger;
var call = url + "id=48&jsoncallback=?";
//
// make the ajax call
//
$.getJSON(call, function (rsp) {
debugger;
alert(rsp);
if (rsp.stat != "ok") {
//
// something went wrong!
//
$("#myDiv").append(
"<label style=\"background-color:red;color:white;padding: 25px;\">Whoops! It didn't work!" +
" This is embarrassing! Here's what the system had to " +
" say about this - " + rsp.message + "</label>");
}
else {
//
// build the html
//
var html = "";
$.each(rsp.list.myObject, function () {
var obj = this;
html += "<span" + obj.Name + "</span> <br />";
});
//
// append this to the div
//
$("#myDiv").append(html);
}
});
}
//
// get the offers
//
$(document).ready(function() {
alert('go..');
$(getOobjects);
});
</script>
<div id="myDiv"></div>
</body>
</html>
tl;dr why is my getJson() not firing while my getObjects() fires and executes the MVC controller action.
Replace:
var call = url + "id=48&jsoncallback=?";
with:
var call = url + "id=48&callback=?";
The custom JsonpResult you are using relies on a query string parameter called callback and not jsoncallback:
Callback = context.HttpContext.Request.QueryString["callback"];
Also you have decorated your controller action with a [JsonpFilter] attribute and returning a JsonpResult. As explained in the article you must have read you should choose one:
[JsonpFilter]
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return Json(list, JsonRequestBehavior.AllowGet);
}
or the other:
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
but do not mix the two.
All , Say you have a code in a View like this.
<img src='#Url.Action("GetCaptchaImg")' alt='' />
and of course there is an Action named GetCaptchaImg in the controller which return a FileContentResult to View.
After open this view in FireFox. I found the Html code is
<img alt="" src="/Controllername/GetCaptchaImg" />
the src is not the real physical path . So My question is what is the real physical path of this img, How can I change the image by Ajax call to an Action? Hope you can help me . thanks.
You can make an ajax call to the actionresult and from that return the name of the image and onsuccess of your ajax call change the image
Alternatively you can do this thing, which i've implemented in my project
Make your HTML form like this
#using (Html.BeginForm("ActionResult", "Controller", FormMethod.Post, new { #id = "ImgForm", #enctype = "multipart/form-data", name = "ImgForm", target = "UploadTarget" }))
{
}
Make an iframe as target of your form
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
left: -999em; top: -999em;"></iframe>
Your upload control
Then upload the Image and Show it on your form
function UploadImage() {
$("#ImgForm").submit(); //form id
}
function UploadImage_Complete() {
try {
//Check to see if this is the first load of the iFrame
if (isFirstLoad == true) {
isFirstLoad = false;
return;
}
//Reset the image form so the file won't get uploaded again
document.getElementById("ImgForm").reset();
//Grab the content of the textarea we named jsonResult . This shold be loaded into
//the hidden iFrame.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
if (newImg.IsValid) {
document.getElementById("dp").src = newImg.ImagePath;
document.getElementById('profile-pic').src = newImg.ThumbnailPath;
document.getElementById("change").style.display = "block";
}
// If there was an error, display it to the user
if (newImg.IsValid == false) {
alert(newImg.Message);
return;
}
}
catch (e) {
}
}
Your Action will look like this
public WrappedJsonResult ChangeImage(HttpPostedFileBase file)
{
}
and your WrappedJsonResult class will look likes
public class WrappedJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea></body></html>");
context.HttpContext.Response.ContentType = "text/html";
}
}