I used google.cloud.storage for .mp3 files. I tried it before and it worked.
now I writed another new function that uses the existing storage function.
everything was suppose to work but I get this weird error:
"Google.Apis.Requests.RequestError
text-to-speach#XXXXXXXXXXX.iam.gserviceaccount.com does not have storage.objects.create access to objectsound/voiceAnimals20.mp3. [403]"
I dont know what to begin with. can anybody help me?
the Ok storage function is here:
public static string VoiceStorage(int catId, string URL,
Dictionary<string, int> voicesCounter)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
#"C:\wordproject-XXXXXXXXXX.json");
// upload the image storage
//----------------
string voiceName;
voiceName = "voice" + BLLcategory.GetCategoryById(catId).CategoryName
+ voicesCounter[BLLcategory.GetCategoryById(catId).CategoryName]++ +
".mp3";
string bucketName = "XXXXXXXX";
var storage = StorageClient.Create();
using (var f = File.OpenRead(URL))
{
try
{
var res = storage.UploadObject(bucketName, voiceName, null,
f);
URL = "https://storage.cloud.google.com/" + bucketName + "/" +
voiceName;
}
catch (Exception e)
{
throw e;
}
}
return URL;
}
the new not working function is:
private void button12_Click(object sender, EventArgs e)
{
foreach (COMimageObject obj in BLLobject.GetObjects())
{
if(obj.VoiceURL==null)
{
try
{
string url=BLLtextToSpeach.TextToSpeach(obj.Name);
url=BLLtextToSpeach.VoiceStorage(
BLLimage.GetImageById(obj.ImageID).CategoryID,
url, voicesCounter);
BLLobject.UpdateVoiceURL(obj.ObjectId, url);
}
catch (Exception)
{
throw;
}
}
}
}
the catch happening after the line with url=BLLtextToSpeach.VoiceStorage
tnx!!
What the error mean is that the service account of the text-to-speach api doesn't have create access on the objectsound bucket. Go to the bucket permissions and add the text-to-speach service account with storage creator rights.
When you get this error:
[403] Errors [ Message[.................iam.gserviceaccount.com does
not have storage.buckets.list access to the Google Cloud project.
you need to have permissions in your service account from the IAM to read the buckets
storage.buckets.get Read bucket metadata, excluding IAM policies.
storage.buckets.list List buckets in a project. Also read bucket
metadata,
https://cloud.google.com/storage/docs/access-control/iam-permissions
The "Firebase Admin" will enable all necessary permissions.
Related
We are converting our old webservices (asmx) to use https, trying to get it working locally.
I have a test app I wrote in winforms jsut to call the service.
Trying to modify it to call via https, following this pattern
https://www.codeproject.com/Questions/751059/Call-https-Webservice-in-Console-Application
(Not sure I trust this pattern 100%, but it's a place to start, looks like it's trying to ignore all errors)
private void button8_Click(object sender, EventArgs e)
{
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
}
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{
AdStudent.ADStudent ws = new AdStudent.ADStudent();
ws.Url = "https://localhost/JCDCADStudent/ADStudent.asmx";
try
{
string str = ws.GetGuidString("Brown.Eric");
MessageBox.Show("secure guid is " + str + ".");
}
catch (Exception ex)
{
string cleanMsg = GetCleanMsg(ex.Message);
MessageBox.Show("\n\n " + cleanMsg + "\n\n\n\n\nProgrammer Msg:\n\n" + ex.Message, "Error");
}
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
private string GetCleanMsg(string message)
{
string startTag = "<ClientMsg>";
string endTag = "</ClientMsg>";
Int32 start = message.IndexOf(startTag) + startTag.Length;
Int32 end = message.IndexOf(endTag);
try
{
return message.Substring(start, end - start);
}
catch (Exception ex)
{
return "UNABLE TO PARSE MESSAGE : \n " + message;
}
}
}
}
I get the exception
{"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."}
inner exception
The remote certificate is invalid according to the validation procedure.
When I try and just run the HTTPS in the browser, it complains that like the title or subject field is not formatted correctly. but If I tell it to ignore that it opens the web service, I'm guessing that is the problem,
How do I fix it?
How do I get a better error like the one the browser gives me, to report in my app?
The cert was provided by our IT team, I'm not sure I can get it changed, it's a long-standing cert used for Dev.
Maybe I can get it regenerated correctly (it's applied to our machines via network policy)
I have a Xamarin mobile project setup with the Sitecore MobileSDK (WebAPI) and can browse through the items using the ReadItemsRequestWithPath method. Now I am trying to download a pdf file that is stored in the 'media library' directory. I have tried the following:
private async void DownloadFile()
{
try
{
string instanceUrl = "https://sitecoredev10.myapp.org";
using (var demoCredentials = new SecureStringPasswordProvider("username", "password"))
using
(
var session =
SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(instanceUrl)
.Credentials(demoCredentials)
.BuildReadonlySession())
{
var request = ItemWebApiRequestBuilder.DownloadResourceRequestWithMediaPath("/sitecore/media library/path/to/file")
.Build();
Stream response = await session.DownloadMediaResourceAsync(request);
// Process Stream...
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Exception originalError = e.InnerException;
Console.WriteLine(originalError.Message); // access original error
Console.WriteLine(originalError.StackTrace);
}
}
However, I'm getting the following exception:
[Sitecore Mobile SDK] Unable to download data from the internet
2016-11-03 15:24:53.411 SitecoreDemo.iOS[88136:15581600] Not Found
Should I be using a different method other than DownloadMediaResourceAsync? How can I download the file?
Found a documentation (here) in an answer thread on this site but i can´t get an connection to an AD. When i use a program like Active Directory Explorer i can connect. I think, because i am trying to connect to a LDAPS i need a different approach?
I have the server IP, a domain, username/pwd and the port 636.
I tried various combinations # new DirectoryEntry but couldn´t get it to connect. Always get a COMException Domain is not existing .
static DirectoryEntry createDirectoryEntry()
{
DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://192.168.2.59", USER, PWD);
ldapConnection.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
return ldapConnection;
}
Background Infos:
User places his card to a Card Reader Unit. Porgram gets ID from card and searches the DB for this ID and returns the eMail address belonging to the ID/User
.
And here the working solution:
private string getEmail(string userID)
{
try
{
string ldapfilter = "(&(otherPager=" + userID + "))";
DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://" + SERVER, USER, PWD);
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = ldapfilter;
/*search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();*/
string[] requiredValue = new String[] { "mail" };
foreach (String value in requiredValue)
search.PropertiesToLoad.Add(value);
SearchResult result = search.FindOne();
if (result != null)
{
foreach (String value in requiredValue)
foreach (Object myCollection in result.Properties[value])
{
return myCollection.ToString();
}
}
else
{
return "No Entry fround";
}
}
catch (Exception e)
{
Console.WriteLine("Exception Problem: " + e.ToString());
return null;
}
return null;
}
private void cmdClose_Click(object sender, EventArgs e)
{
Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.Text = getEmail(textBox1.Text);
}
You need to specify the port, since 636 is the default LDAPS port.
new DirectoryEntry("LDAP://192.168.2.59:636", USER, PWD)
I do this in some of my code, and using "LDAP://" (not "LDAPS://") is what works.
If that doesn't work, then there may be a certificate error. You can test this with a browser. If you use Chrome, open Chrome with this (so it lets you use port 636):
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=636
Then go to https://192.168.2.59:636. If you get a big fancy certificate error, then the problem is that the certificate is not trusted. View the certificate from Chrome and see what the problem is. It could be issued by an authority that is not in the Windows cert store.
We use Amazon S3 to save picture for our project but now we need to copy some images from one place to another in S3. I have older/saved images path stored in my DB and now wants to save them using new path.
Can someone please guide me in any right direction to start with. I have been looking into CopyObjectRequest but can't figure out how to proceed.
Any help will be appreciated.
Thanks
Here is a generic example with original and destination variables being passed to the function from the caller.
public void DuplicateFileInCloud(string original, string destination)
{
try
{
CopyObjectRequest request = new CopyObjectRequest();
if (original.StartsWith("http"))
{
// example: http://jk-v30.s3.amazonaws.com/PredefinedFiles/Favicons/002.ico
string bucket = getBucketNameFromUrl(original), // i.e. jk-v30
key = getKeyFromUrl(original); // the path to your file: PredefinedFiles/Favicons/002.ico
request.WithSourceBucket(bucket);
request.WithSourceKey(key);
}
else
{
// same bucket: copy/paste operation
request.WithSourceBucket(this.bucketName);
request.WithSourceKey(original);
}
request.WithDestinationBucket(this.bucketName);
request.WithDestinationKey(destination);
request.CannedACL = S3CannedACL.PublicRead; // one way of setting public headers - see other below
using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(this.accessKey, this.secretAccessKey))
{
S3Response response = client.CopyObject(request);
response.Dispose();
}
}
catch (AmazonS3Exception s3Exception)
{
throw s3Exception;
}
}
Hope this is what you were looking for!
Setting public-read
response.Addheader("x-amz-acl","public-read");
I'm developping a Facebook Application (using ASP.NET C# and Nathan Totten's Facebook C# SDK) and trying to access to extended permissions.
I tried on localhost (with an existing app in facebook), and everybody works. But when I try to use it directly in facebook, I obtain a blank page (i'm still connected on facebook).
Here is my code :
Page/aspx :
protected void btn_ask_question_Click(object sender, EventArgs e)
{
if (ControllerAccess.testUserConnected())
{
if (txt_ask_question.InnerText != "")
{
Dictionary<string, object> action = new Dictionary<string,object>();
action.Add("action", "askQuestion");
action.Add("message", txt_ask_question.InnerText);
action.Add("idTheme", ddl_choose_question_category.SelectedValue);
HttpContext.Current.Session["ActionToDo"] = action;
String s = Controller.GetExtendedPermission2(this, ControllerAccess.getScopeByAction("askQuestion"));
try{
Response.Redirect(s, false);
} catch(Exception ex)
{
}
}
}
}
In my Page_Load() :
if (HttpContext.Current.Session["ActionToDo"] != null)
{
Dictionary<string, object> action = HttpContext.Current.Session["ActionToDo"] as Dictionary<string, object>;
String s = action["action"].ToString();
switch (s)
{
case "askQuestion":
Guid idTheme;
Boolean themeExists = Guid.TryParse(action["idTheme"].ToString(), out idTheme);
if(themeExists)
{
askQuestion(action["message"].ToString(), idTheme);
lbl_errors.Text = "Votre question a bien été posée";
}
break;
default:
break;
}
HttpContext.Current.Session["ActionToDo"] = null;
}
In Control.cs :
public static string GetCustomOAuthDialogParameters(string AppID, string RedirectURI, string Scope, string State)
{
string CustomParameters = "?client_id=" + AppID + "&redirect_uri=" + RedirectURI + "&scope=" + Scope + "&state=" + State;
return CustomParameters;
}
public static void GetExtendedPermission(Page page, String scope)
{
ecritureFichier("GetExtendedPermission");
Label lbl_errors = page.Form.FindControl("lbl_errors") as Label;
string OAuthDialogAbsoluteURL = "";
try
{
string OAuthDialogURL = "https://www.facebook.com/dialog/oauth";
string PageLocation = GetCurrentPageFacebookPublishedPath(page.Request); //The redirect page (eg: https://apps.facebook.com/democsharpsdk/TestsExtendedPermission.aspx)
string UniqueReferenceCode = Guid.NewGuid().ToString();
OAuthDialogAbsoluteURL = OAuthDialogURL + GetCustomOAuthDialogParameters(AppID, PageLocation, scope, UniqueReferenceCode);
page.Response.Redirect(OAuthDialogAbsoluteURL, false);
}
catch (Exception exp)
{
lbl_errors.Text += "Erreur Catchée via ASP.NET : " + exp.Message;
}
}
The blank page appears when I use this line : page.Response.Redirect(OAuthDialogAbsoluteURL, false);
But I log all my steps and my OAuthDialogAbsoluteURL is correct :
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXXXXXXXX&redirect_uri=https://apps.facebook.com/name_of_my_app&scope=email&state=0443030f-dddd-4fe6-9d6c-9454409d01b3
When I type it into the adress bar manually, everything works correctly.
Do you have any idea about the difference between local version and published version or why the redirect doesn't work? Maybe facebook block some requests?
Thanks.
Make sure you settings point to the hosted version if you want to use the app to test different environments. Facebook doesn't let you authorise a user from a site that isn't connect to your app for security reasons.
Normally, you would see an error like "URL isn't owned by Application" or similar.
I finally resolved my problem usingChrome Debugger. The error was :
Refused to display document because display forbidden by X-Frame-Options
I used Javascript to fix it, and did my redirection like this :
Response.Write("<script>");
Response.Write("window.open('"+redirect+"','_top')");
Response.Write("</script>");
Hope it'll help some people.