I'm creating a windows store app to read write files.
I gave permissions for document library but still getting this error
App manifest declares document library access capability without specifying at least one file type association
The code snippet of my code:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
String temp = Month.SelectedValue.ToString() + "/" + Day.SelectedValue.ToString() + "/" + Year.SelectedValue.ToString(); //((ComboBoxItem)Month.SelectedItem).Content.ToString();
DateTime date = Convert.ToDateTime(temp);
Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt");
var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(temp, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
}
Any other better approach is also acceptable.
1.I don't have access to Skydrive. 2.Also don't want to use filepicker
You need to specify file type association also.
From: http://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx
Documents Library:
Note You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.
you can find it in the app manifest, when you check documents library in capabilites, you have to fill in atleast one file type association under Declarations tab.
Found exactly what i was looking for. File type associations was to be added in the app.manifest
For those who facing the same problem check this link
Related
I am using "Azure Storage File Shares" to store some files from our website, but failed with error message "The specified share already exists".
I have change the file that being upload, but the error persist.
Here my code
public static void Test2Upload()
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
string connectionString = "DefaultEndpointsProtocol=https;AccountName=xxxxx;AccountKey=xxxxx;EndpointSuffix=core.windows.net";
string shareName = "myapp-dev";
string dirName = "files";
string fileName = "catto.jpg";
// Path to the local file to upload
string localFilePath = #"d:\temp\two.jpg";
// Get a reference to a share and then create it
ShareClient share = new ShareClient(connectionString, shareName);
share.Create();
// Get a reference to a directory and create it
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.Create();
// Get a reference to a file and upload it
ShareFileClient file = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
file.Create(stream.Length);
file.UploadRange(
new HttpRange(0, stream.Length),
stream);
}
}
Looks like I should not create ShareClient with same name several times.
Then how to check and use it?
The most important question is, why the file still not yet uploaded (even if I rename the ShareClient object)?
Looks like I should not create ShareClient with same name several
times. Then how to check and use it?
You can use ShareClient.CreateIfNotExists instead of ShareClient.Create method. Former will try to create a share but if a share already exists, then it won't be changed.
You can also use ShareClient.Exists to check if the share exists and then create it using ShareClient.Create if it does not exist. This is not recommended however as it might not work if multiple users are executing that code at the same time. Furthermore, you will be making 2 network calls - first to check the existence of share and then the second to create it.
The most important question is, why the file still not yet uploaded
(even if I rename the ShareClient object)?
Your code for uploading the file looks ok to me. Are you getting any error in that code?
We could use ShareClient.CreateIfNotExists when creating ShareClient object to avoid the problem. Like below
ShareClient share = new ShareClient(connectionString, shareName);
share.CreateIfNotExists();
You might found Similar problem on ShareDirectoryClient.
This part purpose is to create the folder structure.
The upload will fail if the destination folder is not exist.
Error will occur if we create a folder when it already exist.
So, use method ShareDirectoryClient.CreateIfNotExists, like below
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.CreateIfNotExists();
Here my complete code
public static void TestUpload()
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
string connectionString = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xx;EndpointSuffix=core.windows.net";
string shareName = "myapp-dev";
string dirName = "myfiles";
string fileName = "catto.jpg";
string localFilePath = #"d:\temp\two.jpg";
// Get a reference to a share and then create it
ShareClient share = new ShareClient(connectionString, shareName);
share.CreateIfNotExists();
// Get a reference to a directory and create it
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.CreateIfNotExists();
// Get a reference to a file and upload it
ShareFileClient file = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
file.Create(stream.Length);
file.UploadRange(
new HttpRange(0, stream.Length),
stream);
}
}
I am using Azure Function App
I am using CSVHelper package to create file, But CSVHelper needs local file path first to Create/Write file.
using (var writer = new StreamWriter(filePath))
using (var csvData = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
// Write input in csv
csvData.WriteRecords(input);
}
What path can I use to create file in Azure Function App?
Since it looks like you're using a StreamWriter, you could also write to a MemoryStream instead of creating an actual file. This feels like a better route to take with Azure Functions.
If you're really set on creating an actual file, you can do so by using System.IO.Path.GetTempPath(), which will always return a valid path for any given system. Create your temporary file there, then continue with the process.
Please take into account that your Function might run multiple times on the same environment, so be sure to use a unique filename.
For future reference:
private static void ExportContentToCsv(ILogger log, IEnumerable<T> content)
{
var path = Path.Combine(Path.GetTempPath(), "content.csv");
log.LogInformation($"Writing csv file at {path}");
if (File.Exists(path))
{
log.LogInformation("Deleting existent resources...");
File.Delete(path);
}
using (var writer = new StreamWriter(path))
{
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(content);
}
}
}
I developed an algorithm that when u type in discord server's text channel : "-nuke #tag" that member will get a "Muted" role and his id will be added to an array. If he leaves the server and joins back, the bot will compare the new member's id with all the ids in the array and if they are matching it will automatically give that person the "Muted" role. The problem is, the bot.on doesn't seem to work inside something else than index.js. I dont really want to go inside all the event handlers and stuff, just to get this one working nuke.js
This answer is in reference to a comment I made. This will show you how to create and access a global map.
To start you need to extend the client class by the map you want to use. You do that like this.
const { Client } = require('discord.js');
module.exports = class extends Client {
constructor(config) {
super({});
this.muteIDs = new Map(); // you can name it whatever you like
this.config = config;
}
};
You should do that in a separate file. Lets call that file clientextend.js. Now you can create your bot client like you usually would, however you need to require the file that you just created. This example has both the file in which you extend the client and the file you create the client in, in the same directory. Note: In your example you have bot instead of client.
const Client = require('./clientextend.js')
const client = new Client();
You now have access to the map you created anywhere you have your client available to you. You can access it like this.
muteIDs = client.muteIDs;
I have some variables which are going to be used by the business logic part of a function. Therefore, instead of adding them inside the appsetting.json file, I have added a separated file as variable.json
Testing on my machine works but after deploy, it seems function can not find it. and I got an error:
The properties for this file is like the below image. (The build action was None before, but nothing has been changed even by content)
and the below image shows how it looks like in root
And because of that reason, any call the response will be "Function host is not running."
The code for reading this file (path = "Variables.json")
private static List<Variable> GetVariables(string path)
{
string json = File.ReadAllText(path);
var variables = JsonConvert.DeserializeObject<List<Variable>>(json);
return variables;
}
Does anyone have any clue why this is happening?
Problem was because when we start Azure Function locally the file varibale.json is available by Directory.GetCurrentDirectory(), but published on azure portal it's Directory.GetCurrentDirectory() + #"\site\wwwroot"
To get the correct folder path you can use following code:
public static HttpResponseMessage Run(HttpRequestMessage req, ExecutionContext context)
{
var path = System.IO.Path.Combine(context.FunctionDirectory, "varibale.json");
// ...
}
For startup.cs, you can use the following code:
var executioncontextoptions = builder.Services.BuildServiceProvider()
.GetService<IOptions<ExecutionContextOptions>>().Value;
var currentDirectory = executioncontextoptions.AppDirectory;
I need to create/add a new File from Files Lib, then i need to set the name of the file with an unique ID and update other fieds. I can update the fields without any problems, but i couldn't find a way to create the file.
How can i possibly achieve the New => Create from template like in the image below
I've tried many ways but nothing fullfill my request.
1
this.web.lists.getByTitle('myFilesLib').items.add() => i get an error about the need to use SPFileCollection.Add()
2
this.web.getFolderByServerRelativeUrl(url).files.addTemplateFile => there is nothing for custom template
3
this.web.getFolderByServerRelativeUrl(url).files.add => i need to provide a file.
For JSOM, you can try this:
newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
For CSOM:
var creationInformation = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem listItem = list.AddItem(creationInformation);
listItem.FieldValues["Foo"] = "Bar";
listItem.Update();
clientContext.ExecuteQuery();
Some wiki for this way: https://social.technet.microsoft.com/wiki/contents/articles/37575.sharepoint-online-working-with-files-inside-document-library-using-jsom.aspx
this.web.getFolderByServerRelativeUrl(url).files.addTemplateFile is used to add page, so it is not suitable for your scenario.
http://www.ktskumar.com/2016/08/pnp-js-core-create-new-page-sharepoint-library/
The PnP JS method requires a File DOM or BLOB object for uploading a file to the SharePoint. Based on the those, we will try two options to upload a file to the SharePoint Library or folder in a library:BLOB/FileAPI
http://www.ktskumar.com/2016/09/pnp-js-core-upload-file-sharepoint/
More reference for you from Microsoft:
https://msdn.microsoft.com/en-us/library/office/dn450841.aspx
This is a sample code to use when you want to upload an existing ContentType to your content library on SharePoint.
const templateUrl = '/sites/App/Template/Forms/Template/test.docx'
const name = 'test.docx'
const depositUrl = '/sites/App/Template'
const web = new Web('http://localhost:8080/sites/App'); // Proxy URL for Dev
web.getFileByServerRelativeUrl(templateUrl)
.getBuffer()
.then((templateData: ArrayBuffer) => {
web.getFolderByServerRelativeUrl(depositUrl).files.add(name, templateData));
});
There is an issue if you use SP-Rest-Proxy at the moment (file is corrupted on SharePoint) but it should be fix soon.
If you Deploy your app on SharePoint, it work as expected.
Related links:
https://github.com/pnp/pnpjs/issues/196#issuecomment-410908170
https://github.com/koltyakov/sp-rest-proxy/issues/61