Retrieving Connection String when Creating ServiceBus with Pulumi (AzureNative) - c#

I create a Servicebus-Namespace using AzureNative on Pulumi:
public void CreateNamespace(string namespaceName, SkuName skuname, SkuTier tier)
{
var namespace = new Namespace(namespaceName, new NamespaceArgs
{
Location = _resourceGroup.Location,
NamespaceName = namespaceName,
ResourceGroupName = _resourceGroup.Name,
Sku = new Pulumi.AzureNative.ServiceBus.Inputs.SBSkuArgs
{
Name = skuname,
Tier = tier
}
});
}
The Servicebus Namespace is created correctly. After creating the Servicebus-Namespace I need to retrieve the ConnectionString for this resource. Either for the automatically created RootManageSharedAccessKey or alternatively by creating a specific additional policy for that task.
Within the Azure Portal I can retrieve the Key by navigating through
Settings/Shared access policies/Policy/ and copying the Primary access key from there.
I did not find any property or function within the AzureNative.ServiceBus - Namespace that seem to lead to that key. Any way to retrieve that property?

I solved it by creating a new NamespaceRule and return ListNamespaceKeys-Properties:
var namespaceRule = new NamespaceAuthorizationRule(rulename, new NamespaceAuthorizationRuleArgs
{
AuthorizationRuleName = rulename,
NamespaceName = namespace.Name,
ResourceGroupName = _resourceGroup.Name,
Rights = new[]
{
AccessRights.Listen,
AccessRights.Send
}
});
var nameSpaceKeys = Output
.Tuple(namespace.Name, namespaceRule.Name)
.Apply(t => ListNamespaceKeys.InvokeAsync(new ListNamespaceKeysArgs
{
NamespaceName = t.Item1,
AuthorizationRuleName = t.Item2,
ResourceGroupName = _resourceGroup.GetResourceName()
}));
Now NamespaceKeys contains all the required Properties like PrimaryConnectionString etc.

Related

C# AWS CDK Serverless, publish new version Lambda and create new API resource

I'm new to AWS CDK and what I'm trying to accomplish (using C#) is to version my lambda function, and then create a new API resource referencing the version.
For example: The program accepts a version parameter.
internal CdkAppStack(Construct scope, string id, IStackProps props, string bucketName, string functionName, string version) : base(scope, id, props)
{
var bucket = new Bucket(this, bucketName, new BucketProps {
BucketName = bucketName
});
var handler = new Function(this, $"{functionName}Handler", new FunctionProps
{
Runtime = Runtime.DOTNET_CORE_3_1,
Code = Code.FromAsset("Lambdas\\src\\Lambdas\\bin\\Debug\\netcoreapp3.1"),
Handler = "Lambdas::Lambdas.Function::FunctionHandler",
Environment = new Dictionary<string, string>
{
["BUCKET"] = bucket.BucketName,
},
FunctionName = functionName
});
string apiName = !string.IsNullOrEmpty(version) ? $"{functionName}-{version}" : functionName;
bucket.GrantReadWrite(handler);
var api = new RestApi(this, $"{apiName}-API", new RestApiProps
{
RestApiName = $"{apiName}API",
Description = $"This service the Lambda - {functionName}.",
RetainDeployments = true
});
var getWidgetsIntegration = new LambdaIntegration(handler, new LambdaIntegrationOptions
{
RequestTemplates = new Dictionary<string, string>
{
["application/json"] = "{ \"statusCode\": \"200\" }"
}
});
string resource = !string.IsNullOrEmpty(version) ? $"execute-{version}" : "execute";
var helloWorldResource = api.Root.AddResource(resource);
var method = helloWorldResource.AddMethod("POST", getWidgetsIntegration);
}
Actual result:
It overrides the lambda and api resource.
Expected result:(version parameter is 3). Added new resource (execute-3)
AWS Console - Expected result
For the given code the process probably looks like this:
Current provisioned state includes execute-2
CDK synthesizes a Cloudformation template where execute-3 exists and execute-2 does not exist.
Cloudformation figures out that in order to reach the desired state (described in the template) it needs to delete execute-2 and provision execute-3.
If you literally want to reach what you are describing you will have to add resources and not delete previously provisioned ones (say write a loop that runs over 1..version and adds all past versions)
Another (less recommendable) option is to use a deletion policy. This way you can hint cloudformation not the delete execute-2 (the downside here is that execute-2's lifecycle is no longer managed by any stack --> you will have to manage changes to it manually)

Usage of GetApiKeys in Amazon SDK

I am trying to get the total count of api keys in my API gateway via SDK.
However I am unsure on the proper implementation of the parameters that the GetApiKeysRequest takes in. My main objective is to get the count of all API keys that are already existing for my account.
The code I have so far looks like this :
class Program
{
public static void Main(string[] args)
{
var awsUserAccessKey = "xxxxx";
var awsUserSecretKey = "yyyyyyyyyyy";
var regionEndpoint = "us-west-2";
var keysInRepository = new GetApiKeysRequest
{
CustomerId = "",
IncludeValues = true||false,
Limit=0,
NameQuery = "",
Position = ""
};
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys =client.GetApiKeys(keysInRepository);
Console.Read();
}
}
This code throws an error saying that The security token included in the request is invalid (Amazon.APIGateway exception).I am unsure on how to set the parameters for this request.
Because the AmazonAPIGatewayClient you are using as described here takes three string arguments and the last one is awsSessionToken i think you are confusing with this one which takes as third argument RegionEndpoint
Do something like that instead :
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, RegionEndpoint.USWest2);
For someone looking for a solution to similar problems, this worked :
var awsUserAccessKey = "xxxx";
var awsUserSecretKey = "yyyyy";
var regionEndpointName = "us-west-2";
var regionEndpoint = RegionEndpoint.GetBySystemName(regionEndpointName);
var keysInRepository = new GetApiKeysRequest
{
Limit = 500
};
//define the key and its fields
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys = client.GetApiKeys(keysInRepository);
Console.WriteLine("Current number of api keys:{0}", apiKeys.Items.Count);

C# Save Data To Database and Exit Program

Hey Guys i have a script written in c# that generates some encryption keys that i want to save into my database my code looks like this:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.WindowsAzure.MediaServices.Client;
using Microsoft.WindowsAzure.MediaServices.Client.ContentKeyAuthorization;
using Microsoft.WindowsAzure.MediaServices.Client.DynamicEncryption;
using Microsoft.WindowsAzure.MediaServices.Client.Widevine;
using Newtonsoft.Json;
namespace DeliverDRMLicenses
{
class Program
{
// Read values from the App.config file.
private static readonly string _mediaServicesAccountName =
ConfigurationManager.AppSettings["MediaServicesAccountName"];
private static readonly string _mediaServicesAccountKey =
ConfigurationManager.AppSettings["MediaServicesAccountKey"];
private static readonly Uri _sampleIssuer =
new Uri(ConfigurationManager.AppSettings["Issuer"]);
private static readonly Uri _sampleAudience =
new Uri(ConfigurationManager.AppSettings["Audience"]);
// Field for service context.
private static CloudMediaContext _context = null;
private static MediaServicesCredentials _cachedCredentials = null;
static void Main(string[] args)
{
// Create and cache the Media Services credentials in a static class variable.
_cachedCredentials = new MediaServicesCredentials(
_mediaServicesAccountName,
_mediaServicesAccountKey);
// Used the cached credentials to create CloudMediaContext.
_context = new CloudMediaContext(_cachedCredentials);
bool tokenRestriction = true;
string tokenTemplateString = null;
string drm_key_id = null;
IContentKey key = CreateCommonTypeContentKey();
// Print out the key ID and Key in base64 string format
drm_key_id = key.Id;
Console.WriteLine(" key:{0}",
key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));
Console.WriteLine(" key value:{1} ",
key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));
sbasedrmdataDataSetTableAdapters.sbase_drm_keysTableAdapter sbasedrmTableAdapter =
new sbasedrmdataDataSetTableAdapters.sbase_drm_keysTableAdapter();
sbasedrmTableAdapter.Insert(drm_key_id);
Console.WriteLine("Protection key: {0} ",
key.ProtectionKeyId, System.Convert.ToBase64String(key.GetClearKeyValue()));
Console.WriteLine("PlayReady URL: {0}",
key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));
Console.WriteLine("Widevin URL: {0}",
key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine));
if (tokenRestriction)
tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);
else
AddOpenAuthorizationPolicy(key);
Console.WriteLine("Auth policy: {0}",
key.AuthorizationPolicyId);
Console.WriteLine();
Console.ReadLine();
Environment.Exit(0);
}
static public void AddOpenAuthorizationPolicy(IContentKey contentKey)
{
// Create ContentKeyAuthorizationPolicy with Open restrictions
// and create authorization policy
List<ContentKeyAuthorizationPolicyRestriction> restrictions =
new List<ContentKeyAuthorizationPolicyRestriction>
{
new ContentKeyAuthorizationPolicyRestriction
{
Name = "Open",
KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
Requirements = null
}
};
// Configure PlayReady and Widevine license templates.
string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();
string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();
IContentKeyAuthorizationPolicyOption PlayReadyPolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("",
ContentKeyDeliveryType.PlayReadyLicense,
restrictions, PlayReadyLicenseTemplate);
IContentKeyAuthorizationPolicyOption WidevinePolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("",
ContentKeyDeliveryType.Widevine,
restrictions, WidevineLicenseTemplate);
IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
ContentKeyAuthorizationPolicies.
CreateAsync("Deliver Common Content Key with no restrictions").
Result;
contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);
// Associate the content key authorization policy with the content key.
contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
contentKey = contentKey.UpdateAsync().Result;
}
public static string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
{
string tokenTemplateString = GenerateTokenRequirements();
List<ContentKeyAuthorizationPolicyRestriction> restrictions =
new List<ContentKeyAuthorizationPolicyRestriction>
{
new ContentKeyAuthorizationPolicyRestriction
{
Name = "Token Authorization Policy",
KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
Requirements = tokenTemplateString,
}
};
// Configure PlayReady and Widevine license templates.
string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();
string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();
IContentKeyAuthorizationPolicyOption PlayReadyPolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
ContentKeyDeliveryType.PlayReadyLicense,
restrictions, PlayReadyLicenseTemplate);
IContentKeyAuthorizationPolicyOption WidevinePolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
ContentKeyDeliveryType.Widevine,
restrictions, WidevineLicenseTemplate);
IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
ContentKeyAuthorizationPolicies.
CreateAsync("Deliver Common Content Key with token restrictions").
Result;
contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);
// Associate the content key authorization policy with the content key
contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
contentKey = contentKey.UpdateAsync().Result;
return tokenTemplateString;
}
static private string GenerateTokenRequirements()
{
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);
template.PrimaryVerificationKey = new SymmetricVerificationKey();
template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
template.Audience = _sampleAudience.ToString();
template.Issuer = _sampleIssuer.ToString();
template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
return TokenRestrictionTemplateSerializer.Serialize(template);
}
static private string ConfigurePlayReadyLicenseTemplate()
{
// The following code configures PlayReady License Template using .NET classes
// and returns the XML string.
//The PlayReadyLicenseResponseTemplate class represents the template
//for the response sent back to the end user.
//It contains a field for a custom data string between the license server
//and the application (may be useful for custom app logic)
//as well as a list of one or more license templates.
PlayReadyLicenseResponseTemplate responseTemplate =
new PlayReadyLicenseResponseTemplate();
// The PlayReadyLicenseTemplate class represents a license template
// for creating PlayReady licenses
// to be returned to the end users.
// It contains the data on the content key in the license
// and any rights or restrictions to be
// enforced by the PlayReady DRM runtime when using the content key.
PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
// Configure whether the license is persistent
// (saved in persistent storage on the client)
// or non-persistent (only held in memory while the player is using the license).
licenseTemplate.LicenseType = PlayReadyLicenseType.Nonpersistent;
// AllowTestDevices controls whether test devices can use the license or not.
// If true, the MinimumSecurityLevel property of the license
// is set to 150. If false (the default),
// the MinimumSecurityLevel property of the license is set to 2000.
licenseTemplate.AllowTestDevices = true;
// You can also configure the Play Right in the PlayReady license by using the PlayReadyPlayRight class.
// It grants the user the ability to playback the content subject to the zero or more restrictions
// configured in the license and on the PlayRight itself (for playback specific policy).
// Much of the policy on the PlayRight has to do with output restrictions
// which control the types of outputs that the content can be played over and
// any restrictions that must be put in place when using a given output.
// For example, if the DigitalVideoOnlyContentRestriction is enabled,
//then the DRM runtime will only allow the video to be displayed over digital outputs
//(analog video outputs won’t be allowed to pass the content).
// IMPORTANT: These types of restrictions can be very powerful
// but can also affect the consumer experience.
// If the output protections are configured too restrictive,
// the content might be unplayable on some clients.
// For more information, see the PlayReady Compliance Rules document.
// For example:
//licenseTemplate.PlayRight.AgcAndColorStripeRestriction = new AgcAndColorStripeRestriction(1);
responseTemplate.LicenseTemplates.Add(licenseTemplate);
return MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
}
private static string ConfigureWidevineLicenseTemplate()
{
var template = new WidevineMessage
{
allowed_track_types = AllowedTrackTypes.SD_HD,
content_key_specs = new[]
{
new ContentKeySpecs
{
required_output_protection =
new RequiredOutputProtection { hdcp = Hdcp.HDCP_NONE},
security_level = 1,
track_type = "SD"
}
},
policy_overrides = new
{
can_play = true,
can_persist = true,
can_renew = false
}
};
string configuration = JsonConvert.SerializeObject(template);
return configuration;
}
static public IContentKey CreateCommonTypeContentKey()
{
// Create envelope encryption content key
Guid keyId = Guid.NewGuid();
byte[] contentKey = GetRandomBuffer(16);
IContentKey key = _context.ContentKeys.Create(
keyId,
contentKey,
"ContentKey",
ContentKeyType.CommonEncryption);
return key;
}
static private byte[] GetRandomBuffer(int length)
{
var returnValue = new byte[length];
using (var rng =
new System.Security.Cryptography.RNGCryptoServiceProvider())
{
rng.GetBytes(returnValue);
}
return returnValue;
}
}
}
So the issue im having is when i try to run the program i get an error at this line
sbasedrmTableAdapter.Insert(drm_key_id);
and the error i receive is:
Error CS7036 There is no argument given that corresponds to the
required formal parameter 'drm_key' of
'sbase_drm_keysTableAdapter.Insert(string, string, string, string)'
How can i solve this error
It looks like you are trying to call a method that requires 4 strings as parameters with just one parameter. Try supplying the correct parameters to the method.
Your problem looks quite similar to: OOP inheritance and default constructor

RavenDB throws a JSON deserialisation error when retrieving document

I've just completed a round of refactoring of my application, which has resulted in my removing a project that was no longer required and moving its classes into a different project. A side effect of this is that my User class, which is stored in RavenDB, has a collection property of a type moved to the new assembly. As soon as I attempt to query the session for the User class I get a Json deserialisation error. The issue is touched upon here but the answers don't address my issue. Here's the offending property:
{
"OAuthAccounts": {
"$type": "System.Collections.ObjectModel.Collection`1[
[Friendorsement.Contracts.Membership.IOAuthAccount,
Friendorsement.Contracts]], mscorlib",
"$values": []
},
}
OAuthAccounts is a collection property of User that used to map here:
System.Collections.ObjectModel.Collection`1[[Friendorsement.Contracts.Membership.IOAuthAccount, Friendorsement.Contracts]]
It now maps here:
System.Collections.ObjectModel.Collection`1[[Friendorsement.Domain.Membership.IOAuthAccount, Friendorsement.Domain]]
Friendorsement.Contracts no longer exists. All of its types are now in Friendorsement.Domain
I've tried using store.DatabaseCommands.StartsWith("User", "", 0, 128) but that didn't return anything.
I've tried looking at UpdateByIndex but not got very far with it:
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new[]
{
new PatchRequest { // unsure what to set here }
});
I'm using Raven 2.0
Below is a simple sample application that shows you the patching Metadata. While your example is a little different this should be a good starting point
namespace SO19941925
{
internal class Program
{
private static void Main(string[] args)
{
IDocumentStore store = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "SO19941925"
}.Initialize();
using (IDocumentSession session = store.OpenSession())
{
for (int i = 0; i < 10; i++)
{
session.Store(new User {Name = "User" + i});
}
session.SaveChanges();
}
using (IDocumentSession session = store.OpenSession())
{
List<User> users = session.Query<User>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();
Console.WriteLine("{0} SO19941925.Users", users.Count);
}
Operation s = store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new ScriptedPatchRequest
{
Script = #"this['#metadata']['Raven-Clr-Type'] = 'SO19941925.Models.User, SO19941925';"
}, true
);
s.WaitForCompletion();
using (IDocumentSession session = store.OpenSession())
{
List<Models.User> users =
session.Query<Models.User>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();
Console.WriteLine("{0} SO19941925.Models.Users", users.Count);
}
Console.ReadLine();
}
}
internal class User
{
public string Name { get; set; }
}
}
namespace SO19941925.Models
{
internal class User
{
public string Name { get; set; }
}
}
UPDATE: Based on the initial answer above, here is the code that actually solves the OP question:
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new ScriptedPatchRequest
{
Script = #"this['OAuthAccounts']['$type'] =
'System.Collections.ObjectModel.Collection`1[
[Friendorsement.Domain.Membership.IFlexOAuthAccount,
Friendorsement.Domain]], mscorlib';",
}, true
);
Here are two possible solutions:
Option 1: Depending on what state your project is in, for example if you are still in development, you could easily just delete that collection out of RavenDB from the Raven Studio and recreate all those User documents. All the new User documents should then have the correct class name and assembly and should then deserialize correctly. Obviously, if you are already in production, this probably won't be a good option.
Option 2: Depending on how many User documents you have, you should be able to manually edit each one to specify the correct C# class name and assembly, so that they will be deserialized correctly. Again, if you have too many objects to manually modify, this may not be a good option; however, if there are just a few, it shouldn't be too bad to open each one up go to the metadata tab and paste the correct value for "Raven-Entity-Name" and "Raven-Clr-Type".
I ended up doing this:
Advanced.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Album"},
new []{ new PatchRequest() {
Type = PatchCommandType.Modify,
Name = "#metadata",
Nested= new []{
new PatchRequest{
Name= "Raven-Clr-Type",
Type = PatchCommandType.Set,
Value = "Core.Model.Album, Core" }}}},
false);

How to get all the documents in a folder in Google Docs

I can get all the documents in Google Docs using
public DocumentsFeed GetDocs()
{
DocumentsListQuery query = new DocumentsListQuery();
DocumentsFeed feed = service.Query(query);
return feed;
}
But how can I get the documents in a particular folder? I wan to discover the list of folders and then populate the folders in a tree view. On selection of a folder, I shall like to get the documents in that folder.
To get the folder, I am using
public DocumentsFeed GetFolders()
{
FolderQuery query = new FolderQuery("root"); //http://docs.google.com/feeds/documents/private/full
DocumentsFeed feed = service.Query(query);
return feed;
}
For the service, I am using private DocumentsService service;
Can somebody help?
Another guy using the API has described how he does it:
var docService = new DocumentsService("company-app-version");
docService.setUserCredentials("username", "password");
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
// snipped method declaration etc
var docService = new DocumentsService("company-app-version");
docService.setUserCredentials("username", "password");
var folderList = docService.Query(new FolderQuery());
var fLinks = folderList.Entries.Select(e =>
new
{
// note how to get the document Id of the folder
Id = DocumentsListQuery.DocumentId(e.Id.AbsoluteUri),
Name = e.Title.Text
});
foreach (var folder in fLinks)
{
Console.WriteLine("Folder {0}", folder.Name);
var fileList = docService.Query(
new SpreadsheetQuery()
{
// setting the base address to the folder's URI restricts your results
BaseAddress = DocumentsListQuery.folderBaseUri + folder.Id
});
foreach (var file in fileList.Entries)
{
Console.WriteLine(" - {0}", file.Title.Text);
}
}
Source:
http://jtnlex.com/blog/2010/06/09/google-docs-api-get-all-spreadsheetsdocs-in-a-folder/
Here's how :
instead of typing the name of the folder , use the resourceID of the folder query = new FolderQuery(FolderEntry.ResourceId);
But first you need to get ALL documents in the root and enable showing folders : query.ShowFolders = true; , that's how you get the resourceId's of the docs in the root and
folders!
Hope this helps !

Categories