Hello I'm trying to use TFS API to create a new group, for it I have this code:
var teamProjects = this.VersionControlServer.GetAllTeamProjects(false);
foreach (var teamProject in teamProjects)
{
var result = _gss.CreateApplicationGroup(teamProject.ArtifactUri.AbsoluteUri, "NewGroup","TestDescription");
//NOW I WANT TO SET THE PERMISSIONS FOR THIS GROUP
}
As I need to set the permission "Edit project-level information" for this group I tried lot of methods and different approaches, but anything seems to solve my need. This for example:
var ProjectSecurityToken = AuthorizationSecurityConstants.ProjectSecurityPrefix + teamProject.ArtifactUri.AbsoluteUri;
var groupACL = securityNamespace.QueryAccessControlList(ProjectSecurityToken, new[] {list[4].Descriptor}, false);
securityNamespace.SetAccessControlEntry(ProjectSecurityToken, new Microsoft.TeamFoundation.Framework.Client.AccessControlEntry(list[4].Descriptor, 115, 0), true);
I had hard-coded "list[4]" because it was the group I just created, I need some help to see what is wrong in my code. I get no error message and it doesn't work as well.
I can get the permissions been set via following code:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
namespace API
{
class Program
{
static void Main(string[] args)
{
string project = "http://xxx.xxx.xxx.xxx:8080/tfs";
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(project));
var tps = tpc.GetService<VersionControlServer>();
var ttt = tps.GetTeamProject("ProjectName");
ISecurityService securityService = tpc.GetService<ISecurityService>();
System.Collections.ObjectModel.ReadOnlyCollection<SecurityNamespace> securityNamespaces = securityService.GetSecurityNamespaces();
IGroupSecurityService gss = tpc.GetService<IGroupSecurityService>();
Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, "GroupName", QueryMembership.Expanded);//GourName format: [ProjectName]\\GourpName
IdentityDescriptor id = new IdentityDescriptor("Microsoft.TeamFoundation.Identity", SIDS.Sid);
List<SecurityNamespace> securityList = securityNamespaces.ToList<SecurityNamespace>();
string securityToken;
foreach (SecurityNamespace sn in securityList)
{
if (sn.Description.DisplayName == "Project")
{
securityToken = "$PROJECT:" + ttt.ArtifactUri.AbsoluteUri;
sn.SetPermissions(securityToken, id, 115, 0, true);
}
}
}
}
}
Related
How to verify two Images using Azure Cognitive Face API ? Need Sample Code
I have two images of a single person. Now I want to compare those images and check whether those images are of same person or not. From the documentation I came to know that, I have to send two faceid's along with the url. I tried that, but it is not working. May be, I am missing something. Please help me for the same & provide me some sample code for the same if possible.
Waiting for your response.
Try the console app code below :
using Microsoft.Azure.CognitiveServices.Vision.Face;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using System;
using System.IO;
using System.Linq;
using System.Threading;
namespace FaceIdentityTest
{
class Program
{
static void Main(string[] args)
{
string persionPicPath = #"<some path>\personPic.jpg";
String[] picsPath = { #"<some path>\pic1.jpg", #"<some path>\pic2.jpg" };
string endpoint = #"https://<your endpoint name>.cognitiveservices.azure.com/";
string subscriptionKey = "<your subscription key>";
IFaceClient faceClient = new FaceClient(
new ApiKeyServiceClientCredentials(subscriptionKey),
new System.Net.Http.DelegatingHandler[] { });
faceClient.Endpoint = endpoint;
// Create an empty PersonGroup
Console.WriteLine("create person group");
string personGroupId = "demogroup";
faceClient.PersonGroup.CreateAsync(personGroupId, "demo group").GetAwaiter().GetResult();
// Define a person named Bill
Console.WriteLine("create a person in group");
var createPersonResult = faceClient.PersonGroupPerson.CreateAsync(
// Id of the PersonGroup that the person belonged to
personGroupId,
// Name of the person
"Bill"
).GetAwaiter().GetResult();
//Add a face to Bill
Console.WriteLine("Add a face to person");
using (Stream s = File.OpenRead(persionPicPath))
{
// Detect faces in the image and add to Anna
faceClient.PersonGroupPerson.AddFaceFromStreamAsync(
personGroupId, createPersonResult.PersonId, s).GetAwaiter().GetResult();
}
//Train person group
Console.WriteLine("start train person group...");
faceClient.PersonGroup.TrainAsync(personGroupId).GetAwaiter().GetResult();
//Check train status
TrainingStatus trainingStatus = null;
while (true)
{
trainingStatus = faceClient.PersonGroup.GetTrainingStatusAsync(personGroupId).GetAwaiter().GetResult();
if (trainingStatus.Status != TrainingStatusType.Running)
{
break;
}
else {
Console.WriteLine("trainning person group...");
}
Thread.Sleep(1000);
}
foreach (var pic in picsPath) {
Console.WriteLine("start identify faces in :" + pic);
using (Stream s = File.OpenRead(pic))
{
var faces = faceClient.Face.DetectWithStreamAsync(s).GetAwaiter().GetResult();
var faceIds = faces.Select(face => (Guid)face.FaceId).ToList();
var results = faceClient.Face.IdentifyAsync(faceIds, personGroupId).GetAwaiter().GetResult();
foreach (var identifyResult in results)
{
Console.WriteLine("Result of face: {0}", identifyResult.FaceId);
if (identifyResult.Candidates.Count == 0)
{
Console.WriteLine("No one identified");
}
else
{
// Get top 1 among all candidates returned
var candidateId = identifyResult.Candidates[0].PersonId;
var person = faceClient.PersonGroupPerson.GetAsync(personGroupId, candidateId).GetAwaiter().GetResult();
Console.WriteLine("Identified as {0}", person.Name);
}
}
}
}
Console.ReadKey();
}
}
}
My pics :
Result :
Btw, no matter which programming language you are using , just follow the steps in this demo will be able to use Face API to identify faces .
Hope it helps .
You can import Microsoft.Azure.CognitiveServices.Vision.Face here in VS :
I need to be able to get a list of all named ranges in a spreadsheet, but can't figure out how to do this.
I've found the following code but its not c# - how do I do the same thing in c#?
Code that does what I need but not in c#
function getNamedRanges2(spreadsheetId) {
var ss = SpreadsheetApp.openById(spreadsheetId);
var sheetIdToName = {};
ss.getSheets().forEach(function(e) {
sheetIdToName[e.getSheetId()] = e.getSheetName();
});
var result = {};
Sheets.Spreadsheets.get(spreadsheetId, {fields: "namedRanges"})
.namedRanges.forEach(function(e) {
var sheetName = sheetIdToName[e.range.sheetId.toString()];
var a1notation = ss.getSheetByName(sheetName).getRange(
e.range.startRowIndex + 1,
e.range.startColumnIndex + 1,
e.range.endRowIndex - e.range.startRowIndex,
e.range.endColumnIndex - e.range.startColumnIndex
).getA1Notation();
result[e.name] = sheetName + "!" + a1notation;
});
return result;
}
function main() {
var spreadsheetId = "### spreadsheet ID ###";
var result = getNamedRanges2(spreadsheetId);
Logger.log(JSON.stringify(result));
}
Based on the Quickstart for Sheets API and the C# sample code for Method: spreadsheets.get2, you can combine the two code snippets as following, in order to retrieve named ranges:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Newtonsoft.Json;
using Data = Google.Apis.Sheets.v4.Data;
namespace SheetsQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "Google Sheets API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// The spreadsheet to request.
string spreadsheetId = "YOUR SPREADSHEET ID";
// TODO: Update placeholder value.
SpreadsheetsResource.GetRequest request = service.Spreadsheets.Get(spreadsheetId);
request.Fields = "namedRanges";
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Data.Spreadsheet response = request.Execute();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
}
}
The response will contain only the named ranges when request.Fields = "namedRanges"; is specified.
I am using the following code
BuildHttpClient service = new BuildHttpClient(tfsCollectionUri,
new Microsoft.VisualStudio.Services.Common.VssCredentials(true));
var asyncResult = service.GetBuildsAsync(project: tfsTeamProject);
var queryResult = asyncResult.Result;
This returns only the first 199 builds.
Looks like in need to use the continuationtoken but am not sure how to do this. The docs say that the REST API will return the token. I am using the Object Model, and am looking for how to retrieve the token!
I am using Microsoft.TeamFoundationServer.Client v 14.102.0; Microsoft.TeamFoundationServer.ExtendedClient v 14.102.0, Microsoft.VisualStudio.Service.Client v 14.102.0 and Microsoft.VisualStudio.Services.InteractiveClient v 14.102.0
Question
How do I use the continuation token **when using the TFS Object model?
The continuationToken is in the response header after the first call to the API:
x-ms-continuationtoken: xxxx
It can not be retrieved from .net client library. You have to use the rest api to retrieve the header information. Here is an example for your reference:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace GetBuilds
{
class Program
{
public static void Main()
{
Task t = GetBuilds();
Task.WaitAll(new Task[] { t });
}
private static async Task GetBuilds()
{
try
{
var username = "xxxxx";
var password = "******";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
using (HttpResponseMessage response = client.GetAsync(
"http://tfs2015:8080/tfs/DefaultCollection/teamproject/_apis/build/builds?api-version=2.2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You have to use 'GetBuildsAsync2', which returns an IPagedList. You can retrieve the ContinuationToken from the IPagedList:
// Iterate to get the full set of builds
string continuationToken = null;
List<Build> builds = new List<Build>();
do
{
IPagedList<Build> buildsPage = service.GetBuildsAsync2(tfsTeamProject, continuationToken: continuationToken).Result;
//add the builds
builds.AddRange(buildsPage);
//get the continuationToken for the next loop
continuationToken = buildsPage.ContinuationToken;
}
while (continuationToken != null);
In CRM 2011, I want to attach Contacts to Quote, no problems for that.
When I save the quote, for each Contact I want to send a email for reminder purpose. (With a plugin)
How It's possible to flag this and give the ability to CRM user to unflag this from the quote form with a checkbox.
The final purpose, It's to give the ability to CRM user to send a new email reminder to one or multiple contacts attached in the quote.
Can you help me ?
You will need to have a ribbon button that will call a JavaScript method in one of the web-resources.
In the CommandDefinition of you RibbonDiff XML you will need to send a parameter to the JS method which will contain all the IDs of selected records in the subgrid.
<CommandDefinitions>
<CommandDefinition Id="xyz.Button.SendEmail.command">
<EnableRules>
</EnableRules>
<DisplayRules>
</DisplayRules>
<Actions>
<JavaScriptFunction Library="$webresource:Test.Js" FunctionName="SendEmail">
<CrmParameter Value="SelectedControlAllItemIds" />
</JavaScriptFunction>
</Actions>
</CommandDefinition>
and then the JS method would be something like below wherein you will need to parse all the IDs and then process your logic
function SendEmail(selectedIds) {
if (selectedIds != null && selectedIds != “”) {
var strIds = selectedIds.toString();
var arrIds = strIds.split(“, ”);
for (var indxIds = 0; indxIds < arrIds.length; indxIds++) {
//The logic that you want to process on each record will come here.
}
} else {
alert(“No records selected !! !”);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}
I am trying to query on both Release and Iteration so I can fill out a drop down list with these various values. I'm not quite sure how to do this, however. What are the members of the object that come back via the query if we are able to do this? (Name, FormattedID, CreationDate, etc). Do we just create a new request of type "Release" and "Iteration" ?
Thanks!
Here is a code that queries on releases based on a project reference. If this project is not in a default workspace of the user that runs the code we either need to hardcode the workspace reference or get it from the project.
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "TopSecret1984", "https://rally1.rallydev.com", "1.40");
var projectRef = "/project/22222222"; //use your project OID
DynamicJsonObject itemWorkspace = restApi.GetByReference(projectRef, "Workspace");
var workspaceRef = itemWorkspace["Workspace"]["_ref"];
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
Request request = new Request("Release");
request.ProjectScopeDown = false;
request.ProjectScopeUp = false;
request.Workspace = workspaceRef;
request.Fetch = new List<string>()
{
"Name"
};
// request.Query = new Query("Project.ObjectID", Query.Operator.Equals, "22222222"); //also works
request.Query = new Query("Project", Query.Operator.Equals, projectRef);
QueryResult queryResult = restApi.Query(request);
foreach (var r in queryResult.Results)
{
Console.WriteLine("Name: " + r["Name"]);
}
}
catch
{
Console.WriteLine("problem!");
}
}
}
}