Is there any way to refresh pull request merge status in Azure DevOps REST API? - c#

Using the Azure DevOps REST API in C#, I'm creating a pull request and then attempting to complete it like this (simplified):
var pullRequest = new GitPullRequest {
Title = "My PR",
SourceRefName = "refs/heads/my",
TargetRefName = "refs/heads/master",
Commits = commits
};
pullRequest = await gitClient.CreatePullRequestAsync(pullRequest, repositoryId);
await Task.Delay(3000);
if (pullRequest.MergeStatus == PullRequestAsyncStatus.Succeeded) {
var pr2 = new GitPullRequest
{
LastMergeSourceCommit = pullRequest.LastMergeSourceCommit,
Status = PullRequestStatus.Completed
};
var result = await gitClient.UpdatePullRequestAsync(pullRequest, pullRequest.Repository.Id, pullRequest.pullRequestId);
}
This works fine if there's no conflicts. But if the pull request has conflicts, MergeStatus will be Conflicts. Now, let's assume someone resolves those conflicts manually and the PR is ready to be merged.
After resolving conflicts I get the pull request again
var pullRequest = await gitClient.GetPullRequestByIdAsync(pullRequestId);
pullRequest.MergeStatus is still Conflicts, even though UI is showing green.
Is there a way to refresh MergeStatus once it has been set to Conflicts? I tried updating the pull request by setting MergeStatus to Queued. Or is it a missing feature in the API?

Hopefully you got through this, so just in case someone else comes looking (like I did today) this worked for me.
var prOriginal = gitClient.CreatePullRequestAsync(
new GitPullRequest() {
SourceRefName = $"refs/heads/{Input.SrcBranch}",
TargetRefName = $"refs/heads/{Input.TgtBranch}",
Title = Input.Title,
Description = Input.Description
},
tgtRepo.Id).Result;
Thread.Sleep(TimeSpan.FromSeconds(30));
var statusRetry = 0;
var prTest = gitClient.GetPullRequestAsync(
tgtRepo.Id,
prOriginal.PullRequestId).Result;
while(PullRequestAsyncStatus.Succeeded != prTest.MergeStatus) {
// TODO decide when to quit.
Thread.Sleep(TimeSpan.FromSeconds(30));
prTest = gitClient.GetPullRequestAsync(
tgtRepo.Id,
prOriginal.PullRequestId).Result;
}
Debug.WriteLine($"MergeStatus: {prTest.MergeStatus}");
MergeStatus came back succeeded soon after I resolved the problems online. Now if I can get those conflicts resolved using the api I'll be in great shape.

Related

How can we add existing links in Azure DevOps programmatically

I want to link the existing work items which are already created in a project under Azure DevOps by writing a code or program in C#, so is there any kind of API or SDK which can be used to link the work items programmatically?
The Workitems can be of any type i.e.
Bug
User Story
Issue
Task etc.
The linking between the Workitems can also be of any type i.e. Relational, Parent-Child, etc.
Recently I referred to this link for my problem.
The link contains issue very much related and similar to mine, however it is not working as expected when I tried it.
Given:
//int relatedId = ...
//int id = ...
//CancellationToken token = ...
//string organization = ...
//string projectName = ...
//WorkItemTrackingHttpClient azureClient = ...
Create a JsonPatchDocument as below:
JsonPatchDocument patchDoc = new JsonPatchDocument();
patchDoc.Add(
new JsonPatchOperation
{
From = null,
Operation = Operation.Add,
Path = "/relations/-",
Value = new {
rel = "System.LinkTypes.Related",
url = $"https://dev.azure.com/{organization}/{projectName}/_workitems/edit/{relatedId}",
attributes = new
{
comment = $"Created programmatically on {DateTime.Now}."
}
}
}
);
and call this async method of Azure DevOps SDK:
await azureClient.UpdateWorkItemAsync(patchDoc, id, false, true, true, WorkItemExpand.All, cancellationToken: token);
In the case above we created a related link using System.LinkTypes.Related referenceName.
For a full link types reference guide in Azure DevOps refer to this so's question or this microsoft's doc.

Cancel the StripeSubscriptionservice

Right now, I work as a member of the site to cancel membership. Just when I try to run through the test, it makes the mistake of saying it
Stripe.StripeException: 'No such subscription: cus_CCKeYhNjyKTYTh'
Here's how information is displayed by a user with this ID.
var api = Settings.ConstName.StrinpAPIKey;//Get Stripe Key from Class.
StripeConfiguration.SetApiKey(api);
var customerSerive = new StripeCustomerService(api);
var subservice = new StripeSubscriptionService(api);
var stripeCustomerID = customerSerive.Get(members.User.CustomerId);//members i get the userCustomerId from DB.
subservice.Cancel(subscriptionId: check.CustomerId, cancelAtPeriodEnd: true);
So my question is how it may be that it will not let me do it? Do I need anything more for it to stop the membership of the customer?
i have a check here:
It's 100% the same ID I have in the database* and i get the version from stripe 12.1.0
i have complete this:
var api = Settings.ConstName.StrinpAPIKey;
StripeConfiguration.SetApiKey(api);
var customerSerive = new StripeCustomerService(api);
var subservice = new StripeSubscriptionService(api);
var stripeCustomerID = customerSerive.Get(members.User.CustomerId);
var GetIdSubscriptions = stripeCustomerID.Subscriptions.FirstOrDefault(i => i.CustomerId == check.CustomerId).Id;

How do I grab user info from Microsoft Graph for authenticated user using Azure mobile app backend?

Using the backend of my app, I am attempting to capture information from Microsoft Graph for a user that has been authenticated and then add that user to a database. The authentication appears to be working correctly, but the user is never added to the database. I am really stuck on this. I've studied the online documentation extensively, but have been unable to find a solution. If I could just tell if the user properties were getting populated, I could figure out what's going on, but I've been unable to do that since the code runs on the server. (I've attempted to remote debug, but have been unable to successfully set a breakpoint.) Can anyone tell me what I'm doing wrong in the code below?
class MicrosoftAccountInfo
{
public string id { get; set; }
public string displayName { get; set; }
public string mail { get; set; }
}
[MobileAppController]
public class MicrosoftAccountController : ApiController
{
MicrosoftAccountCredentials credentials;
string msRequestUrl;
MyAppContext context;
EntityDomainManager<User> domainManager;
// GET api/<controller>
public async Task<User> Get()
{
if (credentials == null)
{
credentials = await this.User.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(this.Request);
}
msRequestUrl = "https://graph.microsoft.com/v1.0/me/?$select=id,displayName,mail";
var client = new System.Net.Http.HttpClient();
var headerValue = "Bearer" + credentials.AccessToken;
client.DefaultRequestHeaders.Add("Authorization", headerValue);
var resp = await client.GetAsync(msRequestUrl);
resp.EnsureSuccessStatusCode();
var msInfo = await resp.Content.ReadAsStringAsync();
MicrosoftAccountInfo info = JsonConvert.DeserializeObject<MicrosoftAccountInfo>(msInfo);
context = new MyAppContext();
domainManager = new EntityDomainManager<User>(context, Request);
var user = context.Users.FirstOrDefault(u => u.Email == info.mail);
if (user == null)
{
user = new DataObjects.User { Email = info.mail, UserName = info.displayName, ProviderId = info.id };
await domainManager.InsertAsync(user);
}
else if (string.IsNullOrEmpty(user.ProviderId))
{
user.UserName = info.displayName;
user.ProviderId = info.id;
await context.SaveChangesAsync();
}
return user;
}
}
As to why this is failing, it is difficult to determine without an actual error message. There are simply to many variables/potential failure points involved to say for sure.
That said, you can reduce the number of potential failure points by using the Microsoft Graph .NET Client Library. There is also a NuGet package available: Install-Package Microsoft.Graph.
This library will handle composing the Microsoft Graph and deserializing the response into an object. Along with removing a risk factor, it will greatly simplify your code:
Microsoft.Graph.GraphServiceClient graphClient =
new Microsoft.Graph.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", "{your-access-token}");
return Task.FromResult(0);
}));
Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync();
I would also suggest implementing a monitoring solution that can trap exceptions on the server. This will help with debugging. If you're running on Azure, I strongly recommend using Application Insights. Aside from being free to get started, it is effectively a "click once, get monitoring" solution. It will handle wiring up the server and provide reporting for any exceptions it runs into.
Note that you can also use App Insights with your own servers or apps hosted on other services (i.e. AWS, RackSpace), there may however be some manual configuration required.

Connect CouchDB with asp.net C# application

How to connect couchDB with ASP.NET C# application? If any one can you give a sample application.
I had the same need and after evaluating the options available, to meet the requirements of my application, I created any components that helped me a lot and maybe they can help you and also others. I make it clear that I have no intention of promoting myself here, just sharing something that may be useful.
The detailed explanation of how to configure and use it is on Github.
Link: Nuget Package |
Github
Example of use for retrieving documents with mango-querie:
IList<User> users;
var sts = new List<String> { "ACTIVE", "LOCKED" };
using (UserRepository db = new UserRepository())
{
var query = db.FindOf("list-status", new { id = "OwnerIdloop.user.7", statuses = sts });
users = db.List<User>(query);
}
Array.ForEach(users.ToArray(), Console.WriteLine);
Example of adding documents:
User user = createUser("email#email.com");
using (UserRepository db = new UserRepository())
{
var result = db.Insert<User>(user); // add document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of changing documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
user.Name = user.Name + "::CHANGED";
var result = db.Update<User>(user); // update document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of deleting documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
var result = db.Delete<User>(user); // delete document from database. Return true case sucess or false case not deleted
Console.WriteLine($"Sucesso: {result}");
}
After installing the NuGet, just create an instance of MyCouch.Client and pass it the URL of your database.
using (var client = new MyCouchClient("http://127.0.0.1:5984/test"))
{
//Consume here
}
The format is: {scheme}://[{username}:{password}]/{authority}/{localpath}. From v0.11.0, there's a specific MyCouchUriBuilder that you can use for building the Uri. It will automatically e.g. apply Uri.EscapeDataString to username and password when calling SetBasicCredentials.
var uriBuilder = new MyCouchUriBuilder("http://localhost:5984/")
.SetDbName(TestConstants.TestDbName)
.SetBasicCredentials("foob#r", "p#ssword");
return new MyCouchClient(uriBuilder.Build());
For more details Click Here

c# using Magento REST api to display product information

I created a windows form app and have been looking for a way to pass authentication to connect to the server and retrieve product information.
Couldn't find any examples anywhere. Can someone help me?
Here is the api link.
If you check out this link you might get everything you need:
https://github.com/nickvane/Magento-RestApi/wiki/Authentication-steps
Usage of the library can be found here:
https://github.com/nickvane/Magento-RestApi
(just scroll down a bit)
So in order to authenticate your code, you can use:
var client = new MagentoApi()
.Initialize("http://www.yourmagentourl.com", "ConsumerKey", "ConsumerSecret")
.AuthenticateAdmin("UserName", "Password");
or the other variants that exist in the last above link.
Please use the code below. I think it will help you
var client = new MagentoApi()
.SetCustomAdminUrlPart(AdminUrlPart)
.Initialize(StoreUrl, ConsumerKey, ConsumerSerect)
.AuthenticateAdmin(AdminUserName, AdminPassword);
var filter = new Magento.RestApi.Models.Filter();
//filter.FilterExpressions.Add(new FilterExpression("name", ExpressionOperator.like, "L%"));
filter.PageSize = 100;
filter.Page = 0;
// var response = await client.GetProducts(filter);
var sCode = Task.Run(async () => await client.GetProducts(filter));
MagentoApiResponse<IList<Magento.RestApi.Models.Product>> product = sCode.Result;

Categories

Resources