I have to ask the user to choose a location and save the file with a custom extension (.tdr). I have set intent.SetType to */* and currently I have to save file without any extension. Can anyone please help me to resolve my issue?
Here is my code sample
Intent intent = new Intent();
intent.SetType("*/*");
intent.PutExtra(Intent.ExtraAllowMultiple, false);
intent.SetAction(Intent.ActionCreateDocument);
MainActivity.Instance.persistentStorageService.Write("DataToWrite", projectJson);
MainActivity.Instance.StartActivityForResult(Intent.CreateChooser(intent, "Save TRW Project File"), RequestCodeConstants.FilePickerSaveRequestCode);
In MainActivity.cs
System.IO.Stream output = ContentResolver.OpenOutputStream(data.Data);
var dataToWrite = persistentStorageService.Read("DataToWrite", typeof(string));
var buffer = Encoding.ASCII.GetBytes((string)dataToWrite);
output.Write(buffer, 0, buffer.Length);
output.Close();
result = buffer;
I want to save file in custom extension.
The issue is your MimeType, it needs to be set to octet for custom file types:
intent.SetType("application/octet");
Once you do that all you need to do is StartActivityForResult and you are done.
Activity.StartActivityForResult(intent, resultCode);
Make sure your extension type is a part of the file name itself, you can assign that through intent as well
intent.PutExtra(Intent.ExtraTitle, fileName);
Related
Using FilePicker one can open an existing file:
FileResult file = await FilePicker.PickAsync();
TextView textview = FindViewById<TextView>(Resource.Id.textview);
string path = file.FullPath;
var handle = File.Open(path, FileMode.OpenOrCreate);
byte[] data = new byte[10];
handle.Read(data, 0, 10);
Is there a similar way for saving a new file?
For now, the FilePicker plugin is only designed to pick existing files.
On Android and iOS, you could not do that. But on UWP, you could use the FileSavePicker.
Xamarin: https://learn.microsoft.com/en-us/xamarin/essentials/file-picker?tabs=android
UWP: https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-save-a-file-with-a-picker
I am trying to import Attachments/Annotations to CRM Dynamics, I am doing this using the SDK.
I am not using the data import wizard.
I am not individually creating Annotation entities, instead I am using Data Import Feature programmatically.
I mostly leveraged the DataImport sample from the SDK sample code (SDK\SampleCode\CS\DataManagement\DataImport).
Import import = new Import()
{
ModeCode = new OptionSetValue((int)ImportModeCode.Create),
Name = "Data Import"
};
Guid importId = _serviceProxy.Create(import);
_serviceProxy.Create(
new ColumnMapping()
{
ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId),
ProcessCode = new OptionSetValue((int)ColumnMappingProcessCode.Process),
SourceEntityName = sourceEntityName,
SourceAttributeName = sourceAttributeName,
TargetEntityName = targetEntityName,
TargetAttributeName = targetAttributeName
});
I am getting an error "The reference to the attachment could not be found".
The documentation says the crm async service will find the physical file on disk and upload it, my question is where does the async service look for attachment files?
I tried to map documentbody field to the full path of the attachment on the desk, but that still didn't work.
The answer below was provided before the question edits clarifying the use of the import wizard instead of the SDK. The answer below is specific to using the SDK.
When you are attaching files to an Annotation (Note) record in CRM via the SDK, you do use the documentbody attribute (along with mimetype), but you have to first convert it base64.
Something like this:
var myFile = #"C:\Path\To\My\File.pdf";
// Do checks to make sure file exists...
// Convert to Base64.
var base64Data = Convert.ToBase64String(System.IO.File.ReadAllBytes(myFile));
var newNote = new Entity("annotation");
// Set subject, regarding object, etc.
// Add the data required for a file attachment.
newNote.Attributes.Add("documentbody", base64Data);
newNote.Attributes.Add("mimetype", "text/plain"); // This mime type seems to work for all file types.
orgService.Create(newNote);
I found the solution in an obscure blog post, I think the documentation is misleading or unclear, the way this whole thing works, makes having the files available on the server disk for the async to process, odd.
To follow the same principle, all contents should be sent like the csv file itself while being linked to the same import.
To solve this we need create individual special Internal ImportFile for each physical attachment, and link it to the import that has the attachments record details.
As you see below with linking the attachments ImportFile using the ImportId and then setting the two properties (ProcessCode and FileTypeCode), it all worked in the end.
Suffice to say using this method is much more efficient and quicker than individually creating Annotation records.
foreach (var line in File.ReadLines(csvFilesPath + "Attachment.csv").Skip(1))
{
var fileName = line.Split(',')[0].Replace("\"", null);
using (FileStream stream = File.OpenRead(attachmentsPath + fileName))
{
byte[] byteData = new byte[stream.Length];
stream.Read(byteData, 0, byteData.Length);
stream.Close();
string encodedAttachmentData = System.Convert.ToBase64String(byteData);
ImportFile importFileAttachment = new ImportFile()
{
Content = encodedAttachmentData,
Name = fileName,
ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId),
UseSystemMap = true,
ImportId = new EntityReference(Import.EntityLogicalName, importId),
ProcessCode = new OptionSetValue((int)ImportFileProcessCode.Internal),
FileTypeCode = new OptionSetValue((int)ImportFileFileTypeCode.Attachment),
RecordsOwnerId = currentUserRef
};
_serviceProxy.Create(importFileAttachment);
}
idx++;
}
I am making a Windows Store application and I want to allow users that press an "Export To Word" button to have all the data that they have input into the app to be displayed in a Word document and saved to a desired location on their computer. The code below is a test segment of code that almost does what I am after, however after saving the document and opening it using Word rather than the app, it cannot open the file due to it being corrupted apparently. However when you open it in Notepad the text is displayed as I want.
private async void exportToWord_Click(object sender, RoutedEventArgs e)
{
await ExportToWord();
}
private async Task ExportToWord()
{
// Create the picker object and set options
Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Word", newList<string>{".docx"});
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "Test";
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
MessageDialog mD;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish
// making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
await Windows.Storage.FileIO.WriteTextAsync(file, createContentsOfFile());
// Let Windows know that we're finished changing the file so the other
// app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.Provider.FileUpdateStatus updateStatus = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (updateStatus == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
mD = newMessageDialog("Connect exported to:" + file, "Export Successful");
}
else
{
mD = newMessageDialog("Could not save file. Try again", "Export Unsuccessful");
}
}
else
{
mD = newMessageDialog("Operation canceled because the file could not be found. Try again", "Export Unsuccessful");
}
await mD.ShowAsync();
}
private string createContentsOfFile()
{
return "Testing...";
}
I believe the issue is that I am outputting plain text to the Word document but it needs to be in a certain format to be output correctly and be displayed in a Word doc. Is there any way of doing this in Windows Store apps?
Any help would be appreciated.
I'm not aware of any Word doc components available for Windows Runtime apps (Microsoft doesn't provide one, but there could be a third party component I'm not aware of).
You can get documentation on the docx format and for simple text it may not be too complex (I'm not sure), or you can use another format which Word can open.
If you don't need formatting I'd probably stick with txt.
If you need small amounts of formatting then rtf is a good option. It is fairly simple to generate yourself or the RichEditBox can export RTF format text which you can then save into a .doc file and open in Word.
When the first time my app starts on a windows phone, I want to get some files(xml/images) from project folders and write them to the isolated storage .
How do I detect that my app is running for the first time?
How do I access file in project folders?
Here is another way to read files from your visual studio project. The following shows how to read a txt file but can be used for other file as well. Here the file is in the same directory as the .xaml.cs file.
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
make sure your file is marked as Content.
If you mean project folders as in the folders in your visual studio project, I usually right click on the files and set the build action to 'Embedded Resource'. At runtime, you can read the data from the embedded resource like so:
// The resource name will correspond to the namespace and path in the file system.
// Have a look at the resources collection in the debugger to figure out the name.
string resourcePath = "assembly namespace" + "path inside project";
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resources = assembly .GetManifestResourceNames();
List<string> files = new List<string>();
if (resource.StartsWith(resourcePath))
{
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource), Encoding.Default);
files.Add(reader.ReadToEnd());
}
To read the images you would need something like this to read the stream:
public static byte[] ReadAllBytes(Stream input)
{
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
I am in the process of writing a custom event receiver. The basic flow is as follows:
Document is added to Library
Based on metadata of document, we check to see if a folder within another document library exists.
If the folder does not exist, it is created.
The newly added document is copied to the folder residing in another document library.
I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.
Here is my code so far:
SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
Answer
//Ensure folder here
var destFolder = destLib.RootFolder.SubFolders["name"];
destFile = destFolder.Files.Add(sourceFile.Name, stream);