LDAP The server is not operational - active-directory

I have this LDAP problem where the server is not operational.
Here's my code
var directoryEntry = new DirectoryEntry();
directoryEntry.Path = "LDAP://";
directoryEntry.Username = myusername;
directoryEntry.Password = mypass;
DirectorySearcher objDirSearch = new DirectorySearcher(directoryEntry);
SearchResult objSearchResult;
if (objDirSearch != null)
{
objDirSearch.Filter = String.Format("(SAMAccountName={0})", "abcd");
MessageBox.Show(directoryEntry.Username);
objSearchResult = objDirSearch.FindOne();
}
Please help me I'm stuck and frustrated

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "abcd");
if(user != null)
{
// do something here....
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!

Related

OData V4 to access secured URI

I need to develolp a WPF application that use the OData service of a Project Online Server. When I try to reference the OData service with ODataLib V4, it doesn't work because the OData service is secure.
Anyone know a workaround for this problem ?
I found the solution.
Extract the metadata of Project Online in xml file (https://[your pwa site]/_api/ProjectData/$metadata)
Change the extension of the xml file to .edmx
Execute DataSvcUtil in your Framework directory (DataSvcUtil /in:edmxfile.edmx /out:csfile.cs /language:CSharp)
Add the csfile.cs in your .Net Project
Add the following references in your project :
- Microsoft.SharePoint.Client
- Microsoft.SharePoint.Client.DocumentManagement
- Microsoft.SharePoint.Client.Publishing
- Microsoft.SharePoint.Client.Runtime
- Microsoft.SharePoint.Client.Runtime.Windows
- Microsoft.SharePoint.Client.Taxonomy
- Microsoft.SharePoint.Client.UserProfiles
- Microsoft.SharePoint.Client.WorkflowServices
- Microsoft.SharePoint.WorkflowServices.Activities
- Microsoft SharePoint Solutions Framework
Here, an example of the code :
private const string PSDATA = "https://[your pwa site]";
ProjectOData.ReportingData context =
new ProjectOData.ReportingData(new Uri(PSDATA + "/_api/ProjectData/", UriKind.Absolute)) { IgnoreMissingProperties = true };
var username = <username>;
var password = <password>;
var secureString = new System.Security.SecureString();
foreach (char c in password.ToCharArray())
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
SharePointOnlineCredentials credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, secureString);
var authenticationCookie = credentials.GetAuthenticationCookie(new Uri(PSDATA));
context.SendingRequest += delegate (object sender, SendingRequestEventArgs e)
{
e.RequestHeaders.Clear();
e.RequestHeaders.Add("Cookie", authenticationCookie);
};
var projectQuery1 = from p in context.Projects
select p;

How do i manage the SQL Server connections in asp.net core MVC mode?

I am working on a APP's server program which using asp.net core MVC mode. And in the XXXXcontrller i never use code like "Connection.open()" and "Connection.close()",a HTTP GET action is like this.
public async Task<IActionResult> register(string phoneNum, string password, string userType)
{
//从数据库里找到m.Id和 id相同的车,赋给dbCars
var dbCars = await _context.dbUsers.SingleOrDefaultAsync(m => m.UserName == phoneNum);
// var dbCars= _context.dbCars.Where(s => s.Id == id).FirstOrDefault<dbCars>();
if (dbCars == null)//如果为空,则注册
{
//注册新用户
dbCars = new dbUsers();
dbCars.UserName = phoneNum;
dbCars.Password = password;
dbCars.UserType = userType;
dbCars.IsVerified = true;
_context.Add(dbCars);
await _context.SaveChangesAsync();
//注册完成之后,把ID、用户类型和是否认证返回回去
List<string> userInfo = new List<string>();
userInfo.Add(dbCars.Id.ToString().Trim());
userInfo.Add(dbCars.UserType.ToString().Trim());
userInfo.Add(dbCars.IsVerified.ToString());
string json = JsonConvert.SerializeObject(userInfo);
return Ok(json);
}
else //如果不为空就代表注册过了
{
return Ok("0"); //返回1代表注册过了
}
}
I wondered how should i maintain the SQL Connections when many users access this service?? Should I close these connections manually? Or it can be done automatically by some magic?? If many users access this service, do my program breaked down??
I am confused, who can give me an answer??
if you are using Entity Framework or ORM you should see and set the connection string on the web.config or if it's on a separate layer you can see the settings on the app.config. If you run the application it will use the startup project of your application connectionstring app.config(windows application) or web.config (web application)

How to list subscriptions with Microsoft.Azure.ResourceManager?

Context
My core goal is to write an Azure WebApps deployment tool in C#. The process will be roughly
User logs in
User selects subscription
User selects or creates resource group
User selects or creates storage for the web app
User selects or creates web service plan
User selects or creates web app
Tool uploads the web app using Kudu to POST a zip
Since the last step can't be done in the portal, my idea was to do everything in a GUI tool.
I started out using Kudu's ARMClient.Authentication and Microsoft.Azure.ResourceManager 1.0.0-preview. However, when it comes to creating a storage account I get a permissions error (The subscription is not registered to use namespace Microsoft.Storage), so my plan B was to do the authentication myself following Brady Gaster's blog post.
The problem
I've set up an application as documented, and using its clientId and tenantId I'm able to log in and list tenants. But I can't list any subscriptions. (NB I've partly elided the clientId and tenantId in case there are security risks with giving them in full).
string clientId = "f62903b9-ELIDED";
string tenantId = "47b6e6c3-ELIDED";
const string redirectUri = "urn:ietf:wg:oauth:2.0:oob";
const string baseAuthUri = "https://login.microsoftonline.com/";
const string resource = "https://management.core.windows.net/";
var ctx = new AuthenticationContext(baseAuthUri + tenantId);
var authResult = ctx.AcquireToken(resource, clientId, new Uri(redirectUri), PromptBehavior.Auto);
var token = new TokenCredentials(authResult.AccessToken);
var subClient = new SubscriptionClient(token);
var tenants = await subClient.Tenants.ListAsync();
foreach (var tenant in tenants) Console.WriteLine(tenant.TenantId);
var subs = await subClient.Subscriptions.ListAsync();
foreach (var sub in subs) Console.WriteLine(sub.DisplayName);
When I run this it prompts me to login, and lists the tenants corresponding to the subscriptions I own or co-administer. But it doesn't list a single subscription. If I change the IDs to the commonly used (I think officially for Powershell) values
clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
tenantId = "common";
then it's the same.
What is the step I've missed in order to get a list of my subscriptions?
You need to iterate through the tenants, authenticate in tenant and get a subscription list for every tenant.
The following code will output the Subscriptions like Get-AzureRmSubscription powershell cmdlet does.
class Program
{
private static string m_resource = "https://management.core.windows.net/";
private static string m_clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; // well-known client ID for Azure PowerShell
private static string m_redirectURI = "urn:ietf:wg:oauth:2.0:oob"; // redirect URI for Azure PowerShell
static void Main(string[] args)
{
try
{
var ctx = new AuthenticationContext("https://login.microsoftonline.com/common");
// This will show the login window
var mainAuthRes = ctx.AcquireToken(m_resource, m_clientId, new Uri(m_redirectURI), PromptBehavior.Always);
var subscriptionCredentials = new TokenCloudCredentials(mainAuthRes.AccessToken);
var cancelToken = new CancellationToken();
using (var subscriptionClient = new SubscriptionClient(subscriptionCredentials))
{
var tenants = subscriptionClient.Tenants.ListAsync(cancelToken).Result;
foreach (var tenantDescription in tenants.TenantIds)
{
var tenantCtx = new AuthenticationContext("https://login.microsoftonline.com/" + tenantDescription.TenantId);
// This will NOT show the login window
var tenantAuthRes = tenantCtx.AcquireToken(
m_resource,
m_clientId,
new Uri(m_redirectURI),
PromptBehavior.Never,
new UserIdentifier(mainAuthRes.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId));
var tenantTokenCreds = new TokenCloudCredentials(tenantAuthRes.AccessToken);
using (var tenantSubscriptionClient = new SubscriptionClient(tenantTokenCreds))
{
var tenantSubscriptioins = tenantSubscriptionClient.Subscriptions.ListAsync(cancelToken).Result;
foreach (var sub in tenantSubscriptioins.Subscriptions)
{
Console.WriteLine($"SubscriptionName : {sub.DisplayName}");
Console.WriteLine($"SubscriptionId : {sub.SubscriptionId}");
Console.WriteLine($"TenantId : {tenantDescription.TenantId}");
Console.WriteLine($"State : {sub.State}");
Console.WriteLine();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.WriteLine("press something");
Console.ReadLine();
}
}
}
A couple things you can look into...
1) the error you saw during creating of the storage account is likely due to the Resource Provider not being registered for use with the subscription. Any RP needs to be registered before use, some clients (Portal, PowerShell) will register the RP for you so you never notice it. See: https://msdn.microsoft.com/en-us/library/azure/dn790548.aspx - you should be able to do that from your code if the user has sufficient perms.
2) You may not be getting any subscriptions back because your endpoint (management.core.windows.net) is the endpoint for Azure Service Management not Azure Resource Manager (management.azure.com). If the subscription access is granted via AzureRM and RBAC, the old ASM apis will not see (i.e. have access to) those subscriptions.

How to get user group using TFS API in asp.net MVC

http://blogs.microsoft.co.il/blogs/shair/archive/2011/12/07/tfs-api-part-41-manage-groups-and-members.aspx
He can't get group name belong to a user using WPF base on TeamProjectPicker instant:
private void BtnConnectClick(object sender, RoutedEventArgs e)
{
DisableUi();
var tpp = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false);
tpp.ShowDialog();
if (tpp.SelectedTeamProjectCollection == null) return;
EnableUi();
_tfs = tpp.SelectedTeamProjectCollection;
_css = (ICommonStructureService)_tfs.GetService<ICommonStructureService>();
_gss = (IGroupSecurityService)_tfs.GetService<IGroupSecurityService>();
var allSids = _gss.ReadIdentity(SearchFactor.AccountName,
"Project Collection Valid Users", QueryMembership.Expanded);
listAllUsers.ItemsSource = _gss.ReadIdentities(SearchFactor.Sid, allSids.Members,
QueryMembership.None).Where(a => a.Type == IdentityType.WindowsUser
|| a.Type == IdentityType.WindowsGroup);
listProjects.ItemsSource = _css.ListAllProjects();
}
I can't do it when implement this function on asp.net MVC
You will need to implement your own Project Picker or supply the project collection uri directly to the TfsTeamProjectCollectionfactory.GetProjectCollection method. See the documentation here.
To create your own Project Picker, you can use the TfsConfigurationServerFactory.GetConfigurationServer to connect to a TFS instance. See the documentation here. Then you can query all the Team Project Collections and the underlying Team Projects from there. See the following piece of documentation for more information.

System.DirectoryServices vs system.directoryservices.accountmanagement

I have an array (propertyList) that contains the names of certain Active Directory properties whose data I want to retrieve. Using Ironpython and .NET library System.DirectoryServices I solve the retrieval of properties to be loaded in this way:
for propertyActDir in propertyList:
obj.PropertiesToLoad.Add(propertyActDir)
res = obj.FindAll()
myDict = {}
for sr in res:
for prop in propertyList:
myDict[prop] = getField(prop,sr.Properties[prop][0])
The function getField is mine. How can I solve the same situation using the library system.directoryservices.accountmanagement? I think it is not possible.
Thanks.
Yes, you're right - System.DirectoryServices.AccountManagement builds on System.DirectoryServices and was introduced with .NET 3.5. It makes common Active Directory tasks easier. If you need any special properties you need to fall back to System.DirectoryServices.
See this C# code sample for usage:
// Connect to the current domain using the credentials of the executing user:
PrincipalContext currentDomain = new PrincipalContext(ContextType.Domain);
// Search the entire domain for users with non-expiring passwords:
UserPrincipal userQuery = new UserPrincipal(currentDomain);
userQuery.PasswordNeverExpires = true;
PrincipalSearcher searchForUser = new PrincipalSearcher(userQuery);
foreach (UserPrincipal foundUser in searchForUser.FindAll())
{
Console.WriteLine("DistinguishedName: " + foundUser.DistinguishedName);
// To get the countryCode-attribute you need to get the underlying DirectoryEntry-object:
DirectoryEntry foundUserDE = (DirectoryEntry)foundUser.GetUnderlyingObject();
Console.WriteLine("Country Code: " + foundUserDE.Properties["countryCode"].Value);
}
System.DirectoryServices.AccountManagement (excellent MSDN article on it here) is designed to help you more easily manage user and groups, e.g.
find users and groups
create users and groups
set specific properties on users and groups
It is not designed to handle "generic" property management like you describe - in that case, simply keep on using System.DirectoryServices, there's nothing stopping you from doing this!
Marc

Resources