How to get company's Active Directory data to display on a razor view(webgrid)? - asp.net-mvc

I need to build a simple asp.net mvc web apps to display the detailed data from Active Directory and show it in a webgrid feature , is that possible? I appreciate if anybody can provide any good examples, thanks in advance.
I found this example: http://www.dotnetcodesg.com/Article/UploadFile/2/223/Get%20List%20of%20Active%20Directory%20Users%20in%20ASP.NET%20Csharp.aspx
but when I execute the codes, the program stopped on this line of code:
MembershipUser myUser = Membership.GetAllUsers()[searchResult...
I got error : "Unable to connect to SQL Server database. "
The codes stopped on :
MembershipUser myUser = Membership.GetAllUsers()[searchResult.Properties["sAMAccountName"][0].ToString()];
It seems I need to connect Membership database, do I have to connect membership database in order to get all employee data?
I only want to get all employee information such as : name, ID, email, phone , ,, and display them in a view (better in webgrid or other format easy to read).
I tried these codes :
DirectoryEntry myLdapConnection = new DirectoryEntry(LDAP://company.domin);
// DirectorySearcher search = new DirectorySearcher(myLdapConnection) { Filter = ("(objectClass=user)") };
DirectorySearcher search = new DirectorySearcher();
// search.CacheResults = true;
search.SearchRoot = myLdapConnection;
search.SearchScope = SearchScope.Subtree;
SearchResultCollection allResults = search.FindAll();
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("sAMAccountName");
.....
Basically, I added the data to a datatable and show them in a razor view, I got the data and displayed them on the razor view, but the data is not complete data, some employee information is missing, can anybody tell me what is wrong with my codes for the missing data? there must be something wrong with the codes which get the partial data. What I want to get is complete data in my company's Active Directory which includes all employee's name and group name, etc.

The database error message suggests that your site is configured for Forms Authentication. You need to set the authentication mode to Windows in your web.config file to use Active directory.
<system.web>
<authentication mode="Windows" />
</system.web>

Related

Working with Entity framework with Sitefinity and Portal Connector and Dynamic CRM

I'm working on a project that contains Dynamics CRM and Portal Connector which built upon Sitefinity.
There is a way to retrieve data inside Portal Connector from Dynamic CRM called Saved Query and this way generate a URL for you to retrieve data by HTTP request in front-end but I don't want to access it by the front end I want to access the Dynamics CRM by Backened, specifically by Entity framework, is it possible to connect to Dynamic CRM by Entity framework and retrieve the data by C# then send it to View?
My apologies for not coming across your post sooner.
A better way is to use the CRM connection provided by the Portal Connector. It essentially wraps the CRM SDK so calls you want make to the SDK can be made here and it uses the CRM connection configured in the site.
https://www.crmportalconnector.com/developer-network/documentation/developing-for-tpc/Dynamics-CRM-Connection-API
// Required usings
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using pavliks.PortalConnector.Crm.Connection;
// The Code
// Create an instance of the connection manager
CrmConnectionManager manager = new CrmConnectionManager();
// Use the Connection property of the manager to access the
// configured CRM connection and create a new account
Guid newId = manager.Connection.Create(new Entity("account")
{
Attributes = new AttributeCollection()
{
{"name", "My Account Name"}
}
});
// Create Query Expression
QueryExpression query = new QueryExpression("account")
{
ColumnSet = new ColumnSet(true),
};
// Use manager to query CRM
EntityCollection entities = manager.Connection.RetrieveMultiple(query);
All the required assemblies are already in the Sitefinity site bin folder as they come with the Portal Connector assemblies and are copied to that location with the Portal Connector during installation. If your code is in another project, either reference the assemblies in the Sitefinity project or add them from the Portal Connector deploy package to your project.
I know it's a bit late but I hope it helps you in your next portal project.
let me answer my question, in case anyone wants to do a similar thing in the future :
1- first thing connect to Dynamic CRM is not related to Portal Connector, so the area that you should search in is Dynamic CRM.
2- To connect to Dynamic CRM you should follow the below steps :
2.1- install this package "Microsoft.CrmSdk.XrmTooling.CoreAssembly"
2.2- find what is your connection string.
2.3 use below code
var service=new CrmServiceClient("AuthType=Office365;Url=https://ititisdf.crm4.dynamics.com;Password=1234" )/*put your connection string instead*/
3- Some example of you could create or retrieved data
service.Create(new Entity("account"){["name]="Test connection"}); // add record
// retrive data
//1- query expression
//var query= new QueryExpression().Criteria. <===== from here you can add filteration ... and so on
//2- fetch xml expression
//var query=new FetchExpression(#"fetch xml value"); // you need to use XrmToolBox to generate your fetchXml
//3- var query=new QueryByAttribute("account");
// query.AddAttributeValue("name","Test1");
var entities=service.RetrieveMultiple(query).Entities;
foreach(var entity in entities)
{
entity["name"];
}
var organization=new OrganizationServiceContext(service);
// below code is under a concept called late-bound
var result=(from account in organization.CreateQuery("account")
join contact in organization.CreateQuery("contact")
on account["primarcontactid"] equals contact["contactid"]
where account["gendercode"] == "test" AND account["industrycode"]=1
select new {
Name=account["name"],
ContactName=contact["fullname"]
}).ToList();
// to implement Early bound
1- go to XrmToolBox ==> About ==> Plugin Store ==> Early Bound Generator==>Early Bound Generator Page will opened choose Entity to skip and choose which entity to want to include and which want to exclude
===> choose the path of generated .cs class that will represent you Entity in your project ===> press on Create Entities ===> now copy the generated file .
Now you have something like Entity framework :
Just use Entity name as a normal class :
var account = new Account{Name="Ahmed"};
and instead of this :
organization.CreateQuery("account")
use
organization.CreateQuery<yourEntityName>()
Actually, I got all of this information from youtube serious related to Dynamic, and here is the link
note: this serious in the Arabic language for this reason I summarised the steps in this answer to make it helpful for all.

Reading from a textfile in MVC

I have recently tried to read from a textfile and populate the db and then display the populated data onto my MVC application. Reason for all of this is because I want my desktop application to be able to pass data to my MVC application and save it into my MVC db.
This is what I have:
public ActionResult Index([Bind(Include = "location_id,location_name")] Location location)
{
string full_path = Request.MapPath("~/App_Data/TestText.txt");
if (System.IO.File.Exists(full_path))
{
if (new System.IO.FileInfo(full_path).Length > 0)
{
string[] text_file = System.IO.File.ReadAllLines(HostingEnvironment.MapPath(#"~/App_Data/TestText.txt"));
foreach (string record in text_file)
{
string[] record_cell = record.Split('~');
location.location_name = record_cell[1];
db.Locations.Add(location);
db.SaveChanges();
}
System.IO.File.WriteAllText(HostingEnvironment.MapPath(#"~/App_Data/TestText.txt"), "");
}
}
ViewBag.location_id = new SelectList(db.Locations, "location_id", "location_name");
return View();
}
I have the code above which is placed in my home controller so that everytime the page loads it looks into the textfile for new data and stores it in the db, and at the same time returns a view to display the index page.
Everything works fine on localhost however when hosted I am getting the following error:
I have my textfile located in App_Data, I however feel as though placing the code in the controller under Index is causing this. Can you please help me out to show me where to place the code so that on startup of the website it checks for updated datab in the textfile.
Update:
I have found the error causing the site not to load. Somehow the following line of code from the view, which is populating a dropdown list with data from the db is not working:
#Html.DropDownList("location_id", null, htmlAttributes: new { #class = "form-control"})
Any solutions on fixing this?

where is password must have at least one lowercase ['a'-'z'] message in mvc 5

in registration form when user enter just numeric character it shows "password must have at least one lowercase ['a'-'z']", I need to translate it in my native language, where can I find this message?
Firstly, install the identity localized package in Package Manager Console:
Install-Package Microsoft.AspNet.Identity.Core.tr
(.tr or your localization code .it, .es, .de, .fr etc.)
Then set culture in web.config:
<system.web>
<globalization culture="tr-TR" uiCulture="tr"/>
</system.web>
Now, your identity messages will be automatically set according to your language.
These messages are provided by framework, not from your model, so you cannot use data annotations for this. But you can solve the problem in another way:
Step 1: Create resource file for your controller or use shared resource. For example, if your controller is /Controllers/AccountController.cs, then resource file should be Controllers.AccountController.de.resx in your resources folder (depending on configuration; instead of de use your locale code).
Step 2: Write translations for strings: PasswordRequiresLower, PasswordRequiresNonAlphanumeric, PasswordRequiresUpper. These strings are codes of identity errors. You can see them during debug of registration process after failed registration.
Step 3: Do not forget to use localizer in your controller
using Microsoft.Extensions.Localization;
public class AccountController : Controller
{
private readonly IStringLocalizer<AccountController> _localizer;
public AccountController(IStringLocalizer<AccountController> localizer)
{
_localizer = localizer;
}
// Another code of AccountController class.
}
Step 4: Add translated descriptions for errors in registration action
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// User account created.
return RedirectToAction("Index", "Home");
}
// User account creation failed.
foreach (var error in result.Errors)
{
ModelState.AddModelError(error.Code, _localizer[error.Code]);
}

How to check whether username already exists using ajax in asp.net?

I am working on an application which has a registration form and I have to display to the user whether the username exists or not.
I am using asp.net mvc3 and planned to use AJAX to achieve this.
I have a form
<tr>
<td>User Name*</td>
<td><input id="UserName" name="UserName" type="text" onblur="check(this.value);"/></td>
<td id= "UName"></td>
</tr>
which calls a .js file that has the folling contents
function check(User) {
...
var url = "/UserNameCheck/Index";
url += "?User=" + User;
xmlHttp.onreadystatechange = state_Change;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function state_Change() {
if (xmlhttp.readyState == 4) {// 4 = "Response loaded"
if (xmlhttp.status == 200) {// 200 = Response Error Free
document.getElementById("UName").innerHTML = xmlHttp.responseText
}
else {
alert("Problem retrieving XML data");
}
}
}
I alerted the username and I am getting the correct value that i had entered. Now, the URL is /UserNameCheck/Index where UserNameCheck is a controller and Index is a method in that.
The controller has this code.
public ActionResult Index(string User)
{
string UserName;
try
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
UserName = Request.QueryString["User"];
ConnectionPackage.ConnectionClass cc = new ConnectionPackage.ConnectionClass();
conn = cc.con;
string sql = "Select UserName FROM UserDetails where UserName = '" + UserName + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
object p = cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
string u = (string)p;
if (u.Length==0 || u.Equals("NULL") || u.Equals("null")||u.Equals("Null"))
{
return View();
}
return null;
}
catch (Exception ex){
}
and the view has
String buffer = " <table><tr><td id = 'UName' >" This user name already exists. Please select some other unser name.
buffer = buffer + "</td></tr></table>";
response.getWriter().println(buffer);
I also tried writing
Response.Clear();
Response.Write("UserName already exists. Please select another UserName");
Response.End();
instead of returning View.
But in both the cases, I didn't get any message that the username exists even though I typed a user name that was already present in the database.
The connection string work for inserting into the database, so I dont think there is a problem with that. Is there a problem with the URL that I have mentioned in the js file? Or is my entire approach wrong?
I am basically from java background so dont know much about asp.net. Please do help.
Thank you very much in advance.
I followed what was given in MSDN article How to: Implement Remote Validation in ASP.NET MVC
jQuery in Action is the most popular jQuery book
You're doing alright but you could make this a whole lot easier on yourself. If you are usinng MVC3 with Razor, your app already has jQuery installed.
Use the $.ajax() method to perform the calls to your controller action that checks names...
Bind the $.ajax() call "unobtrusively" which means instead of on your HTML control, bind the event to your control from the jquery/javascript.
Second, if you want a little fancy performance, you can bind it via the live() jquery function or keyup event, so that as you are typing the ajax call is made and you find out realtime.
Ultimately you will end up with a lot less javascript, and your JS stuff will be cleanly separated from your markup.
As far as your controller action is going, it looks fine for playing around and learning, but you'd want to think about either (a) putting your SQL statement as a stored procedure on the db server and calling that, or (b) writing a repository pattern class and then using LINQ to do your query work after the DB fetch.
Another possibility would be to use Entity Framework 4.1 via NuGet to eliminate both needs. It can have a bit of a learning curve, but there's lots of good stuff out there and your example would be fairly simple to get started with.
Let me know if you have any specific concerns with your code and I can provide a more detailed answer.

ASP.NET MVC Facebook

I am trying to do a seemingly simple thing, but having trouble accomplishing it. I am trying to automate the posting on my Facebook wall. Basically I have a ASP.NET MVC website that I post updates on, and I want to automatically submit the post to my wall.
I see a lot of stuff on FB Connect and getting data, I just want to post.
Thanks for any help or guidance.
UPDATE: Just trying to resurrect and be a little more clear in my description as I am not getting anywhere.
I have a page that I want with a text box and a button. When I submit the form I want the message to post to my Facebook wall. I thought it was Facebook Connect, but I am getting no where as to how to automatically authenticate myself and post to my wall.
I would like to use C# rather than JavaScript.
private const string ApplicationKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private const string SecretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
private Facebook.Rest.Api _facebookAPI;
private Facebook.Session.ConnectSession _connectSession;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
_connectSession = new Facebook.Session.ConnectSession(ApplicationKey, SecretKey);
if (_connectSession.IsConnected())
{
_facebookAPI = new Facebook.Rest.Api(_connectSession);
string response = _facebookAPI.Stream.Publish("This is a generated test");
}
return View();
}
}
The IsConnected() is returning false.
Any help is appreciated.
This code was right, the problem was that I had not added my application to my profile. Dumb miss, but my thought is that the whole thing is poorly documented. I have another issue with offline access, but that is for a different post.
string apiKey = "XXXXXXXXX";
string apiSecret = "XXXXXXXXXXXX";
Facebook.Session.ConnectSession._connectSession = new Facebook.Session.ConnectSession(apiKey, apiSecret);
if (_connectSession.IsConnected)
{
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
string response = api.Stream.Publish("Test", null, null, null, api.Users.Session.UserId);
}
It could be that you tested your Website on your localhost. The Facebook Cookie is not written out, when you test your Website on localhost. See this link http://forum.developers.facebook.net/viewtopic.php?pid=247332
This might solve your problem:
Add "127.0.0.1 localhost.local" to your file
Update your FB application Connect settings to use "http://localhost.local/" URL and "localhost.local" domain.
Create an IIS Web site on port 80 with the name "localhost.local". I had to stop my default web site, which is also on port 80
Update my Visual Studio 2010 web application to use IIS with the "http://localhost.local/" url.
To see cookies, make sure to install FireCookies, along with FireBug.

Resources