Microsoft Graph - Filtering in SDK C# - c#

Based on another post, I can filter via HTTP requests as follows:
https://graph.microsoft.com/v1.0/me/events?
$filter=categories/any(a:a+eq+'Red+Category')
I am not sure what the a:a stands for here but it works.
I want to replicate this in Microsoft Graph SDK, I am using a query option as per below which does not return any results:
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$filter",
"categories/any(a:a+eq+'Red+Category'")
};

You seem to be executing a search instead of a filter in your c# code.
Try using:
var request = graphClient.Users[userId].Events.Request().Filter("categories/any(a:a+eq+'Red+Category')");
var result = await request.GetAsync();
Or alternatively:
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$filter",
"categories/any(a:a+eq+'Red+Category')")
};

Related

Creating snapshot and export in new Azure SDK .NET - Azure.ResourceManager

Because old Azure SDK for .NET is deprecated, I'm trying to migrate it to new version. I've been stucked with finding substitions for old methods and properties in new SDK. We do a snapshot of existing database and export to Storage Account.
Snippet of old approach:
var sp = new ServicePrincipalLoginInformation()
{
ClientId = clientId,
ClientSecret = clientSecret
};
var credentials = new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud);
var azureClient = Authenticate(credentials).WithSubscription(subscriptionId);
var sqlServer = await azureClient.SqlServers.GetByIdAsync(db.SourceServerId);
var serverDbs = await sqlServer.Databases.ListAsync();
var snapshotDb = serverDbs.FirstOrDefault(i => i.Name == snapshotDbName);
if(snapshotDb is not null)
return;
snapshotDb = await azureClient.SqlServers.Databases
.Define(snapshotDbName)
.WithExistingSqlServer(sqlServer)
.WithSourceDatabase(sourceDatabaseId)
.WithMode(CreateMode.Copy)
.CreateAsync(cancellationToken);
.
.
.
var storageAccount = azureClient.StorageAccounts.GetByIdAsync(storageId);
await snapshotDb.ExportTo(storageAccount, storageContainer, outputFileName)
.WithSqlAdministratorLoginAndPassword(user, password)
.ExecuteAsync(cancellationToken);
According to documentation, I was able to get this:
var sp = new ClientSecretCredential(tenantId, clientId, clientSecret);
var azureClient = new ArmClient(sp, subscriptionId);
var ri = new ResourceIdentifier(NOT SURE WHAT SHOULD BE HERE);
var resGroup = azure.GetResourceGroupResource(ri);
var sqlServerResponse = await resGroup.GetSqlServers().GetAsync(sourceServerId);
var sqlServer = sqlServers.Value;
var serverDBs = sqlServer.GetSqlDatabases();
var snapshotDB = serverDBs.FirstOrDefault(x => x.Data.Name == db.SnapshotDbName);
What are substitution commands, which handle creating snapshot and exporting to Storage Account base on parameters used in deprecated sample? Or do I miss some Package?
We have a general guidance for using our latest version of .NET SDK against resource management.
Regarding your issue, you can refer to code below
var resourceGroup = _client.GetDefaultSubscription().GetResourceGroup(resourceGroupName).Value;
var sqlServer = resourceGroup.GetSqlServer("mySqlServerName").Value;
var sqlDB = sqlServer.GetSqlDatabase("myDbName").Value;
var exportResult= sqlDB.Export(Azure.WaitUntil.Completed, new Azure.ResourceManager.Sql.Models.DatabaseExportDefinition("storageKeyType", "storageKey", new Uri("storageUri"), "adminLogin", "adminLoginPWD")).Value;
The _client here is ArmClient object,
your code var ri = new ResourceIdentifier(NOT SURE WHAT SHOULD BE HERE); is not necessary, may I know why do you want to create a resource identifier here?
Please make sure you are using 1.1.0 version of Azure SDK for SQL libirary in .NET
We are open to any feedback regarding our new SDK, feel free to let us know your thoughts on our new SDK in this survey

In Google.Apis.Pagespeedonline.v5 how to get all categories in one call?

I am using Google.Apis.Pagespeedonline.v5 (nuget) to perform the analysis on my site.
By performing the analysis directly from the API Explorer site you can perform the test on all five categories.
https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed
However, using the dotnet api, the category parameter only accepts one CategoryEnum, so, I can only get the result in one category per request.
I wonder if it is possible to get all categories in a single request
var initializer = new Initializer()
{
ApiKey = "XXXXXXXXXXXXXXX",
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed",
GZipEnabled = true
};
var service = new PagespeedonlineService(initializer);
var request = new RunpagespeedRequest(service, "https://www.google.com");
request.Category = CategoryEnum.Accessibility;
request.Locale = "pt";
request.Strategy = StrategyEnum.Desktop;
var response = request.Execute();
Well, you can do it this way:
GET https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE&locale=pt&strategy=DESKTOP&url=https%3A%2F%2Fwww.google.com%2F&prettyPrint=true&key=[YOUR_API_KEY] HTTP/1.1
But in your situation maybe you can change base URL to look like:
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE"
Give it a try this way

How to use SQL query with CosmosDB client in C# .NET Core 2.1 API app

I am trying to use an Azure CosmosDB (former DocumentDB) repository in an API I am creating (I'm quite new to C#). I have managed to get a result with all documents using the client.CreateDocumentQuery method without passing a SQL query to it. However, when I pass a SQL query, program execution hangs and the controller responds with 404. I've tried to add a try-catch around it but I get no exception or anything.
Using Microsoft.Azure.DocumentDB.Core Version 1.9.1.
I've tried many things, other methods and also LINQ, but got nothing to work. If you have a look at this sample method, could you give me an example on how to correctly query and get a result from the document collection? I would really appreciate it!UPDATE: I updated the SQL a bit. Have tried with hard coded parameter and have tested it in the data explorer where it works. Execution seems to freeze on *var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();*
// Document repository
public async Task<IEnumerable<JObject>> GetDocsFromCollectionAsync(string someId)
{
DocumentClient client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
IDocumentQuery<JObject> documentQuery;
var documentCollectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
var queryOptions = new FeedOptions { MaxItemCount = -1 };
if (someId.IsNullOrEmpty())
{
// This works
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri,queryOptions)
.AsDocumentQuery();
}
else
{
var query = new SqlQuerySpec(
"SELECT * FROM c WHERE c.someId = #someId",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "#someId", Value = someId } }));
// This hangs during execution / returns 404 in the API controller
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri, query, queryOptions)
.AsDocumentQuery();
}
List<JObject> documents = new List<JObject>();
while (documentQuery.HasMoreResults)
{
var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();
documents.AddRange(feedResponse);
}
return documents; // Return documents to API controller
}

AdWords API in ASP.NET. Can I avoid using the `user` object?

The story is: I am building a Node application, but I need data from Google AdWords. Since there is no official Node library and I couldn't get the unofficial ones to work I wanted to create a REST API in ASP.NET. So far this is what I have:
[HttpGet]
public IEnumerable<string> Get()
{
TargetingIdeaSelector selector = new TargetingIdeaSelector
{
requestType = RequestType.IDEAS,
ideaType = IdeaType.KEYWORD,
requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
}
};
// Set selector paging (required for targeting idea service).
Paging paging = Paging.Default;
// Create related to query search parameter.
RelatedToQuerySearchParameter relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter
{
queries = new String[] {
"bakery", "pastries", "birthday cake"
}
};
var searchParameters = new List<SearchParameter>
{
relatedToQuerySearchParameter
};
TargetingIdeaPage page = new TargetingIdeaPage();
page = targetingIdeaService.get(selector);
return new string[] { "value1", "value2" };
}
I basically grabbed the code from the docs. The problem is that the targetingIdeaService is not defined. If I try to take a look at a code sample it looks like this:
public void Run(AdWordsUser user, long? adGroupId) {
using (TargetingIdeaService targetingIdeaService =
(TargetingIdeaService) user.GetService(AdWordsService.v201802.TargetingIdeaService)) {
// Create selector.
TargetingIdeaSelector selector = new TargetingIdeaSelector();
selector.requestType = RequestType.IDEAS;
selector.ideaType = IdeaType.KEYWORD;
selector.requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
};
List<SearchParameter> searchParameters = new List<SearchParameter>();
// Create related to query search parameter.
RelatedToQuerySearchParameter relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter();
relatedToQuerySearchParameter.queries = new String[] {
"bakery", "pastries", "birthday cake"
};
searchParameters.Add(relatedToQuerySearchParameter);
And a lot more code. The point is they made it in a function, and are passing a user object into it. Now I will not have said object. Unless it's needed. Then I'm screwed. But I need to get this service up and running. This is the only missing step, other than that it should work.
So my question is: Does anyone see a way around it?
The AdWordsUser object contains the authentication you need to connect to the API. Without it your app will have no idea of which AdWords account and OAuth refresh token to supply to the TargetingIdeaService.

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

Categories

Resources