Google Crendentials in NULL and I cant set the environmental variable - google-translate

I'm trying to translate text box text using ASP.Net. While integrating Google translate API i'm getting in TranslationClient.Create(). and in metadata file the translation client is null.Even i set credentials path in environmental variable but still it is null..How to resolved it?
TranslationClient Client = TranslationClient.Create();
var text = txtCategoryName.Text;
var resp = Client.TranslateText(text, LanguageCodes.English, LanguageCodes.ChineseSimplified);
*Meta DATA file*
public static TranslationClient Create(GoogleCredential credential = null, TranslationModel model = TranslationModel.ServiceDefault);
//
// Summary:
// Asynchronously creates a Google.Cloud.Translation.V2.TranslationClient, using
// application default credentials if no credentials are specified.
//
// Parameters:
// credential:
// Optional Google.Apis.Auth.OAuth2.GoogleCredential.
//
// model:
// The default translation model to use. Defaults to Google.Cloud.Translation.V2.TranslationModel.ServiceDefault.
//
// Returns:
// The task representing the created Google.Cloud.Translation.V2.TranslationClient.
//
// Remarks:
// The credentials are scoped as necessary.
[AsyncStateMachine(typeof(<CreateAsync>d__19))]
public static Task<TranslationClient> CreateAsync(GoogleCredential credential = null, TranslationModel model = TranslationModel.ServiceDefault);
Actual Result is null in translation client instead on translated text
Highlighted line in this image is showing null
Meta Data File Image

Related

POST method to upload file to Azure storage - what to return

I am creating an app where
user can upload the text file and then
find most used word and change that word in text and
show the changed text to the user.
if it is possible, I would like to
get the file’s text content before uploading when Post method is being called and save that content
so I add the “DownloadTextAsync()” method inside of the POST method, but it seems like I am calling this method to the wrong subject?
[HttpPost("UploadText")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
string connectionString = Environment.GetEnvironmentVariable("mykeystringhere");
// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
//Create a unique name for the container
string containerName = "textdata" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "textfiledata" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
// Open the file and upload its data
using FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");
// Get the blob file as text
string contents = blobClient.DownloadTextAsync().Result;
//return the string
return contents;
//if (uploadSuccess)
// return View("UploadSuccess");
//else
// return View("UploadError");
}
The issues I am having are
I understood that ‘blobClient’ is the reference to the blob, where I can get the file’s data but this must be wrong?
Also it seems like I cannot use “CloudBlobContainer” nor the “CloudBlockBlob blob”. Is it because inside of the POST method, the blob has been just initialized and does not exist when these twos are executed?
Also when I test the POST method, the console throws “Refused to load the font '' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.” which I googled but have no idea what it means?
I have tried different ways but keep getting CANNOT POST/“ But could not really find the solid anwers. Could this be related to my POST method?
I understood that ‘blobClient’ is the reference to the blob, where I
can get the file’s data but this must be wrong?
That's correct in a sense that you can use blobClient to perform operations on blob like upload/download etc. I am not sure why you say but this must be wrong.
Also it seems like I cannot use “CloudBlobContainer” nor the
“CloudBlockBlob blob”. Is it because inside of the POST method, the
blob has been just initialized and does not exist when these twos are
executed?
No, this is happening because you're using a newer version of SDK (version 12.x.x) and CloudBlobContainer and CloudBlockBlob are available in the older version of the SDK.
Also when I test the POST method, the console throws “Refused to load
the font '' because it violates the following Content Security Policy
directive: "default-src 'none'". Note that 'font-src' was not
explicitly set, so 'default-src' is used as a fallback.” which I
googled but have no idea what it means? I have tried different ways
but keep getting CANNOT POST/“ But could not really find the solid
anwers. Could this be related to my POST method?
Not sure why this is happening. You may want to ask a separate question for this and when you do, please include the HTML portion of your code as well.

FormRecognizer C# SDK with blob file - unsupported media type error

I am trying to use C# FormRecognizer SDK of Azure Cognitive Service. I have pdfs stored in Azure Blob and I need to extract text/tables from these pdf files using C# SDK.
I see that "AnalyzeWithCustomModelAsync" method takes "Stream" as input parameter, where it accepts only "FileStream" type. If I pass "MemoryStream" as input parameter type, I am getting following error:
{"value":{"error":{"code":"UnsupportedMediaType","message":"In case of HTML form data, the multipart request must contain a document with a media type of - 'application/pdf', 'image/jpeg' or 'image/png'."}},"formatters":[],"contentTypes":[],"statusCode":415}
Is there anyway where I can use my blob file directly, without needing to have those files saved locally?
Regards,
Madhu
The following code snippet works by getting an instance of the blob (into CloudBlockBlob class) and then loading it into the MemoryStream. Once you have that, you can pass that into Form Recognizer to analyze.
List<string> blobsToAnalyze = new List<string>();
// Get latest Form Recognizer training model ID
Guid aiTrainModelId = Guid.Empty;
ModelResult latestModel = await FormRecognizer.GetModelAsync(config, log);
if (latestModel != null)
aiTrainModelId = latestModel.ModelId;
// Iterate through all blobs
foreach (string strBlob in blobsToAnalyze)
{
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(strBlob);
using (MemoryStream ms = new MemoryStream())
{
// Load blob into a MemoryStream object
await blob.DownloadToStreamAsync(ms);
// Send to Form Recognizer to analyze
AnalyzeResult results = await FormRecognizer.AnalyzeFormAsync(config, aiTrainModelId, ms, log);
searchResults = FormRecognizer.AnalyzeResults(config, tableClient, results, log);
}
}

Changelog method based on project tracker template

Based on the project tracker I have integrated a changelog into my app that relates my UserSettings model to a UserHistory model. The latter contains the fields FieldName, CreatedBy, CreatedDate, OldValue, NewValue.
The relation between both models works fine. Whenever a record is modified, I can see the changes in a changelog table. I now want add an "undo"-button to the table that allows the admin to undo a change he clicks on. I have therefore created a method that is handled by the widget that holds the changelog record:
function undoChangesToUserRecord(changelog) {
if (!isAdmin()) {
return;
}
var fieldName = changelog.datasource.item.FieldName;
var record = changelog.datasource.item.UserSettings;
record[fieldName] = changelog.datasource.item.OldValue;
}
In theory method goes the connection between UserHistory and UserSettings up to the field and rewrites its value. But when I click on the button, I get a "Failed due to circular reference" error. What am I doing wrong?
I was able to repro the issue with this bit of code:
google.script.run.ServerFunction(app.currentPage.descendants.SomeWidget);
It is kinda expected behavior, because all App Maker objects are pretty much complex and Apps Script RPC has some limitations.
App Maker way to implement it would look like this:
// Server side script
function undoChangesToUserRecord(key) {
if (!isAdmin()) {
return;
}
var history = app.models.UserHistory.getRecord(key);
if (history !== null) {
var fieldName = history.FieldName;
var settings = history.UserSettings;
settings[fieldName] = history.OldValue;
}
}
// Client side script
function onUndoClick(button) {
var history = widget.datasource.item;
google.script.run
.undoChangesToUserRecord(history._key);
}

How to change the default culture?

I created my first app with ASP.NET Core. When I debug it, I see a problem with words that have accents:
How can I correctly localize the application?
Update:
I tried to implement Joe's suggestion, but I didn't get the expected result as you can see in this image.
The strings displayed from the database are okay, but the strings used in the view template like title or text are displayed incorrectly.
I don't want a multi-language application, just one in português.
On the old asp.net this configurations was done on .config with element
text html
in project.json you need this dependency
"Microsoft.Extensions.Localization": "1.0.0-rc2-final",
in Startup.cs in ConfigureServices you need code like this:
services.AddLocalization(options => options.ResourcesPath = "GlobalResources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};
// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedCultures;
// You can change which providers are configured to determine the culture for requests, or even add a custom
// provider with your own logic. The providers will be asked in order to provide a culture for each request,
// and the first to provide a non-null result that is in the configured supported cultures list will be used.
// By default, the following built-in providers are configured:
// - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
// - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
// - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
//options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
//{
// // My custom request culture logic
// return new ProviderCultureResult("en");
//}));
});
in Configure you need code something like this:
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
I have some working demo code here, if you need more

Difficulty with the image quality of the map generated with Bing Map Api

I'm developing an application that retrieves an image of "Bing Maps" with [Bing Api] since my webService.
My problem is the rendering of the image.
If I set my zoom greater than 11,or if I set a size too big, the result of recover my image is like "cut" into several loading and gives the impression that the image is not entirely downloaded.
Example picture below...
Have you any idea why the image looks like its back?
Here is my code used in my webService.
//call function
GetImageMap(46,6,800,800,17);
//Get Bing map Image from the web
public string GetImageMap(double latitude,double longitude,int mapSizeHeight, int mapSizeWidth, int zoomLevel)
{
string key = "asoidfz9aos78fa9w3hf9w3fh9hf7ha9wfw37fhblablablablablabla";
MapUriRequest mapUriRequest = new MapUriRequest();
// Set credentials using a valid Bing Maps key
mapUriRequest.Credentials = new ImageryService.Credentials();
mapUriRequest.Credentials.ApplicationId = key;
// Set the location of the requested image
mapUriRequest.Center = new ImageryService.Location();
mapUriRequest.Center.Latitude = latitude;
mapUriRequest.Center.Longitude = longitude;
// Set the map style and zoom level
MapUriOptions mapUriOptions = new MapUriOptions();
mapUriOptions.Style = MapStyle.Aerial;
mapUriOptions.ZoomLevel = zoomLevel;
mapUriOptions.PreventIconCollision = true;
// Set the size of the requested image in pixels
mapUriOptions.ImageSize = new ImageryService.SizeOfint();
mapUriOptions.ImageSize.Height = mapSizeHeight;
mapUriOptions.ImageSize.Width = mapSizeWidth;
mapUriRequest.Options = mapUriOptions;
//Make the request and return the URI
ImageryServiceClient imageryService = new ImageryServiceClient();
MapUriResponse mapUriResponse = imageryService.GetMapUri(mapUriRequest);
return mapUriResponse.Uri;
}
// ### END Function getImageMap
And the url query:
http://api.tiles.virtualearth.net/api/GetMap.ashx?c=46,6&dcl=1&w=800&h=800&b=a,mkt.en-US&z=17&token={token}
Result image.. :
It seems to be related to the aerial imagery and it's not technically related.
I will report it to the appropriate team.
By the way, you should use the REST Imagery API which is the official way to use the imagery from Bing, see the MSDN:
http://msdn.microsoft.com/en-us/library/ff701724.aspx
Here is a sample URL based on your example:
http://dev.virtualearth.net/REST/v1/Imagery/Map/Aerial/46,6/17?mapSize=800,800&key=YOURKEY

Resources