Sharing image via my app in xamarin.forms - xamarin.ios

I want to share an image. Sharing options should contain my app xyz. For example if I open an image and want to share it on instagram sharing options contains instagram,facebook,twitter,email etc. Like that my app should be in sharing options. How can I do that in xamarin.forms(both ios and android).

I think the app icon is created in a directory that is private to your app, so other apps wont be able to get at it.
You will need to save it out somewhere where the other apps can access it then share it from that location some thing like this:
public void Share (string title, string content)
{
if (string.IsNullOrEmpty (title) || string.IsNullOrEmpty (content))
return;
Bitmap b = BitmapFactory.DecodeResource(Resources,Resource.Drawable.icon_120);
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose ();
var imageUri = Android.Net.Uri.Parse ($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent ();
sharingIntent.SetAction (Intent.ActionSend);
sharingIntent.SetType ("image/*");
sharingIntent.PutExtra (Intent.ExtraText, content);
sharingIntent.PutExtra (Intent.ExtraStream, imageUri);
sharingIntent.AddFlags (ActivityFlags.GrantReadUriPermission);
StartActivity (Intent.CreateChooser (sharingIntent, title));
}
Also add ReadExternalStorage and WriteExternalStorage permissions to your app.
Let me know if that works.

Related

Azure Text to Speech (Cognitive Services) in web app - how to stop it from outputting audio?

I'm using Azure Cognitive Services for Text to Speech in a web app.
I return the bytes to the browser and it works great, however on the server (or local machine) the speechSynthesizer.SpeakTextAsync(inp) line outputs the audio to the speaker.
Is there a way to turn this off, since this runs on a web server (and even if I ignore it, there's the delay while it outputs audio before sending back the data)
Here's my code ...
var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
speechConfig.SpeechSynthesisVoiceName = "fa-IR-FaridNeural";
speechConfig.OutputFormat = OutputFormat.Detailed;
using (var speechSynthesizer = new SpeechSynthesizer(speechConfig))
{
// todo - how to disable it saying it here?
var speechSynthesisResult = await speechSynthesizer.SpeakTextAsync(inp);
return Convert.ToBase64String(speechSynthesisResult.AudioData);
}
What you can do is add an audioconfig to the speechSynthesizer.
In this audioconfig object you can specify a file path to a .wav file which already exist on the server.
Whenever you run speaktextasyn instead of a speaker it will redirect the data to the .wav file.
This audio file you can read and perform your logic later.
Just add the following code before creating the speechSynthesizer object.
var audioconfig = AudioConfig.FromWavFileOutput(filepath);
here filepath is a location of the .wav file as a string.
Complete code :
string filepath = "<file path> " ;
var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
var audioconfig = AudioConfig.FromWavFileOutput(filepath);
speechConfig.SpeechSynthesisVoiceName = "fa-IR-FaridNeural";
speechConfig.OutputFormat = OutputFormat.Detailed;
using (var speechSynthesizer = new SpeechSynthesizer(speechConfig, audioconfig))
{
// todo - how to disable it saying it here?
var speechSynthesisResult = await speechSynthesizer.SpeakTextAsync(inp);
return Convert.ToBase64String(speechSynthesisResult.AudioData);
}

Microsoft bot framework : How to define the image path which exists in the solution itself

I have stored the image inside the project itself, now I would like to display the image on the hero card, so I have mentioned the relative path. However the image is not appearing....
List<CardImage> cardImages = new List<CardImage>();
cardImages.Add(new CardImage(url: "~/duck-on-a-rock.jpg", alt:"image1"));
But when I referred the image from some website and mention the same path on the page like below that time the image is appearing.
List<CardImage> cardImages = new List<CardImage>();
cardImages.Add(new CardImage(url: "http://www.publicdomainpictures.net/pictures/30000/t2/duck-on-a-rock.jpg", alt:"image1"));
Is it not possible to keep the image inside the project folder?
This is a super old question, but google me brought here nonetheless. The solution I came across was to create a data url for your local resource. In node.js:
const imageData = fs.readFileSync(path.join(__dirname, '../resources/logo.png'));
const base64Image = Buffer.from(imageData).toString('base64');
const inlinePng = {
name: 'logo.png',
contentType: 'image/png',
contentUrl: `data:image/png;base64,${ base64Image }`
};
With an svg, you can skip the base64 encode:
const svgData = fs.readFileSync(path.join(__dirname, './resources/logo.svg'));
const inlineSvg = {
name: 'logo',
contentType: 'image/svg',
contentUrl: `data:image/svg+xml;utf8,${ svgData }`,
};
See Microsoft's docs for reference and C# samples.
Using DI approach: Pass one extra IHostingEnvironment variable to your dialog constructor.
public DialogBot(ConversationState conversationState, T dialog, ConcurrentDictionary<string, ConversationReference> conversationReferences, IHostingEnvironment env)
{
_conversationReferences = conversationReferences;
_conversationState = conversationState;
_dialog = dialog;
_env = env;
}
And later you can use _env.WebRootPath to access your local storage (for bot emulator) or use environmental variable WEBSITE_HOSTNAME if you run bot in azure.
private async Task SendWelcomeCardAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
var card = new HeroCard();
card.Title = "Welcome to Bot Framework!";
var host = new Uri(Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME") != null ? ("https://" + Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")) : _env.WebRootPath + "/");
var img = new Uri(host, "MyImage.jpg");
card.Images = new List<CardImage>() { new CardImage(img.AbsoluteUri) };
var response = MessageFactory.Attachment(card.ToAttachment());
await turnContext.SendActivityAsync(response, cancellationToken);
}
I simply dropped MyImage.jpg image to wwwroot project folder and marked it as Content

UWP - ImageBrush full path to ImageSource

I have an ellipse and I want to fill it with image. And I would like to set full path to the image to ImageSource property of ImageBrush. But I wasn't able to accomplish it.
I've tried to add:
C:/Users/someuser/Pictures/untitled.png
C:\\Users\\someuser\\Pictures\\untitled.png which came from FilePicker
C:\Users\misko\Pictures\untitled.png.
But non of this works. Can you please explain to me how to properly set full path?
You have to open the file first using FilePicker
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
grid.Background = new ImageBrush
{
ImageSource = bitmapImage
};
}

How to provision Branding files using SharePoint Hosted App in SharePoint Online/Office 365?

I am looking for SharePoint Hosted App Solution which will provision Branding files (JS/CSS/Images) into SharePoint Online/Office 365 environment.
I got a very good article to achive this and tried to implement the same as shown in below link: http://www.sharepointnutsandbolts.com/2013/05/sp2013-host-web-apps-provisioning-files.html
This solution is not working for me and while execution of app, I am getting below error:
Failed to provision file into host web. Error: Unexpected response data from server. Here is the code which is giving me error:
// utility method for uploading files to host web..
uploadFileToHostWebViaCSOM = function (serverRelativeUrl, filename, contents) {
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < contents.length; i++) {
createInfo.get_content().append(contents.charCodeAt(i));
}
createInfo.set_overwrite(true);
createInfo.set_url(filename);
var files = hostWebContext.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
hostWebContext.load(files);
files.add(createInfo);
hostWebContext.executeQueryAsync(onProvisionFileSuccess, onProvisionFileFail);
}
Please suggest me, what can be the issue in this code? Or else suggest me another way/reference in which I can Create a SharePoint-Hosted App to provision Branding Files.
Thanks in Advance!
I would use a different method to access host web context as follows:
//first get app context, you will need it.
var currentcontext = new SP.ClientContext.get_current();
//then get host web context
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
Here are some references:
https://sharepoint.stackexchange.com/questions/122083/sharepoint-2013-app-create-list-in-host-web
https://blog.appliedis.com/2012/12/19/sharepoint-2013-apps-accessing-data-in-the-host-web-in-a-sharepoint-hosted-app/
http://www.mavention.com/blog/sharePoint-app-reading-data-from-host-web
http://www.sharepointnadeem.com/2013/12/sharepoint-2013-apps-access-data-in.html
Additionally, here is an example of how to deploy a master page, however as you might notice during your testing the method used to get host web context is not working as displayed in the video and you should use the one I described before.
https://www.youtube.com/watch?v=wtQKjsjs55I
Finally, here is a an example of how to deploy branding files through a Console Application using CSOM, if you are smart enough you will be able to convert this into JSOM.
https://channel9.msdn.com/Blogs/Office-365-Dev/Applying-Branding-to-SharePoint-Sites-with-an-App-for-SharePoint-Office-365-Developer-Patterns-and-P

Sharing a big String between an app and its extension

I have a text file of 5MB and I need to send from my application to a content blocker extension. I tried a simple group sharing but it's not working, ehre is the code.
In my app:
listText = NSString(data: content, encoding: NSUTF8StringEncoding)! as String
print("\(list): \(listText.characters.count)") // It works
if let userDefaults = NSUserDefaults(suiteName: "group.AG.App") {
print("In the group") // It works
userDefaults.setObject(listText, forKey:"test")
userDefaults.synchronize()
}
In my extension:
if let userDefaults = NSUserDefaults(suiteName: "group.AG.App") {
// Things happen here
if let test = userDefaults.stringForKey("test") {
// Nothing happens here
}
}
How would you do to share a big amount of text between an app and its extension?
Since you load the string from a file and you already use App Groups, I suggest to save that file in the shared container and retrieve its content in the extension.
You can save file in the shared group in the same way you do for your app container. You only have to get the URL for the group root:
Swift
let groupRoot = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("com.group.Armand-Grillet")
Objective-C
NSURL *groupRoot = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:#"com.group.Armand-Grillet"];
You can't retrieve the string because you set a NSString and you try to retrieve an array, try to use stringForKey:

Resources