What is the equivalent of Invoke("SetOption") in System.DirectoryServices.Protocols? - c#

I have a legacy .NET library doing the following:
const int adsOptionPasswordMethod = 7;
const int adsPasswordEncodeClear = 0;
user.Invoke ("SetOption", new object[] { adsOptionPasswordMethod, adsPasswordEncodeClear });
I am using System.DirectoryServices.Protocols in .NET 7 now, and I want to do something like this:
const int adsOptionPasswordMethod = 7;
const int adsPasswordEncodeClear = 0;
var setOptionsAccountControl = new DirectoryAttributeModification
{
Operation = DirectoryAttributeOperation.Replace,
Name = "SetOption",
};
modifyUserAccountControl.Add(adsOptionPasswordMethod);
modifyUserAccountControl.Add(adsPasswordEncodeClear);
But the above seems wrong.

According to the documentation, the value of ADS_PASSWORD_ENCODE_CLEAR is 1, but the old code is using 0, which is the value for ADS_PASSWORD_ENCODE_REQUIRE_SSL, which requires the use of SSL.
So if the old code was working, then it must have already been connecting via SSL (port 636).
The documentation for the unicodePwd attribute (the real attribute for the password, although userPassword can work too) says that:
servers require that the client have a 128-bit (or better) SSL/TLS-encrypted connection to the DC in order to modify this attribute.
If it's already using SSL, then that's all that's needed to be able to set the password. Setting those options isn't necessary.

Related

Why is this public address different for an ethereum signature?

I have a signature created using metamask and the personal_sign RPC method.
Now I want to verify this signature in my C# backend.
In order to do so I have found the Nethereum library.
I have written the below code trying to verify the signature (for now I have used 'test' as the signed message).
public void VerifySignature(string signatureString, string originalMessage)
{
string msg = "\x19Ethereum Signed Message:\n" + originalMessage.Length + originalMessage;
byte[] msgHash = new Sha3Keccack().CalculateHash(Encoding.UTF8.GetBytes(msg));
EthECDSASignature signature = MessageSigner.ExtractEcdsaSignature(signatureString);
EthECKey key = EthECKey.RecoverFromSignature(signature, msgHash);
bool isValid = key.Verify(msgHash, signature);
}
Now the isValid comes back as true. However, if I use key.GetPublicAddress() this address is different than my own public address, so I assume I'm doing something wrong. Can anyone explain to me what, or correct if I'm wrong?
NOTE:
If instead of
EthECKey testKey = EthECKey.RecoverFromSignature(signature, msgHash);
I use
EthECKey testKey = EthECKey.RecoverFromSignature(signature, msgHash, new BigInteger(1));
(I'm using the main network to sign which is chain 1)
I get an error saying "recId should be positive", not sure if this is related but I thought it's worth mentioning.
UPDATE:
Managed to fix this by changing the msg string to use "\x19" + "Ethereum ..." instead of "\x19Ethereum ...", \x19E results in a different character, and results in a different message hash.
The Ethereum address and the public key are different. The Ethereum address is the last 20 bytes of the hash of the public key (see https://ethereum.org/en/developers/docs/accounts/ and https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Signer/EthECKey.cs#L201).

How to get subreddits of current user?

I trying to write simple application that will notify me about new posts in my subreddits from few hours ago.
example of code is:
var reddit = new RedditClient("this is appId", "this is refreshToken");
string subRedditor = "funny";
Subreddit sr = reddit.Subreddit(subRedditor).About();
DateTime dtAfter = DateTime.Now.AddHours(-8);
List<Post> searchedPosts = sr.Posts.GetNew(new CategorizedSrListingInput(after: dtAfter.ToString(), limit: 100));
for (int i=0; i<searchedPosts.Count; i++)
{
Console.WriteLine(searchedPosts[i].Created+" | "+ searchedPosts[i].Title+" | "+searchedPosts[i].Listing.URL);
}
It works nice when I know subreddit name. But the names are nonconstant values, they can change if moderators want. So I wonder to know Is exists some api to get subreddits of current user?
Something like this:
User currUser = reddit.User();
currUser.GetSubreddits;
You didn't mention what SDK you use, so I've assumed it's Reddit.NET by Kris Craig.
Subscribed subreddits can be accessed via the MySubscribedSubreddits method in the Account class:
var subscribed = reddit.Account.MySubscribedSubreddits();

Retrieve AccountKey or ConnectionString from DocumentDB-Account using Pulumi

I create a CosmosDB/DocumentDB - Account using AzureNextGen:
var databaseAccount=new Pulumi.AzureNextGen.DocumentDB.Latest.DatabaseAccount(accountName,
new Pulumi.AzureNextGen.DocumentDB.Latest.DatabaseAccountArgs
{
// parameters
}
);
To be able to access this database afterwards I need to retrieve either the key or connection string of that databaseaccount:
I can build the first part of the connection string (the endpoint) via databaseAccount.DocumentEndpoint.Apply(q => "AccountEndpoint=" + q) but I am stuck getting the more crucial part, the key.
How can this be achieved?
Azure API doesn't return any sensitive data automatically. You need to run an explicit query for any secret data.
In this case, you should use functions listDatabaseAccountKeys and listDatabaseAccountConnectionStrings for this purpose. Here is a snippet in TypeScript:
const keys = pulumi.all([resourceGroupName, databaseAccount.name])
.apply(([resourceGroupName, accountName]) =>
documentdb.listDatabaseAccountKeys({ resourceGroupName, accountName }));
const connectionStrings = pulumi.all([resourceGroupName, databaseAccount.name])
.apply(([resourceGroupName, accountName]) =>
documentdb.listDatabaseAccountConnectionStrings({ resourceGroupName, accountName }));
const connectionString = connectionStrings.apply(cs => cs.connectionStrings![0].connectionString);
const masterKey = keys.primaryMasterKey;
Copied from this example.
When translating to C#, you'd use Output.Tuple instead of pulumi.all like in this template.
Based on Mikhails answer the C# - code to retrieve the primary key is as follows:
var keys = Pulumi.AzureNextGen.DocumentDB.Latest.ListDatabaseAccountKeys.InvokeAsync(
new Pulumi.AzureNextGen.DocumentDB.Latest.ListDatabaseAccountKeysArgs
{
AcccountName = "databasename",
ResourceGroupName = "resourcename"
});
var key = Output.Create(keys).Apply(q => q.PrimaryMasterKey);

Cannot update read/write attributes of UserPoolClient via C# SDK

When programmatically creating a Cognito user pool and app client, if the app client is to have read/write access to attributes of the user pool, that access must be explicitly given. I have been able to do so successfully for custom attributes but built-in attributes always return an error of "Invalid write attributes specified while creating a client" or "Invalid read attributes specified while creating a client".
Documentation is ... both voluminous and difficult to find. I have yet to see an example of this or an actual bit of useful documentation on the CreateUserPoolClientRequest type that says anything about this other than things like "ReadAttributes is a list of strings that are the attributes that can be read".
Here is the code I'm using that always ends up with that error message and failure to create the app client. _client is an AmazonCognitoIdentityProviderClient properly instantiated and credentialed and running in a lambda function.
var request = new CreateUserPoolClientRequest { UserPoolId = userPoolId, ClientName = $"{name}AppClient" };
var builtInAttributes = new List<string>()
{
"address","birthdate","email","family name","gender","given name","locale","middle name","name","nickname","phone number", "picture","preferred username","profile","zoneinfo","updated at","website"
};
var readAttributes = new List<string>();
var writeAttributes = new List<string>();
readAttributes.InsertRange(0,builtInAttributes);
writeAttributes.InsertRange(0, builtInAttributes);
var attributeConfig = ConfigurationHelper.GetListFromSection("UserPoolCustomAttributes");
foreach (var attribute in attributeConfig)
{
readAttributes.Add($"custom:{attribute.Key}");
writeAttributes.Add($"custom:{attribute.Key}");
}
request.ReadAttributes = readAttributes;
request.WriteAttributes = writeAttributes;
var result = await _client.CreateUserPoolClientAsync(request, CancellationToken.None);
Any help is greatly appreciated.
Figured it out. Though I have yet to find it documented anywhere, default attributes with a space in the name in the ui need to have that space replaced with an underscore when using their name in the api.

Different connection string for output or trigger

Here i have a webjob function using servicebus triggers and outputs. I'd like to set a different configuration for output and input.
public static void OnPush(
[ServiceBusTrigger("%PushProcessor.InputTopicName%", "%PushProcessor.InputTopicSubscriptionName%", AccessRights.Listen)]
BrokeredMessage message,
[ServiceBus("%PushProcessor.OutputTopicName%", AccessRights.Send)]
out BrokeredMessage output
)
I see in latest api that one can control the job host with service bus extensions.
JobHostConfiguration config = new JobHostConfiguration
{
StorageConnectionString = ConfigHelpers.GetConfigValue("AzureWebJobsStorage"),
DashboardConnectionString = ConfigHelpers.GetConfigValue("AzureWebJobsDashboard"),
NameResolver = new ByAppSettingsNameResolver()
};
config.UseServiceBus(new ServiceBusConfiguration
{
MessageOptions = new OnMessageOptions {
MaxConcurrentCalls = 2,
AutoRenewTimeout = TimeSpan.FromMinutes(1),
AutoComplete = true,
},
ConnectionString = ConfigHelpers.GetConfigValue("InputServiceBusConnectionString"),
});
Unfortunately i see no control for the connection string for the output. I'd like a different connection string (different namespace/access rights) to be used for inputs versus outputs.
Perhaps the api can support registering named jobhostconfigurations to a jobhost, and referring to that name in the attributes for the trigger/output. Anyways if there is a way to do this let me know.
Yes, also in the latest beta1 release you'll see that there is now a ServiceBusAccountAttribute that you can apply along with the ServiceBusTrigger/ServiceBus attributes. For example:
public static void Test(
[ServiceBusTriggerAttribute("test"),
ServiceBusAccount("testaccount")] BrokeredMessage message)
{
. . .
}
We've done the same for all the other attribute types (Queue/Blob/Table) via StorageAccountAttribute. These account attributes can be applied at the class/method/parameter level. Please give this new feature a try and let us know how it works for you. Also, see the release notes for more details.

Categories

Resources