Get contents of OneDrive folder via shared link (URL) - c#

I've got a URL to a OneDrive folder (https://1drv.ms/f/s!AtXoQFW327DIyMwPjZhmauUCSSHXUA). Everyone with that link can access the folder via browser.
Now, my goal is to create an .NET application that, given that link, is able to get a list of the files/folders inside that folder.
Is that even possible?

The best way to do this is to use the OneDrive API exposed via Graph.
You can read the "Using Sharing Links" documentation for full details, but you'd essentially make a call to:
https://graph.microsoft.com/v1.0/shares/u!aHR0cHM6Ly8xZHJ2Lm1zL2YvcyFBdFhvUUZXMzI3REl5TXdQalpobWF1VUNTU0hYVUE/driveItem/children
You can also use the .NET SDK to avoid making the calls to the API yourself, in which case your code would look something like:
client.Shares["u!aHR0cHM6Ly8xZHJ2Lm1zL2YvcyFBdFhvUUZXMzI3REl5TXdQalpobWF1VUNTU0hYVUE"].DriveItem.Children.Request().GetAsync();

Selenium Web Driver is good option for tasks like that.
Open Solution Explorer.
Right Click on your project.
Select Manage NuGet Packages..
Browse and install these two : Selenium.Chrome.WebDriver and Selenium.WebDriver.
You have just installed selenium to your project!
So now, we need to create a driver service, and find needed elements in our website.
As far as i see, filenames are stored as a span class named signalFieldValue_03700093.
But "Last Modified infos" are stored under this class too, i needed to skip "Last Modified infos" using the code below:
bool skip = false;
List<string> myFiles = new List<string>();
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
ChromeOptions option = new ChromeOptions();
var driver = new ChromeDriver(service, option);
driver.Url = "https://1drv.ms/f/s!AtXoQFW327DIyMwPjZhmauUCSSHXUA";
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
foreach (IWebElement element in driver.FindElements(By.XPath("//span[#class='signalFieldValue_03700093']")))
{
if (!skip)
{
myFiles.Add(element.Text);
skip = true;
}
else
skip = false;
}
As a result, we have our filenames in string array named myFiles.
Hope this helps!

Related

C# Selenium Webdriver

I started using selenium with CS and have one issue. When code is compiled, program cannot find webdriver path, because it's being moved into the .exe file. I fixed this problem, by copying driver into the bin folder, so program can access it again. However, I want it to be able to access that driver inside .exe file.
I was doing this in python using os path:
def resource_path(relative_path: str) -> str:
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.dirname(__file__)
return os.path.join(base_path, relative_path)
If anyone knows how to do this in cs, please let me know.
Code that I'm using in c#:
var browser = new EdgeDriver();
browser.Navigate().GoToUrl(link);
webdrivermanager should be more helpful here. you can add its Nuget and use to manage drivers for browsers without requiring the driver exe files.
I use something like this and call this method everytime I need a browser.
public static InternetExplorerDriver InitBrowser(string browserName)
{
switch (browserName)
{
case "IE":
{
var IE_DRIVER_PATH = #"C:\PathTo\IEDriverServer";
InternetExplorerDriver driver = new InternetExplorerDriver(IE_DRIVER_PATH);
return driver;
}
}
return null;
}
This allows you to define the path from which to grab the driver, and so you wont have to depend on it being in your BIN folder. There are other solutions but this is what I have that works really well for me. You are set up to use this method for other browsers by adding more switch cases, and also from here you can easily add your browser options. You can call the method in your tests using:
InternetExplorerDriver driver = InitBrowser(IE);
Here it is simplified without the switch case:
var IE_DRIVER_PATH = #"C:\PathTo\IEDriverServer";
InternetExplorerDriver driver = new InternetExplorerDriver(IE_DRIVER_PATH);

List the content of a given directory for different users, Linux

Using .NET Core, C#, Linux
I've searched around a bit and can't seem to find anything. Maybe it's not possible and I need a different approach?
Can someone kindly point me in the direction of how I can go about getting the directory listing for a given path for a specific username?
I am running a web application service as Root but need to check and return directories and files for a given username (no password is available) - to report directories and files that a given username has read-access to.
Say for example "/opt/mydata/" and in there I will have a number of directories that I will manually create and set the permissions for each user group. I.e. "/opt/mydata/user_1_readable" will be returned when I do a directory listing for user1 (because this user is in the respective permissions group, or is the owner, or it is set for everyone to read) but will not be returned for user2 (this user is not in the correct group).
Essentially, I want to "impersonate" or in Linux, do the equivalent of "sudo su user1" and report what directories/files are readable within "/opt/mydata/" for a given user.
I can get the directory listing and files fine running as Root. What I can't do / don't know how to is getting the directory listing for a specific user. The examples I found and tried are all Windows Identity and Windows Security specific.
E.g. I found this example but it seemed to apply to "Mono" which I am not running, but essentially I really want to do something along the lines of this:
// Impersonate a user
using (WindowsIdentity newId = new WindowsIdentity("user1"))
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
var content = _fileProvider.GetDirectoryContents(uri);
}
Is there some third party library or some other way please?
Resource:
Change current Linux user in a C# application running with Mono?
If you look at this issue on .net core repository, Proposal: Expose POSIX functions , it looks like it won't be implemented in .net core, but only in Mono.Posix.NETStandard.
The library is compatible with .net core 2.0, and it shouldn't be too hard to implement this yourself.
You could try something like this with the package to filter which files the user can read.
public UserHasReadPermission(string username, string file)
{
var user = new UnixUserInfo(username);
var file = new UnixFileInfo(file);
// Everyone has read permission
if (file.FileAccessPermissions.HasFlag(FileAccessPermissions.OtherRead))
return true;
// User owns the file and has read permission
if (file.OwnerUser == user && file.FileAccessPermissions.HasFlag(FileAccessPermissions.UserRead))
return true;
// User group owns the file and has read permission
if (file.OwnerGroup == user.Group && file.FileAccessPermissions.HasFlag(FileAccessPermissions.GroupRead))
return true;
return false;
}
Perhaps you want to read the /etc/passwd file to get users' directories?
Once you have that, you can then get all subdirs inside the folders:
List<string> AllFiles = new List<string>();
void ParsePath(string path)
{
string[] SubDirs = Directory.GetDirectories(path);
AllFiles.AddRange(SubDirs);
AllFiles.AddRange(Directory.GetFiles(path));
foreach (string subdir in SubDirs)
ParsePath(subdir);
}

Adding ChromeOptions for Selenium Webdriver C#

From what I understand, the default action of when the Webdriver finds an element is to scroll such that the element is as far up the top of the page as possible. This is an issue because the website I'm working on has a header so every time I try to click on a button, it will instead click on the header. Thus, I want to change the scroll setting so that the element will be at the bottom of the page.
From reading this I was able to find what I wanted to set, however, I'm unable to set the DesiredCapabilites or ChromeOptions when I initialise the ChromeDriver. Could some provide code/steps to do this please?
You can use something like this
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("intl.accept_languages", "en");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
var driver = new ChromeDriver(chromeOptions);
Edit-2
If the option you want to set doesn't work for you then try using actions
var elem = driver.FindElements(By.Id("your element"));
Actions action = new Actions(driver);
action.MoveToElement(elem).Click(elem).Perform();//move to list element that needs to be hovered
Edit-3
If the above also doesn't work then your next option is to use Javascript
var elem = driver.FindElements(By.Id("your element"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var success = js.ExecuteScript("arguments[0].click(); return true", elem);
As far as I know you can't change everything through addarguments.
There is a list of what you can do in the Github page. but I have a better solution. you can make your own default settings and save it as a chrome profile. for example I didn't find anything to change homepage with code but this works fine for almost evwerything.
you can use this code :
options.AddArguments( #"user-data -dir=C:\Users\kian\AppData\Local\Google\Chrome\User Data");
options.AddArgument("--profile-directory=Default");
make sure you write the right path and right profile name.
to check the profile name you can go to properties.
properties
you will see the profile name.
there is a good guide for what else u can do in link.

Cannot find referenced file after deploy C#

We are trying to create a website verifier for our internal site, to verify that all sites are up. For this, we use seleniums chromedriver.
We have 2 projects for this:
1 main project which executes the code.
1 "shared" project, which is shared between all of our different solution. This project contains data, which is used across multiple solutions.
We have placed the chromedriver in the shared project, and initialize it like this:
public static IWebDriver InitiateChromeDriver()
{
ChromeOptions option = new ChromeOptions();
option.AddUserProfilePreference("download.default_directory", downloadPath);
option.AddUserProfilePreference("disable-popup-blocking", "true");
var path = Path.GetFullPath("Utility");
Console.WriteLine(path);
IWebDriver driver = new ChromeDriver(path, option, TimeSpan.FromMinutes(20));
return driver;
}
This method is placed in the "Utility" folder, together with the Chromedriver.exe, and can run locally when debugging through Visual Studio.
When we deploy it to our production server, it cannot find the path to the chromedriver. The referenced path changes to C:\windows\system32\inetsrv\Utility\chromedriver.exe on our production server.
What is a better approach at referencing the file, and ensuring that the path is correct?
Try the below. Create a folder called drivers and add the chromedriver to it.
ChromeOptions options = new ChromeOptions();
option.AddUserProfilePreference("disable-popup-blocking", "true");
driver = new ChromeDriver(Path.Combine(GetBasePath, #"Drivers\\"), options);
public static string GetBasePath
{
get
{
var basePath =
System.IO.Path.GetDirectoryName((System.Reflection.Assembly.GetExecutingAssembly().Location));
basePath = basePath.Substring(0, basePath.Length - 10);
return basePath;
}
}

Get Folder names containing .sln and .java files in SharpSVN using C#

I want to search for .sln and .java files from a given remote URL: something like http://olfandsub1.olf.com/nyts/.
I tried the code below used to read all files but it isn't working. Could you please explain what the GetList function does in the code?
Also can you tell me if I could take a textbox value as the projectPath in the code?
What is the best way I could solve my problem?
bool gotList;
List<string> files = new List<string>();
using (SvnClient client = new SvnClient())
{
Collection<SvnListEventArgs> list;
gotList = client.GetList(projectPath, out list);
if (gotList)
{
foreach (SvnListEventArgs item in list)
{
files.Add(item.Path);
}
}
}
I also get the "PROPFIND of '/nyts': authorization failed: Could not authenticate to server: rejected Basic challenge (http://olfandsub1.olf.com <http://olfandsub1.olf.com/> )"
error even though my username and password are absolutely right.
Please let me know asap as I've been trying to implement this for 3 days now. Thanks.
You should add something like
client.Authentication.DefaultCredentials = new NetworkCredentials("user", "password");
Or more cleaner hook the events on the Authentication class and provide credentials only when needed.
(The SharpSvn.UI assembly contains the default UI you see in AnkhSVN)

Categories

Resources