Unable to Read Blob Storage account Directories and sub Directories - blob

I am trying to read directories and sub directories of the storage account and unable to read, below is the sample code and attached blob container structure snapshot
sample code:
CloudBlobContainer container = Retrier<CloudBlobContainer>.TryWithDelayIncremental(() => blobclient.GetContainerReference(ContainerName), NoOfRetries, DelayInMilliSecs);
var directory = container.GetDirectoryReference(#"policies /Initiatives");
var folders = directory.ListBlobs().Where(b => b as CloudBlobDirectory != null).ToList();
foreach (var folder in folders)
{
Console.WriteLine(folder.Uri);
}
folder structure:
container and folder:

Based on your capture, policies is the name of your container, if you want to get all URIs of folders under /Initiatives in container policies, you should not involve container name in directory reference name, try the code below :
CloudBlobContainer container = blobClient.GetContainerReference("policies");
var directory = container.GetDirectoryReference(#"Initiatives");
var folders = directory.ListBlobs().Where(b => b as CloudBlobDirectory != null).ToList();
foreach (var folder in folders)
{
Console.WriteLine(folder.Uri);
}
Test result on my side :

Related

Easy way to retrieve image source in abp

I'm pretty new to ABP Framework and probably this question has a really simple answer, but I haven't managed to find it. Images are an important part of any app and handling them the best way (size, caching) is mandatory.
Scenario
setup a File System Blob Storing provider. This means that the upload file will be stored in the file system as an image file
make a service that uses a Blob container to save and retrieve the image. So, after saving it, I use the unique file name as a blob name. This name is used to retrieve it back.
the user is logged in, so authorization is required
I can easily obtain the byte[]s of the image by calling blobContainer.GetAllBytesOrNullAsync(blobName)
I want to easily display the image in <img> or in datatable row directly.
So, here is my question: is there an easy way to use a blob stored image as src of a <img> directly in a razor page? What I've managed to achieve is setting in the model, a source as a string made from image type + bytes converted to base 64 string (as here) however in this case I need to do it in the model and also I don't know if caching is used by the browser. I don't see how caching would work in this case.
I am aware that this may be a question more related to asp.net core, but I was thinking that maybe in abp there is some way via a link to access the image.
If you have the ID of the blob then it is easy to do. Just create a Endpoint to get the Image based on the blob id.
Here is the sample AppService
public class DocumentAppService : FileUploadAppService
{
private readonly IBlobContainer<DocumentContainer> _blobContainer;
private readonly IRepository<Document, Guid> _repository;
public DocumentAppService(IRepository<Document, Guid> repository, IBlobContainer<DocumentContainer> blobContainer)
{
_repository = repository;
_blobContainer = blobContainer;
}
public async Task<List<DocumentDto>> Upload([FromForm] List<IFormFile> files)
{
var output = new List<DocumentDto>();
foreach (var file in files)
{
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream).ConfigureAwait(false);
var id = Guid.NewGuid();
var newFile = new Document(id, file.Length, file.ContentType, CurrentTenant.Id);
var created = await _repository.InsertAsync(newFile);
await _blobContainer.SaveAsync(id.ToString(), memoryStream.ToArray()).ConfigureAwait(false);
output.Add(ObjectMapper.Map<Document, DocumentDto>(newFile));
}
return output;
}
public async Task<FileResult> Get(Guid id)
{
var currentFile = _repository.FirstOrDefault(x => x.Id == id);
if (currentFile != null)
{
var myfile = await _blobContainer.GetAllBytesOrNullAsync(id.ToString());
return new FileContentResult(myfile, currentFile.MimeType);
}
throw new FileNotFoundException();
}
}
Upload function will upload the files and Get function will get the file.
Now set the Get route as a src for the image.
Here is the blog post: https://blog.antosubash.com/posts/dotnet-file-upload-with-abp
Repo: https://github.com/antosubash/FileUpload

Trouble getting a file from Azure container

I am trying to get a file from Azure container. I need to read its content.
The file has been uploaded to umbraco media, media are stored in our Azure container.
Its normal (umbraco) url would be like:
~/media/10890/filename.xls
I am trying to retrieve it like this:
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["strorageconnstring"]);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("storagemedia");
The thing is - I am not sure how I am supposed to retrieve a particular file? I tried:
1.
CloudBlobDirectory dira = container.GetDirectoryReference("10890"); // file folder within media
var list = dira2.ListBlobs(useFlatBlobListing: true).ToList(); // Returns error saying "The requested URI does not represent any resource on the server."
However the 10890 folder within media storage exists and I can browse it with storage browser.
2.
CloudBlockBlob blobFile = container.GetBlockBlobReference("10890/filename.xls");
string text;
using (var memoryStream = new MemoryStream())
{
blobFile.DownloadToStream(memoryStream); // Throws "The specifed resource name contains invalid characters." error
var length = memoryStream.Length;
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Any idea how to read the file? And what am I doing wrong?
Thank You Gaurav for providing your suggestion in comment section.
Thank You nicornotto for confirming that your issue got resolved by changing the container name reference in the below statement.
var container = blobClient.GetContainerReference("storagemedia");

Exception when listing created sub-directory in documents directory

I am using the official API to list a directory I had created for some purpose and have pushed few files into it. Now I want to list them out.
Here's how I am creating first
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Movies/flutter_test';
final String dirPath = '${extDir.path}/mydir';
await new Directory(dirPath).create(recursive: true);
Here's what I am doing to read in a different page.
final Directory extDir = await getApplicationDocumentsDirectory();
// final String dirPath = '${extDir.path}/Pictures/flutter_test';
final String dirPath = '${extDir.path}/mydir';
final String thumbDirPath = '$dirPath/thumbs';
final Directory imgDir = Directory.fromUri(Uri.file(dirPath));
dirExists = imgDir.existsSync();
fileCount = 0;
if(dirExists) {
print("my dir exists");
// thumbDir.list(recursive: false, followLinks: false)
fileCount = await imgDir.list(recursive: false).length;
print('mydir images count $fileCount');
if(fileCount > 1) { // we think one is always the directory itself?
try {
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
The code breaks here giving the following exception message
type '() => Null' is not a subtype of type '(Object) => FutureOr<dynamic>'
I have to also tell you this doesn't happen when I am listing the external storage directory. Am I doing something wrong while creating my directory?
EDIT
I have now upgraded flutter to 0.7.3 on my Mac, and have a new problem altogether. The application won't run at all.
Okay, I found a solution myself. Apparently tinkering with the large provider API has given me different way to list the items, which actually told me I was trying to run listeners twice.
fileCount = await imgDir.list(recursive: false).length;
and
imgDir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
from original code cannot be written one after the other, as the first one finishes the listener. This I found out by altering my own code and listing directories this way instead.
Stream<FileSystemEntity> files = imgDir.list(recursive: false, followLinks: false);
will add as many events as many files according to API.. and then create a regular generic list
List<FileSystemEntity> entities = await files.toList();
and then you perform usual iteration using iterator or for() loop like
for(FileSystemEntity entity in entities) {
... // every file now is available

Upload file with meta data and checkin to sharpoint folder using Client Object Model

Hi I'm trying to upload a file to sharepoint 2010 using the client api with meta data and also checkin the file after I'm done. Below is my code:
public void UploadDocument(SharePointFolder folder, String filename, Boolean overwrite)
{
var fileInfo = new FileInfo(filename);
var targetLocation = String.Format("{0}{1}{2}", folder.ServerRelativeUrl,
Path.AltDirectorySeparatorChar, fileInfo.Name);
using (var fs = new FileStream(filename, FileMode.Open))
{
SPFile.SaveBinaryDirect(mClientContext, targetLocation, fs, overwrite);
}
// doesn't work
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//check out to make sure not to create multiple versions
newFile.CheckOut();
// use OverwriteCheckIn type to make sure not to create multiple versions
newFile.CheckIn("test", CheckinType.OverwriteCheckIn);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//SPFile uploadFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
//uploadFile.CheckOut();
//uploadFile.CheckIn("SOME VERSION COMMENT I'D LIKE TO ADD", CheckinType.OverwriteCheckIn);
//mClientContext.ExecuteQuery();
}
I'm able to upload the file but I can't add any meta data and file is checked out. I want to add some meta data and checkin the file after I'm done.
My SharePointFolder class has the serverRelativeUrl of the folder path to upload to. Any help greatly appreciated.
You need a credential before the executeQuery(); and SaveBinaryDirect();
For example:
mClientContext.Credentials = new NetworkCredential("LoginID","LoginPW", "LoginDomain");
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();

Getting Location path Wix installation

How to get location path if i want to access mylocation.txt file, this file currently is in E:drive.
[CustomAction]
public static ActionResult FillList(Session xiSession)
{
//Can i get store mylocation.txt into application root instead of E location
string path = "Mylocation.txt";
// Open the file to read from.
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
//Console.WriteLine(s);
FillComboBox(xiSession, s, s);
}
xiSession["COUNTRIES"] = "--Select Location--";
return ActionResult.Success;
}
Can i get store mylocation.txt into application root instead of E location.And how mylocation.txt can be called?Basically what i want is to get the values of combox from this text file,once installation is in progress.
Attach the Mylocation.txt as resource file in Custom action project. Get more details from this discussion.