Google Drive - Authorize once on a single machine - google-app-engine

I am new to Google Drive and have following scenarios for which I am not able to find anything (not sure if anything exists or not)
โ€“> I am creating a Windows app which will be SAAS based. Different Users will register and create their company logins and subusers under them. Now I want them to put the google drive credentials in one of the form and this should work for rest of the users. Currently the problem is that while development I got the google log in done and it never asks for the login again but when testing on a different system with different login, it keeps asking for google login. I simply want admin users to put their google drive credentials and it should work for upload and download files for all the users for that company.
โ€“> I want to keep versions of the same file (just like google drive does by default) on google drive. Lets say user A uploaded file xyz and then user B downloaded and changed file xyz and uploaded it on the drive again.
I want 2 things here โ€“ only the changed content should get uploaded and not the whole file (this will save time for the user)
2ndly I want to have history of the same file so I can show in my Windows application
#region Get Service Object
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "GoogleDriveClientID",
ClientSecret = "GoogleDriveClientSecret"
},
new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;
// Create the service.
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AppName",
});
#endregion
#region Uploading
public void uploadOnGoogleDrive(ObservableCollection<JobAttachments> AttachmentsColl, bool IsDocSaved)
{
try
{
service = getServiceObject();
List<Google.Apis.Drive.v2.Data.File> fileList = retrieveAllFiles(service);
List<Google.Apis.Drive.v2.Data.File> directoryList = GetDirectoryList(service);
if (IsDocSaved)
{
#region for checking if the file already exists
foreach (Google.Apis.Drive.v2.Data.File item in fileList)
{
foreach (JobAttachments attach in AttachmentsColl)
{
if (item.Title == attach.AttachmtGUID)
{
MessageBoxResult result = System.Windows.MessageBox.Show(LogMessages.GetResourceMessage(LogMessages.MessageEnumeration.GD_AlreadyExistsMsg), "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
//DeleteFile(service, item);
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = attach.AttachmtGUID;
body.MimeType = item.MimeType;
fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(attach.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.UpdateMediaUpload request = service.Files.Update(body, item.Id, stream, item.MimeType);
request.Upload();
}
else
{
return;
}
break;
}
}
}
#endregion
}
else
{
#region for direct uploading on google drive
if (AttachmentsCollection != null && AttachmentsCollection.Count > 0)
{
string folderID = string.Empty;
if (_IsProject)
{
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(folderID))
{
Google.Apis.Drive.v2.Data.File foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
folderID = file.Id;
}
}
else
{
//project folder
string prjFolder = string.Empty;
string tskFolder = string.Empty;
Google.Apis.Drive.v2.Data.File foldbody;
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
prjFolder = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(prjFolder))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
prjFolder = file.Id;
}
//task folder
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_TaskName) && dir.Parents[0].Id.Equals(prjFolder))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrWhiteSpace(folderID))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _TaskName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = prjFolder } };
Google.Apis.Drive.v2.Data.File file1 = service.Files.Insert(foldbody).Execute();
folderID = file1.Id;
}
}
foreach (JobAttachments item in AttachmentsColl)
{
if (!string.IsNullOrEmpty(item.AttachmentName))
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = item.AttachmtGUID;
body.MimeType = item.MimeType;
body.Parents = new List<ParentReference>() { new ParentReference() { Id = folderID } };
//fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(item.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, item.MimeType);
request.Upload();
}
}
}
#endregion
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
throw ex.InnerException;
}
}
#endregion
#region Download File
private async Task DownloadFile(DriveService service, string url, string title, long? fSize)
{
service = getServiceObject();
var downloader = new MediaDownloader(service);
//downloader.ChunkSize = 256 * 1024;
downloader.ProgressChanged += Download_ProgressChanged;
var fileName = string.Empty;
//for downloading on system
var SaveFileDialog = new SaveFileDialog();
SaveFileDialog.Title = "Save As";
SaveFileDialog.FileName = title;
Nullable<bool> result = SaveFileDialog.ShowDialog();
if (result == true)
fileName = SaveFileDialog.FileName;
else if (result == false)
{
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
return;
}
else
{
if (Directory.Exists(#"\Downloads"))
fileName = #"\Downloads\" + title;
}
if (!string.IsNullOrWhiteSpace(fileName))
using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
fileSize = fSize;
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status.ToString() == DownloadStatus.Completed.ToString())
{
fName = fileStream.Name;
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
fileStream.Flush();
}
if (progress.Status.ToString() == DownloadStatus.Failed.ToString())
{
HandleDocuments.IsEditButtonClicked = false;
MessageBox.Show("Failed......." + progress.Exception.Message);
}
}
}
#endregion
#region Delete File
private Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
{
service = getServiceObject(); //comment this if calling from another function; create the service object in that function and pass it as parameter to this function.
service.Files.Delete(file.Id).ExecuteAsync();
service.Files.EmptyTrash();
return null;
}
#endregion
#region Get all Directories and Files from Google Drive
public List<Google.Apis.Drive.v2.Data.File> GetDirectoryList(DriveService service)
{
//Creating the global list
List<Google.Apis.Drive.v2.Data.File> AllDirectories = new List<Google.Apis.Drive.v2.Data.File>();
//setting up the Request.
FilesResource.ListRequest request = service.Files.List();
//MaxResults: How many we want back at a time max is 1000
request.MaxResults = 1000;
//Q: Search results. all i want are folders that havent been trashed (deleted)
request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";
do
{
try
{
// getting the results
FileList files = request.Execute();
// adding the results to the list.
AllDirectories.AddRange(files.Items);
// If there are more results then your MaxResults you will have a nextPageToken to get the rest of the results.
request.PageToken = files.NextPageToken;
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
List<Google.Apis.Drive.v2.Data.File> DirsInRoot = AllDirectories.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().IsRoot.Value : false).ToList<Google.Apis.Drive.v2.Data.File>();
List<string> HirearcyList = new List<string>();
// The first Dir is Root it doesnt get returned. But we need it if we
// Want to be able to list the files that are in the root dir.
HirearcyList.Add("Root");
// recersive magic here.
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInRoot)
{
HirearcyList.Add(" " + myDir.Title);
HirearcyList.AddRange(RecsiveDir(AllDirectories, myDir.Id, " "));
}
return AllDirectories;
}
public List<String> RecsiveDir(List<Google.Apis.Drive.v2.Data.File> allDirs, string ParentId, string Prefix)
{
List<string> result = new List<string>();
List<Google.Apis.Drive.v2.Data.File> DirsInParentId = allDirs.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().Id == ParentId : false).ToList<Google.Apis.Drive.v2.Data.File>();
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInParentId)
{
result.Add(Prefix + myDir.Title);
result.AddRange(RecsiveDir(allDirs, myDir.Id, Prefix + " "));
}
return result;
}
public static List<Google.Apis.Drive.v2.Data.File> retrieveAllFiles(DriveService service)
{
List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>();
FilesResource.ListRequest request = service.Files.List();
request.MaxResults = 1000;
do
{
try
{
FileList files = request.Execute();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
//service.Revisions.List(files.Items[0].Id) // for getting the file Revision history
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
#endregion
Thanks
Jatinder

Related

Share a TXT file between two android application Android 11 and Android 12

I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.
I tried with MediaStore:
MAIN APP :
private static void saveLanguageOnFile(String lang, String country){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
boolean success;
if (!folderDocuments.exists()) {
try {
folderDocuments.mkdir();
} catch (Exception ex) {
ex.printStackTrace();
}
}
success = folderDocuments.exists();
if (success) {
try {
FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
fos.write((lang + "-" + country).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
long idFile = -1;
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
String fileName = cursor.getString(columnIndexDisplayName);
if (fileName.equals("language.txt")) {
idFile = cursor.getLong(columnIndexId);
break;
}
}
}
cursor.close();
}
Uri uriFile;
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt"); // file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
uriFile = contentResolver.insert(contentUri, values);
}
try {
if (uriFile != null) {
OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
if (outputStream != null) {
outputStream.write((lang + "-" + country).getBytes());
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ANDROID LAUNCHER APP :
private fun setLanguage() {
var lang = Locale.getDefault().language
var country = Locale.getDefault().country
val previousLang = lang
val previousCountry = country
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
if (language.exists()) {
try {
val br = BufferedReader(FileReader(language))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
Log.e("LauncherDMD", ".loadFile: err: " + e.message)
}
}
} else {
val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentResolver: ContentResolver = application.applicationContext.contentResolver
val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)
var idFile: Long = -1
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
val fileName = cursor.getString(columnIndexDisplayName)
if (fileName.contains("language")) {
idFile = cursor.getLong(columnIndexId)
break
}
}
}
cursor.close()
}
val uriFile: Uri
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile)
try {
val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val locale = Locale(lang,country)
Lingver.getInstance().setLocale(this.applicationContext, locale)
if(!previousCountry.equals(country) && !previousLang.equals(lang)){
recreate()
}
Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.
Thanks in advance!

How to make Vaadin FtpDataProvider properly show files from a specific FTP path

I'm using Vaadin14 in my application and I'm trying to connect to an FTP showing files contained in it under a specific path. I imported the filesystemdataprovider library but I'm unable to make it work.
This is how i connect to my FTP:
void open() throws IOException {
ftp = new FTPClient();
try {
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftp.connect(server, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new IOException("Exception in connecting to FTP Server");
}
ftp.login(user, password);
ftp.enterRemotePassiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
logger.info("Logging su FTP effettuato correttamente");
ftp.printWorkingDirectory();
ftp.changeWorkingDirectory("Utenti/" + SessionManager.utenteCorrente().getEntityKey() +"/DOCUMENTI/ASSEGNATI/04 MODULO CONDUCENTE");
} catch (Exception e) {
Notifier.notifyErrorMessage("Si รจ verificato un errore in fase di connessione");
logger.error("Errore in fase di connessione all'FTP");
logger.error(e.toString(), e);
AppEventBus.post(new DocAssegnatiEvent.ChiudiWindowRequest());
}
}
Then, I pass my configured FTPClient to FtpSelect class where I build the Tree
public SelezioneDocAssegnatiFtpBox(FTPClient client, String filter) {
super(null);
this.client = client;
if (filter != null) this.filter = filter;
getElement().getStyle().set("display", "flex");
getElement().getStyle().set("flex-direction", "column");
setErrorLabelStyles(errorLabel);
errorLabel.setVisible(false);
HorizontalLayout indicators = new HorizontalLayout();
indicators.setSpacing(false);
indicators.setMargin(false);
label.setVisible(false);
required.setVisible(false);
indicators.add(required,label);
setLabelStyles(label);
setLabelStyles(required);
content = setupTree();
add(indicators,content,errorLabel);
}
private Component setupTree() {
if (filter != null) {
root = new FtpData(client, filter, true);
} else {
root = new FtpData(client, true);
}
FtpDataProvider fileSystem = new FtpDataProvider(root);
tree.setDataProvider(fileSystem);
tree.addHierarchyColumn(FtpFile::getName,file -> FileTypeResolver.getIcon(file),file -> getFileDescription(file));
setupTreeStyles(tree, SelectionMode.SINGLE);
tree.addSelectionListener(event -> {
//event
});
setSizeFull();
return tree;
}
private String getFileDescription(FtpFile file) {
String desc = "";
if (!file.isDirectory()) {
Date date = Date.from(file.getTimestamp().toInstant());
long size = file.getSize();
String unit = "";
if (size > GIGA) {
size = size / GIGA;
unit = "GB";
}
else if (size > MEGA) {
size = size / MEGA;
unit = "MB";
}
else if (size > KILO) {
size = size / KILO;
unit = "KB";
} else {
unit = "B";
}
desc = file.getName()+", "+date+", "+size+ " "+unit;
} else {
desc = root.getChildrenFromFilesystem(file).size()+" "+filesText;
}
return desc;
}
I followed the source code of the add-on library, but nothing seems to work.
I also tried to access the Ftp with the default path (/) but nothing.
this is what I get
PS. the console isn't showing any error
Anyone has any idea or has tried this library to connect to an FTP?
Thanks in advance

Use Glide to display an image saved into external storage MediaStore

Before last Android 11 update, I used to get the file path of my external image to display it on Glide. Because of the last update, I now need to use MediaStore storage option to store my images in external. I successfully save my images but I have a problem retrieving it and displaying it on glide.
I tried to use the code from this question to get the uri :
public Uri getUriFromContentResolver(String fileName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getApplicationContext().getContentResolver();
Cursor queryCursor = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.RELATIVE_PATH}, MediaStore.Images.Media.DISPLAY_NAME + "=? ",
new String[]{fileName}, null);
if (queryCursor != null && queryCursor.moveToFirst()) {
return ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, queryCursor.getLong(0));
} else {
return null;
}
} else {
return null;
}
}
And retrieve it to display it on glide :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri uriFromContentResolver = new ImageManager(context).getUriFromContentResolver(listPicture.get(pos).getFileName());
if (uriFromContentResolver !=null) {
System.out.println("Uri " + uriFromContentResolver.toString());
Glide.with(context)
.load(uriFromContentResolver)
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);
}
} else {
Glide.with(context)
.load(listPicture.get(pos).getPath())
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);
}
I also tested glide to load with the path from uri.getPath() when I save the file using this :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
String path = imageUri.getPath();
I'm not used to the MediaStore system, I will take any advice. Thanks.
I created a class to get the Uri of the file by using the file name
Uri uriFromContentResolver = getUriFromContentResolver(fileName);
public Uri getUriFromContentResolver(String fileName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getApplicationContext().getContentResolver();
Cursor queryCursor = resolver.query(
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL),
new String[]{
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.RELATIVE_PATH},
MediaStore.Images.Media.DISPLAY_NAME + " = ?",
new String[]{fileName}, null);
if (queryCursor != null && queryCursor.moveToFirst())
{
return ContentUris.withAppendedId(
MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL),
queryCursor.getLong(0));
} else
{
return null;
}
} else {
return null;
}
}
Once we have it we call this function with the Uri we just got to get a Path
String path = getRealPathFromURI(uriFromContentResolver);
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
And with this path, Glide can read the file
Glide.with(context)
.load(path)
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);

Can't get URI for selecting any file from download folder in MI-Oreo(MI-A2) device in android

I need help in fetching file path of contents that we pick from downloads folder or any other folder through Intent.
I am attaching a fileUtil class that I have been using and it works well till Nougat version. But with oreo and that too in some specific devices, we receive a null path in return. So if anyone has faced such an error and found a solution to this, then please share here.
if(resultCode ==RESULT_OK)
{
final Uri uri = data.getData();
// Get the File path from the Uri
String path = FileUtils.getPath(this, uri);
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
//File file = new File(path);
this.file = new File(path);
profile_imagepath = path;
filename = file.getName();
txtselectedfile.setText(filename);
}
}
You can try to use ACTION_PICK for api level above 26 to get this issue fixed, instead of using ACTION_GET_CONTENT.
Try and hope this helps you.
1) Open file intent.
Intent intent = new Intent()
.setType("*/*")
.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Select a file"), REQUEST_CODE);
2)get download document path using below method.
if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
/* final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
final boolean isOreo = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
}
}

How does one connect to the RootDSE and/or retrieve NetBiosDomain Name with System.DirectoryServices.Protocols?

In case of Directory Entry, one can connect and find the NetBios Domain name as follows :-
private string GetNetbiosDomainName(string dnsDomainName)
{
string netbiosDomainName = string.Empty;
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string configurationNamingContext = rootDSE.Properties["configurationNamingContext"][0].ToString();
DirectoryEntry searchRoot = new DirectoryEntry("LDAP://cn=Partitions," + configurationNamingContext);
DirectorySearcher searcher = new DirectorySearcher(searchRoot);
//searcher.SearchScope = SearchScope.OneLevel;
searcher.PropertiesToLoad.Add("netbiosname");
searcher.Filter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", dnsDomainName);
SearchResult result = searcher.FindOne();
if (result != null)
{
netbiosDomainName = result.Properties["netbiosname"][0].ToString();
}
return netbiosDomainName;
}
where dnsDomainName is a Fully qualified Domain name .
However, in case of System.DirectoryServices.Protocols , How can one connect and find such NetBios Domain name when fully qualified domain name is given ?
Here is the solution i have got in one research paper:-
private string GetDomainNetBios(string sDomainFqdn,NetworkCredential netCred)
{
string sNetBios=string.Empty;
LdapDirectoryIdentifier oLdapDirectory = null;
LdapConnection oLdapConnection = null;
try
{
oLdapDirectory = new LdapDirectoryIdentifier(sDomainFqdn, 389);
oLdapConnection = (netCred == null)
? new LdapConnection(oLdapDirectory)
: new LdapConnection(oLdapDirectory, netCred);
oLdapConnection.Timeout = TimeSpan.FromSeconds(45);
oLdapConnection.SessionOptions.TcpKeepAlive = true;
oLdapConnection.SessionOptions.ProtocolVersion = 3;
//prevents ldap connection from connecting to other servers during session
oLdapConnection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
oLdapConnection.AutoBind = false;
oLdapConnection.Bind();
SearchResponse dirRes = (SearchResponse)_ldapConnectionUsers.SendRequest(new
SearchRequest(
null,
"configurationNamingContext=*",
SearchScope.Base,
"configurationNamingContext"
));
if (dirRes != null)
{
string sConfPartDn =
dirRes.Entries[0].Attributes["configurationNamingContext"][0].ToString();
dirRes = (SearchResponse)_ldapConnectionUsers.SendRequest(new SearchRequest(
sConfPartDn,
String.Format(CultureInfo.InvariantCulture,"(&(nETBIOSName=*)(dnsRoot={0}))", sDomainFqdn),
SearchScope.Subtree,
"nETBIOSName"
));
}
if (dirRes != null && dirRes.Entries.Count > 0)
{
sNetBios = dirRes.Entries[0].Attributes["nETBIOSName"][0].ToString();
}
return sNetBios;
}
catch (Exception ex)
{
throw new Exception(string.Format(CultureInfo.InvariantCulture,"{0}::{1}", new StackFrame(0,
true).GetMethod().Name, PvssMgrException.ToString(ex)));
}
finally
{
oLdapConnection.Dispose();
}
}

Resources