How to fetch change from Git using LibGit2Sharp? - c#

The code below clone a Git url to a test directory.
var url = #"http://abc-555.com/team/project-555.git";
var path = #"E:\temp_555";
var credential = new Credentials() { Username = "a8888", Password="88888888"};
var clonePath = Repository.Clone(url, path, credentials: credential);
using (var repo = new Repository(clonePath))
{
foreach (var branch in repo.Branches)
{
Console.WriteLine(branch.Name);
}
// somebody creates a new branch here, so I want to fetch it.
repo.Fetch("origin");
foreach (var branch in repo.Branches)
{
Console.WriteLine(branch.Name);
}
}
I want to fetch a new branch before merging it to local Git. Anyway, it throws An error was raised by libgit2. Category = Net (Error). Request failed with status code: 401 exception.
How to fix this?

You can specifiy the credentials to be used through a FetchOptions instance as the last parameter of the Fetch call.
repo.Fetch("origin", new FetchOptions { Credentials = credential});

Related

Using explicit credentials in a C# dialogflow application

I'm creating a C# application that uses DialogFlow's detectIntent. I need help passing the Google Cloud credentials explicitly.
It works with the GOOGLE_APPLICATION_CREDENTIALS environment variable. However I want to pass the credentials explicitly. I need a C# version of the solution provided here.
I'm using the following quick-start provided with the documentation:
public static void DetectIntentFromTexts(string projectId,
string sessionId,
string[] texts,
string languageCode = "en-US")
{
var client = df.SessionsClient.Create();
foreach (var text in texts)
{
var response = client.DetectIntent(
session: new df.SessionName(projectId, sessionId),
queryInput: new df.QueryInput()
{
Text = new df.TextInput()
{
Text = text,
LanguageCode = languageCode
}
}
);
var queryResult = response.QueryResult;
Console.WriteLine($"Query text: {queryResult.QueryText}");
if (queryResult.Intent != null)
{
Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
}
Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
Console.WriteLine();
}
}
Currently you need to create a gRPC channel directly, and pass that into the client:
GoogleCredential credential = GoogleCredential.FromFile("...");
ChannelCredentials channelCredentials = credential.ToChannelCredentials();
Channel channel = new Channel(SessionsClient.DefaultEndpoint, channelCredentials);
var client = df.SessionsClient.Create(channel);
Very soon, this will be a lot easier via a builder pattern:
var client = new SessionsClientBuilder
{
CredentialsPath = "path to file",
}.Build();
... or various other ways of specify the credential. I'm hoping that'll be out in the next couple of weeks.

How to pass Repository name for GIT using C#

I developing a program to push files to remote repo of BonoBo GIT.
I have below code
using (var repo = new Repository("path/to/your/repo"))
{
LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions();
options.CredentialsProvider = new CredentialsHandler(
(url, usernameFromUrl, types) =>
new UsernamePasswordCredentials()
{
Username = USERNAME,
Password = PASSWORD
});
repo.Network.Push(repo.Branches[BRANCHNAME], options);
}
`
I have remote repo URL:'http://localhost/Bonobo.git.server/secondRepo.git'. where should I put this url? if I put this in the place of "url" in the code I am getting error as 'Method name expected'

Get IP of Azure VM using SDK

I have a VM powered on and running in azure. I know its name but want to retrieve its IP address programmatically using the new C# SDK and avoiding the REST API. How can I do this?
Try this:
string subId = "deadbeef-beef-beef-beef-beefbeefbeef";
string resourceGroup = "SORG01";
string vmName = "SORG01-BOX01";
using (var client = new ComputeManagementClient(credentials))
{
client.SubscriptionId = subId;
VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);
networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();
}
using (var client = new NetworkManagementClient(credentials))
{
client.SubscriptionId = subId;
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroup, vmName);
string ip = network.IpConfigurations[0].PrivateIPAddress;
}
To have these classes, you'll need to install from nuget:
Microsoft.Azure.Management.Compute
Microsoft.Azure.Management.Compute.Models
Microsoft.Azure.Management.Network
Note that you'll have to select "Include Prerelease" on the nuget search window in order to find these packages. credentials is a Microsoft.Rest.TokenCredentials object that you acquire in this manner:
var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);
result.Wait();
if (result.Result == null)
throw new AuthenticationException("Failed to obtain the JWT token");
credentials = new TokenCredentials(result.Result.AccessToken);
The easiest way to retrieve the public IP Address of Azure Virtual Machine is
{_VirtualMachineInstance}.GetPrimaryPublicIPAddress().IPAddress;
Very good explanation of this matter you can find here- Tom Sun answer:
Get Azure VM using resource manager deployment and rest api

Updating a Password in RackSpace using C#

I'm just trying to change a password of the main account and a sub user in RackSpaceCloud using C# but I keep running into a UserNotAuthorized exception. Its weird because I can do anything else without this error, reset Api keys, list users and userID's(etc.). Sample Code
net.openstack.Core.Domain.CloudIdentity cloudIdentity = new CloudIdentity()//Admin Credits
{
Username = "me",
APIKey = "blahblahblah",
};
CloudIdentityProvider cloudIdentityProvider = new CloudIdentityProvider(cloudIdentity);
cloudIdentityProvider.SetUserPassword("correctUserID", "newP#ssw0rd", cloudIdentity);
And then I error which is confusing because methods like,
cloudIdentityProvider.ListUsers(cloudIdentity)
cloudIdentityProvider.ResetApiKey("UserID", cloudIdentity);
Work Perfectly. Any Help or Ideas would be appreciated.
Oh and Btw the addition info on the exception is always the same. "Unable to authenticate user and retrieve authorized service endpoints"
This is a bug. I have opened issue 528 but in the meantime here is a workaround.
var cloudIdentity = new CloudIdentity
{
Username = "{username}",
APIKey = "{api-key}"
};
var cloudIdentityProvider = new CloudIdentityProvider(cloudIdentity);
var userAccess = cloudIdentityProvider.Authenticate(cloudIdentity);
var request = new HttpRequestMessage(HttpMethod.Post, string.Format("https://identity.api.rackspacecloud.com/v2.0/users/{0}", userAccess.User.Id));
request.Headers.Add("X-Auth-Token", userAccess.Token.Id);
var requestBody = JObject.FromObject(new { user = new { username = userAccess.User.Name } });
((JObject)requestBody["user"]).Add("OS-KSADM:password", "{new-password}");
request.Content = new StringContent(requestBody.ToString(), Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var response = client.SendAsync(request).Result;
}
The cloud identity used must be an admin if you need to change another user's password, otherwise non-admins may only change their own password.

AWS List user folder for S3

Creating a C# application to view folders and files that are stored in AWS S3 for clients that sign up to my site.
Currently I can create a IAM user and assign it permission to a specific folder. But ran into issues when I am trying to view the folder and its contents. I can view the folder if I use the AWS access key and secret key but was wondering if there is a user level credential that I can use to retrieve the folders the user has been given permission to?
This is what I have got so far.
Policy pl = GeneratePolicy(bucketName, foldername);
Credentials creds = GetFederatedCredentials(pl, username);
var sessionCredentials = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken);
using (var client = new AmazonS3Client(sessionCredentials, Amazon.RegionEndpoint.USEast1))
{
var response = client.ListObjects(request);
foreach (var subFolder in response.CommonPrefixes)
{
/* list the sub-folders */
Console.WriteLine(subFolder);
}
foreach (var file in response.S3Objects)
{
/* list the files */
}
}
But getting an error on client.ListObjects(request) - access denied error
Here is the GeneratePolicy code
public static Policy GeneratePolicy(string bucket, string username)
{
var statement = new Statement(Statement.StatementEffect.Allow);
// Allow access to the sub folder represented by the username in the bucket
statement.Resources.Add(ResourceFactory.NewS3ObjectResource(bucket, username + "/*"));
// Allow Get and Put object requests.
statement.Actions = new List<ActionIdentifier>() { S3ActionIdentifiers.GetObject, S3ActionIdentifiers.PutObject };
// Lock the requests coming from the client machine.
//statement.Conditions.Add(ConditionFactory.NewIpAddressCondition(ipAddress));
var policy = new Policy();
policy.Statements.Add(statement);
return policy;
}
Here is the GetFederatedCredentials code
public static Credentials GetFederatedCredentials(Policy policy, string username)
{
var request = new GetFederationTokenRequest()
{
Name = username,
Policy = policy.ToJson()
};
var stsClient = new AmazonSecurityTokenServiceClient(AWS_ACCESS_KEY, AWS_SECRET_KEY, Amazon.RegionEndpoint.USEast1);
var response = stsClient.GetFederationToken(request);
return response.GetFederationTokenResult.Credentials;
}
Any help would be greatly appreciated. Thanks in advance
You should add "ListBucket" to the statement.Actions

Categories