Step 1:
Created GraphServiceClient using Microsoft.Graph 4.9.0 and Microsoft.Graph.Core 2.0.5 SDK
var scopes = new[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, new ClientSecretCredentialOptions()
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});`
GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
Step 2:
And created a custom schema extension like below.
SchemaExtension schemaExtension = new SchemaExtension()
{
Id = "data1",
Description = "creating test schema extn",
TargetTypes = new List<string>()
{
"User"
},
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty()
{
Name ="prop1",
Type ="String"
}
}
};
Step 3:
Updated the Schema extension status to "Available"
var updatedExtn = await graphServiceClient
.SchemaExtensions[schemaExtension.Id].Request()
.UpdateAsync(new SchemaExtension()
{
Status = "Available"
});
Step 4:
Create Class for extension data
public class data1
{
// You must serialize your property names to camelCase if your SchemaExtension describes as such.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "prop1", Required = Newtonsoft.Json.Required.Default)]
public string Prop1 { get; set; }
}
Step 5:
Find the User and add the created schema extension to the user
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
// The below line is not working. but doesn't throw error
extensionInstance.Add(schemaExtension.Id, new data1 { prop1 = "testing" });
var usrCollection = await graphServiceClient.Users
.Request()
.Filter($"userPrincipalNames eq '{adelev_Mail}'")
.GetAsync();
var usr = usrCollection.FirstOrDefault();
if(usr != null)
{
usr.AdditionalData.Add(extensionInstance);
var updatedUser = await graphServiceClient.Users[usr.Id]
.Request()
.UpdateAsync(usr);
}
Step 6:
When you try to retrieve the extension the value is NULL.
User updatedUser = await graphServiceClient.Users[usr.Id].Request()
.Select($"id, {schemaExtension.Id}")
.GetAsync();
But it works with API using Graph Explorer.
PATCH https://graph.microsoft.com/v1.0/users/{userId}
{
"extXXXXXXXX_data1":
{
"prop1" : "testing"
}
}
Please let me know if I'm missing anything here. Any help here is much appreciated.
You should accessing the data on AdditionalData property. Try looking at user.AdditionalData in your result. Here is a screenshot with my example.
Getting User with Schema extension from Graph explorer.
While using the SDK, i access my custom data in user.AdditionalData
Check this thread - Graph SDK and SchemaExtensions for details.
Related
I'm trying to get the response of create chat function with Microsoft Graph Api in my c# Application and show it in a textbox, to let my c# system be able to sent message with the chatID. I was be able to get the response of getallchat with following the steps in How can I parse the JSON response from Microsoft Graph Api List Chat into the textbox, bt I was nt unable to use the following steps to get the response of create chat any ideas?Documentation of create chat https://learn.microsoft.com/en-us/graph/api/chat-post?view=graph-rest-1.0&tabs=http
Coding Part of create chat
private async void button5_Click(object sender, EventArgs e)
{
var scopes = new[] { "Directory.Read.All", "Directory.ReadWrite.All", "User.Read", "User.Read.All", "User.ReadBasic.All", "User.ReadWrite", "Chat.Create", "Chat.ReadWrite" };
{
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "5xxxxxxx3-3xxx6a-xxx1-9xxxc-exxxxxxxxx0";
// Value from app registration
var clientId = "3xxxx04-5c92-42xxx-8500-6xxxxxxxaf";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var userName = "xx.yxxxx#xxxxxxi.com";
var password = "Aaxxxxxxxxxxx#";
// https://learn.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential
var userNamePasswordCredential = new UsernamePasswordCredential(
userName, password, tenantId, clientId, options);
GraphServiceClient graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);
var chat = new Chat
{
ChatType = ChatType.OneOnOne,
Members = new ChatMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users[comboBox1.Text]"}
}
},
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users/[comboBox2.Text]"}
}
}
}
};
await graphClient.Chats
.Request()
.AddAsync(chat);
}
}
here's the sample from the api document.
pls try to give the application api permission and try code below.
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var chat = new Chat
{
ChatType = ChatType.OneOnOne,
Members = new ChatMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users('8b081ef6-4792-4def-b2c9-c363a1bf41d5')"}
}
},
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users('82af01c5-f7cc-4a2e-a728-3a5df21afd9d')"}
}
}
}
};
var res = await graphClient.Chats.Request().AddAsync(chat);
How can I update a certain field in tfs web with Python?
I have connected to tfs and have received an HTML response.
I have a json with the data that I would like to insert to tfs testCases field.
JSON:
data = json.loads(url.read().decode()) (Json external data)
HTML:
tfsResponse = requests.get(tfsApi, auth=HttpNtlmAuth(username, password))
if tfsResponse.ok:
print(tfsResponse)
soup = BeautifulSoup(tfsResponse.text, 'lxml')
How can I do it?
It's not able to directly use Jenkins automation tests results to update TFS test case.
You need use Rest API to handle this. You need to extract the test results fist then update them to TFS server.
With using below Rest API:
PATCH https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=5.1
Sample body
[
{
"state": "Completed",
"testPoint": {
"id": 10
},
"outcome": "Passed",
"testCase": {
"id": 4567
}
}
]
If you want to use code, a code snippet for your reference, should similar to Python:
try
{
var u = new Uri("https://{My Account}.visualstudio.com");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "PAT"));
var connection = new VssConnection(u, c);
var testClient = connection.GetClient<TestManagementHttpClient>();
int testpointid = 1;
string teamProject = "MyProjectName";
RunCreateModel run = new RunCreateModel(name: "TestCase Name", plan: new Microsoft.TeamFoundation.TestManagement.WebApi.ShallowReference("TestPlan Id"), pointIds: new int[] { testpointid });
TestRun testrun = testClient.CreateTestRunAsync(run, teamProject).Result;
TestCaseResult caseResult = new TestCaseResult() { State = "Completed", Outcome = "passed", Id = 100000 };
var testResults = testClient.UpdateTestResultsAsync(new TestCaseResult[] { caseResult }, teamProject, testrun.Id).Result;
RunUpdateModel runmodel = new RunUpdateModel(state: "Completed");
TestRun testRunResult = testClient.UpdateTestRunAsync(runmodel, teamProject, testrun.Id, runmodel).Result;
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerException.Message);
}
I am using aws_ai plugin and the response is in the form of
instance of Future<String>
I read the response as given below. I need to access specific value from json with key "confidence", how do I access it?
Future main1() async {
File sourceImagefile; //load source image in this File object
String accessKey = "",
secretKey = "",
region = "" ;
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
Future<String> labelsArray = rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
}else{
return "Enter Image";}
}
___________________________________
(later in widget build:)
___________________________________
onpressed(){
main1().then((labelsArray){
print("json value is: "+labelsArray);
});
}
the current result is :
json value is: Instance of 'Future<String>'
thanks for the help!
The reason you are getting the Instance of 'Future<String>' as a result is you are not waiting for the future to return and just getting the Future<String> object back refer this for more details:
The below code should solve your problem:
Future<String> futureFunction() async {
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
var labelsArray = await rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
} else {
return "enter image";
}
}
I am trying to get and check values from database , don't want to use existing function like below .
public override async Task
GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
i want to check my own method and parameter instead of this method ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
Example: var user = await myclass.CheckResource(MAC,SerialNO, ProductKey);
Could you please suggest how to change it and return Token?
I haven't been able to find anything that will clearly explain how to use google compute engine through the .net API (specifically c#). Is there anyone that can point me to anything?
P.S. I know about the API reference (https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html)
I could not find any detailed tutorial with code samples, but official documentation is available at [1] includes a code sample.
There is a tutorial with C# sample specific for Google Drive at [2].
For your reference APIs documentation is available at [3] and the annotated library reference is available at [4].
Link:
[1] - https://developers.google.com/api-client-library/dotnet/get_started#examples
[2] - http://conficient.wordpress.com/2014/06/18/using-google-drive-api-with-c-part-1/
[3] - https://developers.google.com/compute/docs/reference/latest/
[4] - https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html
A list of steps you need to follow:
Specifically you can modify and use the following code to Create the vmInstance of Google Compute Engine
Here is the c# (using Google api SDK) functions that can create instances
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ClientId",
ClientSecret = "ClientSecret"
},
new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform },
"user",
CancellationToken.None, null);
`ComputeService service = new ComputeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ApplicationName",
ApiKey = "ApiKey"
});
public IEnumerable<CreateInstanceResult> CreateInstances(params CreateInstanceRequest[] instances)
{
IList<Instance> vmInstances = new List<Instance>();
ComputeService service = assign GoogleComputeServiceObject;
if (instances != null)
{
foreach (CreateInstanceRequest requestInstance in instances)
{
#region Meatadata Setting
Metadata metaData = new Metadata();
metaData.Items = new List<Metadata.ItemsData>();
Metadata.ItemsData itemData = new Metadata.ItemsData();
itemData.Key = "Expiration";
itemData.Value = requestInstance.Expiration.ToString();
metaData.Items.Add(itemData);
itemData = new Metadata.ItemsData();
itemData.Key = "AccountId";
itemData.Value = requestInstance.AccountId;
metaData.Items.Add(itemData);
if (requestInstance.Data != null)
{
foreach (KeyValuePair<string, string> keyValue in requestInstance.Data)
{
Metadata.ItemsData otherItemData = new Metadata.ItemsData();
otherItemData.Key = keyValue.Key;
otherItemData.Value = keyValue.Value;
metaData.Items.Add(otherItemData);
}
}
#endregion Meatadata Setting
#region DiskSetting
IList<AttachedDisk> attachedDisks = new List<AttachedDisk>();
AttachedDisk attachedDisk = new AttachedDisk();
AttachedDiskInitializeParams attachedDiskInitializeParams = new AttachedDiskInitializeParams();
attachedDiskInitializeParams.DiskSizeGb = googleCloudServerSetting.DiskSize;
attachedDiskInitializeParams.DiskType = service.BaseUri + "Your_ProjectId" + "/zones/" + "specifyZone" + "/diskTypes/" + "specify_DiskType";
// for example
attachedDiskInitializeParams.SourceImage = service.BaseUri + "/debian-cloud/global/images/specify_imagesourceImage";
attachedDisk.AutoDelete = true;
attachedDisk.Boot = true;
attachedDisk.Interface__ = "SCSI";//for example
attachedDisk.InitializeParams = attachedDiskInitializeParams;
attachedDisks.Add(attachedDisk);
IList<NetworkInterface> networkInterfaces = new List<NetworkInterface>();
NetworkInterface networkInterface = new NetworkInterface();
networkInterface.Network = service.BaseUri + ProjectId + "/global/networks/default";
networkInterfaces.Add(networkInterface);
Tags tags = new Tags();
IList<string> stringList = new List<string>();
tags.Items = new List<string>();
tags.Items.Add("http-server");
tags.Items.Add("https-server");
#endregion DiskSetting
#region Creating Instance object
Instance instance = new Instance()
{
MachineType = requestInstance.SizeId ?? service.BaseUri + "ProjectId" + "/zones/" + "specify_Zone" + "/machineTypes/" + "specify_machineType",
Metadata = metaData,
Name = "InstanceName",
Tags = tags,
NetworkInterfaces = networkInterfaces,
Disks = attachedDisks
};
#endregion Creating Instance object
vmInstances.Add(instance);
}
var batchRequest = new BatchRequest(service);
foreach (Instance instance in instances)
{
batchRequest.Queue<Instance>(service.Instances.Insert(instance, ProjectId, Zone),
(content, error, i, message) =>
{
});
}
await batchRequest.ExecuteAsync();
}
else
{
throw new Exception("null");
}
}