Amazon Translate - Formality Setting in .Net? - amazon

When trying to use the Formality setting (https://aws.amazon.com/about-aws/whats-new/2022/10/amazon-translate-formality-customization-support-dutch-korean-mexican-spanish/ ) in code behind (.Net), I keep getting System.NullReferenceException: 'Object reference not set to an instance of an object.'
Here's the code I'm running - everything works as expected until I add in request.Settings.Formality = "FORMAL";`
using (var client = new AmazonTranslateClient(awsCredentials, selectedRegion))
{
var request = new Amazon.Translate.Model.TranslateTextRequest();
request.Text = toTranslate;
request.SourceLanguageCode = sourceLanguage;
request.TargetLanguageCode = translateLanguage;
request.Settings.Formality = "FORMAL";
`Looking at the limited examples in other languages from the AWS documentation doesn't indicate anything else that's needed. I also tried the Profanity setting and the same results - System.NullReferenceException.
I also tried making the call later via the using statement that looks like this with the same error:`
var response = client.TranslateTextAsync(request).GetAwaiter().GetResult();
response.AppliedSettings.Formality = translationFormality;
`

Updated code with solution that worked for me:
using (var client = new AmazonTranslateClient(awsCredentials, selectedRegion))
{
var request = new Amazon.Translate.Model.TranslateTextRequest();
request.Text = toTranslate;
request.SourceLanguageCode = sourceLanguage; // SourceLanguageItem.LanguageCode;
request.TargetLanguageCode = translateLanguage; // TranslateLanguageItem.LanguageCode;
TranslationSettings settings = new TranslationSettings();
settings.Formality = "FORMAL";
request.Settings = settings;

Related

How can I extract the SAN's inside a .csr file in node.js (Serverless Framework)?

Using Serverless Framework with node.js, I need to read information inside a .csr file received via http POST. Using the node-forge module, and with the following code, I was able to extract the different information that composes the certificate signing request:
const forge = require('node-forge');
...
var csr = forge.pki.certificationRequestFromPem(cert);
console.log(csr.subject.attributes)
if(csr.subject.getField('CN'))
var CN = csr.subject.getField('CN').value
if(csr.subject.getField('SAN'))
var SAN = csr.subject.getField('SAN').value
if(csr.subject.getField('O'))
var O = csr.subject.getField('O').value
if(csr.subject.getField('OU'))
var OU = csr.subject.getField('OU').value
if(csr.subject.getField('C'))
var C = csr.subject.getField('C').value
if(csr.subject.getField('ST'))
var S = csr.subject.getField('ST').value
if(csr.subject.getField('L'))
var L = csr.subject.getField('L').value
if(csr.subject.getField('E'))
var E = csr.subject.getField('E').value
What I need right now is to also extract the SAN's of the CSR if they exist, problem is that after inspecting the x509.js file ("Javascript implementation of X.509 and related components (such as
Certification Signing Requests) of a Public Key Infrastructure") that comes within the module, I dot not think there is a way to extract the SAN's:
// short name OID mappings
var _shortNames = {};
_shortNames['CN'] = oids['commonName'];
_shortNames['commonName'] = 'CN';
_shortNames['C'] = oids['countryName'];
_shortNames['countryName'] = 'C';
_shortNames['L'] = oids['localityName'];
_shortNames['localityName'] = 'L';
_shortNames['ST'] = oids['stateOrProvinceName'];
_shortNames['stateOrProvinceName'] = 'ST';
_shortNames['O'] = oids['organizationName'];
_shortNames['organizationName'] = 'O';
_shortNames['OU'] = oids['organizationalUnitName'];
_shortNames['organizationalUnitName'] = 'OU';
_shortNames['E'] = oids['emailAddress'];
_shortNames['emailAddress'] = 'E';
Am I using a deprecated module or old version? Is there a way for me to achieve this and I'm simply using the incorrect stuff inside node-forge?
Please let me know if anyone had a similar problem or was able to overcome this issue. Regards
So, I was able to solve this with the following code:
var csr = forge.pki.certificationRequestFromPem(cert);
var altNames = csr.attributes.find(t=>t.name === 'extensionRequest').extensions.find(t=>t.name === 'subjectAltName').altNames;
I created a dummy certificate with SANs and Apparently node-forge extracts that information and places them inside extensionRequest -> subjectAltNames. I have these hardcoded since I'm assuming these attribute names will not change, but I can't be 100% sure about it.
Hope this helps someone who might have gone through this issue. Thank you.

Setting CORS rules using Azure.Storage.Blobs

I'm trying to migrate from the deprecated Microsoft.WindowsAzure.Storage to Azure.Storage. In my API app, I have a method that I call occasionally to programmatically set the CORS rules in my Azure Storage account.
How do I add CORS rules to the properties using the new Azure.Storage.Blobs?
My original code that worked under Microsoft.WindowsAzure.Storage is as follows. In the following code, the _client is an instance of CloudBlobClient. I understand that in Azure.Storage.Blobs, I need to use BlobServiceClient which I now do but as I said, some parts of the following code are not working because some methods/properties are no longer there. I'm sure they're moved somewhere else but I haven't been able to figure out where.
public async Task ConfigureCors()
{
var ALLOWED_CORS_ORIGINS = new List<String> { "http://localhost:49065", "https://myappdomain.com", "https://www.myappdomain", "https://login.microsoftonline.com" };
var ALLOWED_CORS_HEADERS = new List<String> { "x-ms-meta-qqfilename", "Content-Type", "x-ms-blob-type", "x-ms-blob-content-type" };
const CorsHttpMethods ALLOWED_CORS_METHODS = CorsHttpMethods.Get | CorsHttpMethods.Delete | CorsHttpMethods.Put | CorsHttpMethods.Options;
const int ALLOWED_CORS_AGE_DAYS = 5;
var properties = await _client.GetServicePropertiesAsync();
properties.DefaultServiceVersion = "2013-08-15";
await _client.SetServicePropertiesAsync(properties);
var addRule = true;
if (addRule)
{
var ruleWideOpenWriter = new CorsRule()
{
AllowedHeaders = ALLOWED_CORS_HEADERS,
AllowedOrigins = ALLOWED_CORS_ORIGINS,
AllowedMethods = ALLOWED_CORS_METHODS,
MaxAgeInSeconds = (int)TimeSpan.FromDays(ALLOWED_CORS_AGE_DAYS).TotalSeconds
};
properties.Cors.CorsRules.Clear();
properties.Cors.CorsRules.Add(ruleWideOpenWriter);
await _client.SetServicePropertiesAsync(properties);
}
}
Looks like I can get and set properties by changing _client.GetServicePropertiesAsync() to _client.GetPropertiesAsync() but DefaultServiceVersion is no longer there. Also I can't seem to find the right way to set CORS rules.
I'd appreciate your suggestions. Thanks!
You can use the code below when using Azure.Storage.Blobs(I'm using sync method, please change it to async method if you need that):
var properties = blobServiceClient.GetProperties().Value;
properties.DefaultServiceVersion = "xxx";
BlobCorsRule rule = new BlobCorsRule();
rule.AllowedHeaders= "x-ms-meta-qqfilename,Content-Type,x-ms-blob-type,x-ms-blob-content-type";
rule.AllowedMethods = "GET,DELETE,PUT,OPTIONS";
rule.AllowedOrigins = "http://localhost:49065,https://myappdomain.com,https://www.myappdomain,https://login.microsoftonline.com";
rule.MaxAgeInSeconds = 3600; // in seconds
properties.Cors.Add(rule);
blobServiceClient.SetProperties(properties);

Azure SendGrid DeliverAsync works but not Deliver

I wired up SendGrid using their documentation as a guide. Nothing fancy here, just want to fire off an email for certain events. Looking at the code below, the SendGrid documentation directs me to use transportWeb.Deliver(message) but this results in "cannot resolve symbol Deliver" However if I use DeliverAsync everything works fine. Just seems sloppy to define a variable that is never used.
SendGridMessage message = new SendGridMessage();
message.AddTo(to);
message.From = new MailAddress(from);
message.Subject = subject;
message.Text = body;
var uid = AppConfigSettings.SendGridUid;
var pw = AppConfigSettings.SendGridPw;
var credentials = new NetworkCredential(uid, pw);
var transportWeb = new Web(credentials);
// transportWeb.Deliver(message); // "Deliver" won't resolve
var result = transportWeb.DeliverAsync(message);
Deliver() was removed in the most recent version of the library. Can you link me to the docs that are out of date?

How to use Servicestack PostFileWithRequest

I am trying to figure out how to post a file to my webservice using servicestack. I have the following code in my client
Dim client As JsonServiceClient = New JsonServiceClient(api)
Dim rootpath As String = Server.MapPath(("~/" + "temp"))
Dim filename As String = (Guid.NewGuid.ToString.Substring(0, 7) + FileUpload1.FileName)
rootpath = (rootpath + ("/" + filename))
FileUpload1.SaveAs(rootpath)
Dim fileToUpload = New FileInfo(rootpath)
Dim document As AddIDVerification = New AddIDVerification
document.CountryOfIssue = ddlCountry.SelectedValue
document.ExpiryDate = DocumentExipiry.SelectedDate
document.VerificationMethod = ddlVerificationMethod.SelectedValue
Dim responseD As MTM.DTO.AddIDVerificationResponse = client.PostFileWithRequest(Of DTO.AddIDVerificationResponse)("http://localhost:50044/images/", fileToUpload, document)
But no matter what I do I get the error message "Method not allowed". At the moment the server code is written like this
Public Class AddIDVerificationService
Implements IService(Of DTO.AddIDVerification)
Public Function Execute(orequest As DTO.AddIDVerification) As Object Implements ServiceStack.ServiceHost.IService(Of DTO.AddIDVerification).Execute
Return New DTO.AddIDVerificationResponse With {.Result = "success"}
End Function
End Class
As you can see I have not tried to process the file on the server yet. I just want to test the client to make sure it can actually send the file to the server. Any ideas what I am doing wrong?
Firstly you're using ServiceStack's Old and now deprecated API, consider moving to ServiceStack's New API for creating future services.
You can look at ServiceStack's RestFiles example project for an example of handling file uploads:
foreach (var uploadedFile in base.RequestContext.Files)
{
var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName);
uploadedFile.SaveTo(newFilePath);
}
Which is able to access the collection of uploaded files by inspecting the injected RequestContext.
An example of uploading a file is contained in the RestFiles integration tests:
var client = new JsonServiceClient(api);
var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");
var response = restClient.PostFile<FilesResponse>(
"files/Uploads/",fileToUpload,MimeTypes.GetMimeType(fileToUpload.Name));

Apache Thrift with nodejs example

I am trying to use Apache Thrift for passing messages between applications implemented in different languages. It is not necessarily used as RPC, but more for serializing/deserializing messages.
One application is in node.js. I am trying to figure out how Apache thrift works with node.js, but I can't find too much documentation and examples, except for one tiny one regarding Cassandra at:
https://github.com/apache/thrift/tree/trunk/lib/nodejs
Again, I don't need any procedures declared in the .thrift file, I only need to serialize a simple data structure like:
struct Notification {
1: string subject,
2: string message
}
Can anyone help me with an example?
I finally found the answer to this question, after wasting a lot of time just by looking at the library for nodejs.
//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);
At this point, the byte array can be found in the transport.outBuffers field:
var byteArray = transport.outBuffers;
For deserialization:
var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);
Also the following lines need to be added to the index.js file from the nodejs library for thrift:
exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;
Plus there is also at least one bug in the nodejs library.
The above answer is wrong, because it tries to use outBuffers directly, which is an array of buffers. Here is a working example of using thrift with nodejs:
var util = require('util');
var thrift = require('thrift');
var Notification = require('./gen-nodejs/notification_types.js').Notification;
var TFramedTransport = require('thrift/lib/thrift/transport').TFramedTransport;
var TBufferedTransport = require('thrift/lib/thrift/transport').TBufferedTransport;
var TBinaryProtocol = require('thrift/lib/thrift/protocol').TBinaryProtocol;
var transport = new TFramedTransport(null, function(byteArray) {
// Flush puts a 4-byte header, which needs to be parsed/sliced.
byteArray = byteArray.slice(4);
// DESERIALIZATION:
var tTransport = new TFramedTransport(byteArray);
var tProtocol = new TBinaryProtocol(tTransport);
var receivedNotification = new Notification();
receivedUser.read(tProtocol);
console.log(util.inspect(receivedNotification, false, null));
});
var binaryProt = new TBinaryProtocol(transport);
// SERIALIZATION:
var notification = new Notification({"subject":"AAAA"});
console.log(util.inspect(notification, false, null));
notification.write(binaryProt);
transport.flush();
DigitalGhost is right, the previous example is wrong.
IMHO the outBuffers is a private property to the transport class and should not be accessed.

Resources