Google.Apis.Urlshortener in C# giving Error JsonReaderException - c#

I want to use Google Nuget package for shortening URLs.
I included all the required files
public string shortenIt(string url)
{
UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer()
{
ApiKey = "*************************",
ApplicationName = "***************",
});
Url response = service.Url.Insert(new Url { LongUrl = url }).Execute();
return response.Id;
}
I am getting the following error on
Url response = service.Url.Insert(new Url { LongUrl = url }).Execute();
Error:
JsonReaderException: Error parsing NaN value. Path '', line 1, position 1
I would be please to know the solution..Thanks

Google's URL shortener is no longer available, you should move to using Google's Firebase Dynamic Links.
Source: https://developers.googleblog.com/2018/03/transitioning-google-url-shortener.html

Related

Azure Blob SAS Url returned from API authentication failed .net core

I am trying to return a SAS url to my frontend so I can redirect the user to that link and so they can download the file.
This is my code to create the SAS url
private SasQueryParameters GenerateSaSCredentials(string containerName, string blobName) {
// Defines the resource being accessed and for how long the access is allowed.
BlobSasBuilder blobSasBuilder = new() {
StartsOn = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)),
ExpiresOn = DateTime.UtcNow.Add(TimeSpan.FromMinutes(120)) + TimeSpan.FromSeconds(1),
Resource = "b",
BlobName = blobName,
BlobContainerName = containerName
};
// Defines the type of permission.
blobSasBuilder.SetPermissions(BlobSasPermissions.Read);
// Builds an instance of StorageSharedKeyCredential
StorageSharedKeyCredential storageSharedKeyCredential = new(_accountName, _key);
// Builds the Sas URI.
return blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
}
public Uri CreateBlobUri(string blobName, string containerName) {
SasQueryParameters parameters = GenerateSaSCredentials(containerName, blobName);
return new UriBuilder {
Scheme = "https",
Host = $"{_accountName}.blob.core.windows.net",
Path = $"files/{containerName}/{blobName}",
Query = WebUtility.UrlDecode(parameters.ToString())
}.Uri;
}
You may notice the url decode on parameters.ToString() is because of a similar issue ive seen on stackoverflow where they spoke of double encoding.
However when i return this url to the browser and redirect i get the following error.
This is how i return the URL
return Ok(_blobUtils.CreateBlobUri(fileName, containerName).ToString());
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header
is formed correctly including the signature. RequestId:01696cca-d01e-0023-2ea4-74f5df000000
Time:2021-07-09T09:23:33.0250817Z</Message>
<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>
If i remove the WebUtility.UrlDecode from the parameters.ToString(), i get this error
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header
is formed correctly including the signature. RequestId:016a1821-d01e-0023-3da4-74f5df000000
Time:2021-07-09T09:24:38.4051042Z</Message>
<AuthenticationErrorDetail>Signature did not match. String to sign used was r 2021-07-
09T09:14:38Z 2021-07-09T11:24:39Z /blob/${_acountName}/files/bqXbY54sRRsipOUB1PF6/fyI67FYOqDS80y1vNWRL/PRE_OP_CT/0/TK1.left.TST.PTN1.PRE
_OP_CT.zip 2020-04-08 b </AuthenticationErrorDetail>
</Error>
The structure of the Blob i am trying to access is:
And finally the blob we are trying to create a SAS to
Can anyone see why this would fail?
Please get rid of files from Path here:
return new UriBuilder {
Scheme = "https",
Host = $"{_accountName}.blob.core.windows.net",
Path = $"files/{containerName}/{blobName}",
Query = WebUtility.UrlDecode(parameters.ToString())
}.Uri;
It should be something like:
return new UriBuilder {
Scheme = "https",
Host = $"{_accountName}.blob.core.windows.net",
Path = $"{containerName}/{blobName}",
Query = WebUtility.UrlDecode(parameters.ToString())
}.Uri;
UPDATE
Based on the screenshot and the error message, the name of your container is files and the name of the blob is bqXbY54sRRsipOUB1PF6/fyI67FYOqDS80y1vNWRL/PRE_OP_CT/0/TK1.left.TST.PTN1.PRE. Please use them in your code and you should not get the error. You still need to remove files from the Path above as it is already included in your containerName.
The reason your code is failing is because you're calculating SAS token for a blob inside a blob container (the blob path becomes container-name/blob-name). However in your request, you're prepending files to your request URL, your blob path becomes files/container-name/blob-name. Since the SAS token is obtained for a different path but is used for another path, you're getting the error.

Unity- How to get the download URL once an image is uploaded to firebase storage?

I'm using the basic unity firebase storage documentation provided by firebase.
after implementing the codes i get an error saying
'StorageMetadata.DownloadUrl' is obsolete: 'StorageMetadata.DownloadUrl is deprecated. Please use StorageReference.GetDownloadUrlAsync() instead' (CS0619) [Assembly-CSharp]
after that i have changed the code as
string download_url = storage_ref.Child("ss.jpg").GetDownloadUrlAsync().ToString();
in my code
images_ref.PutFileAsync(local_file).ContinueWith((Task<StorageMetadata> task) =>
{
if(task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
status.text = "Uo-oh, an error occurred!";
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
Debug.Log("Finished uploading...");
//string download_url = metadata.DownloadUrl.ToString(); // This shows error
//Changed as
string download_url = storage_ref.Child("ss.jpg").GetDownloadUrlAsync().ToString();
Debug.Log("download url = " + download_url);
}
});
but when use this it does not returns a string of that URL
It returns :
download url = System.Threading.Tasks.Task`1[System.Uri]
I need to get the string value of downloadURL of the image once it is uploaded. Please help.
Thank you in advance.
Like most of the firebase methods GetDownloadUrlAsync() as the name already says is async and returns a Task<Uri>.
just as before you should use ContinueWith()
storage_ref.Child("ss.jpg").GetDownloadUrlAsync().ContinueWith((Task<Uri> uriTask) =>
{
string download_url = uriTask.Result.ToString();
Debug.Log(download_url);
});
where result will be of type Uri

Youtube v3 API captions downloading

I'm trying to download captions from some videos on Youtube using their nuget package. Here's some code:
var request = _youtube.Search.List("snippet,id");
request.Q = "Bill Gates";
request.MaxResults = 50;
request.Type = "video";
var results = request.Execute();
foreach (var result in results.Items)
{
var captionListRequest = _youtube.Captions.List("id,snippet", result.Id.VideoId);
var captionListResponse = captionListRequest.Execute();
var russianCaptions =
captionListResponse.Items.FirstOrDefault(c => c.Snippet.Language.ToLower() == "ru");
if (russianCaptions != null)
{
var downloadRequest = _youtube.Captions.Download(russianCaptions.Id);
downloadRequest.Tfmt = CaptionsResource.DownloadRequest.TfmtEnum.Srt;
var ms = new MemoryStream();
downloadRequest.Download(ms);
}
}
When the Download method is called I'm getting a weird Newtonsoft.JSON Exception that says:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: T. Path '', line 0, position 0.'
at Newtonsoft.Json.JsonTextReader.ParseValue()
I've read some other threads on captions downloading problems and have tried to change my authorization workflow: first I've tried to use just the ApiKey but then also tried OAuth. Here's how it looks now:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "CLIENT_ID",
ClientSecret = "CLIENT_SECRET"
},
new[] { YouTubeService.Scope.YoutubeForceSsl },
"user",
CancellationToken.None,
new FileDataStore("Youtube.CaptionsCrawler")).Result;
_youtube = new YouTubeService(new BaseClientService.Initializer
{
ApplicationName = "LKS Captions downloader",
HttpClientInitializer = credential
});
So, is it even possible to do what I'm trying to achieve?
P.S. I was able to dig deep into the youtube nuget package and as I see, the actual message, that I get (that Newtonsoft.JSON is trying to deserialize, huh!) is "The permissions associated with the request are not sufficient to download the caption track. The request might not be properly authorized, or the video order might not have enabled third-party contributions for this caption."
So, do I have to be the video owner to download captions? But if so, how do other programs like Google2SRT work?
Found this post How to get "transcript" in youtube-api v3
You can get them via GET request on: http://video.google.com/timedtext?lang={LANG}&v={VIDEOID}
Example:
http://video.google.com/timedtext?lang=en&v=-osCkzoL53U
Note that they should have subtitles added, will not work if auto-generated.

Invaild Json Result through Web Api in angular js

I have build a http post web api in asp which return the following string in Json
RootObject rootObject = new RootObject()
{
status = "User Registered"
};
msg = JsonConvert.SerializeObject(rootObject);
Below is my angular js controller in which I am consuming that web api
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.signup=function(data){
var link = 'http://xxxxxxxxxxxxxxxxxxxxxx/api/Home/RegisterUser';
//using http post
//passing values to parameter
$http.post(link, {RegisterName : data.name, RegisterUserName : data.username, RegisterPassword : data.password , RegisterEmail: data.mail , RegisterMobile : data.mobile})
.then(function (res){ //if a response is recieved from the server.
$scope.response = res; //contains Register Result
console.log($scope.response);
});
}
})
With the above code I am getting following result in google chrome console
I am try to get that status only to match it value but I am unable to do so.
The doubt I am having is that json format
console.log(JSON.stringify($scope.response)) will do what you need.
If you're wanting those particular value, you can just access those and pass them to log.
console.log($scope.response.data['status']);
you get the json as :
$scope.response = res.data;
might be you require JSON.parse(res.data) or $.parseJSON(res.data) for getting json object

Getting web search results using Google Custom Search and Google .Net Client Liberary ERROR 400

I'm trying to use Google custom search to retrieve google web search's URLs.
this is my code:
String query = "***";
string apiKey = "********";
string cx = "****";
var svc = new Google.Apis.Customsearch.v1.CustomsearchService
(new BaseClientService.Initializer
{
ApiKey = apiKey
});
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
listRequest.Start = 1;
var search = listRequest.Execute();
foreach (var result in search.Items)
{
Console.WriteLine("Title: {0}", result.Title);
Console.WriteLine("Link: {0}", result.Link);
}
The service customsearch has thrown an exception:
Google.GoogleApiException: Google.Apis.Requests.RequestError Invalid
Value [400] Errors [ Message[Invalid Value] Location[ - ]
Reason[invalid] Domain[global] ]
I apreciate any help.
Thank you.
I figured it out,the problem was in the request, int cx parameter
I'will include the new code after I finish my project
thank you

Categories