//wraper method that allows the upload of its original folder public static void UploadFolderWraper(OAuth2Token token, String parentId, String localPathRoot) { DirectoryInfo di; di = new DirectoryInfo(localPathRoot); //console.WriteLine(di.Name); //console.WriteLine(di.FullName); UploadFolder(token, CreateFolder(token, parentId, di.Name, "Citrix Uploader"), di.FullName); }
public static void addAuthorizationHeader(HttpWebRequest request, OAuth2Token token) { request.Headers.Add(string.Format("Authorization: Bearer {0}", token.AccessToken)); }
/// <summary> /// Uploads a File using the Standard upload method with a multipart/form mime encoded POST. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="parentId">where to upload the file</param> /// <param name="localPath">the full path of the file to upload, like "c:\\path\\to\\file.name"</param> public static void UploadFile(OAuth2Token token, string parentId, string localPath) { while (IsFileLocked(new FileInfo(localPath)) == true) { //file is currently locked, so we must wait for it to unlock //console.WriteLine(localPath + "FIle is Currently Blocked"); //passing the existing file descriptor to fwakehandle Entry.Entry.fWakeHandle = localPath; //let the thread rest Entry.Entry.singleEntranceEvent.WaitOne(); } String uri = string.Format("https://{0}/sf/v3/Items({1})/Upload", ShareFileV3Sample.GetHostname(token), parentId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject uploadConfig = JObject.Parse(body); string chunkUri = (string)uploadConfig["ChunkUri"]; if (chunkUri != null) { //console.WriteLine("Starting Upload"); //File UploadMultiPartFile("File1", new FileInfo(localPath), chunkUri); } } }
//upload a folder using standard upload method //breath first search style //go into a folder, then read all files, upload as files come along //put folders in a queue and repeat the same process public static void UploadFolder(OAuth2Token token, String parentId, String localPathRoot) { //Queue for breathfirst traversal //Queue<String> aqueue = new Queue<String>(); //push the first element into the queue //aqueue.Enqueue(localPathRoot); //to be used variables try { DirectoryInfo di; di = new DirectoryInfo(localPathRoot); foreach (var fi in di.GetFiles()) { //console.WriteLine(fi.Name); UploadFile(token, parentId, fi.FullName); } // Display the names of the directories. foreach (DirectoryInfo dri in di.GetDirectories()) { //console.WriteLine(dri.Name); //console.WriteLine(dri.FullName); UploadFolder(token, CreateFolder(token, parentId, dri.Name, "Citrix Uploader"), dri.FullName); } } catch (Exception e) { //give up } }
//returns the filenameid if item name provided is within this folder, otherwise return null //parameter: token, folderid, file name, stringbuilder: answer, optional: getchildren, default is true to compare to against the entire folder's content //stringbuilder answer is used to retrieve the correct fileid //Solution ONLY assumes that there is one distinct file with the given filename, if there are multiple files, then the fileid returned would be random public static String searchExpandFolderById(OAuth2Token token, String folderId, String fileName, StringBuilder answer, bool getChildren = true) { //foeefacf-7f53-48ff-a5fd-29adcd016419 if (token == null || folderId == null || fileName == null) { //console.WriteLine("returned false on head"); return null; } String uri = string.Format("https://{0}/sf/v3/Items({1})", ShareFileV3Sample.GetHostname(token), folderId); if (getChildren) { uri += "?$expand=Children"; } ////console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); //console.WriteLine("current file name: " + fileName); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject root = JObject.Parse(body); // just print Id, CreationDate, Name of each element //console.WriteLine("ROOT ELEMENT" + root["Id"] + " " + root["CreationDate"] + " " + root["Name"]); JArray children = (JArray)root["Children"]; if (children != null) { foreach (JObject child in children) { //if it is a file and filename matches, then check if (isCloudFile(child["Id"].ToString()) == true) { //if the childname is the filename, then true, otherwise continue if (child["Name"].ToString().Equals(fileName)) { //console.WriteLine("Match Found! {0} belongs to {1}!", child["Id"].ToString(), child["Name"].ToString()); //return child["Id"].ToString(); answer.Append(child["Id"].ToString()); //console.WriteLine("Match Found! answer is now {0}!", answer); return answer.ToString() ; } } else if (isCloudFolder(child["Id"].ToString()) == true) { //console.WriteLine("child id is a Folder: "); if (child["Name"].ToString().Equals(fileName) == true) { //if folder name is the filename we are looking for then return its id //console.WriteLine("Match Found! {0} belongs to {1}!", child["Id"].ToString(), child["Name"].ToString()); //return child["Id"].ToString(); answer.Append(child["Id"].ToString()); //console.WriteLine("Match Found! answer is now {0}!", answer); return answer.ToString(); } else { //if the foldername is not the filename we are looking for then call the function recursively on it to return an itemid searchExpandFolderById(token, child["Id"].ToString(), fileName, answer, true); } } else { //not a file and not a directory //not likely, so we do nothing //console.WriteLine("missed casesssssss"); } //if it is a directory, then check if it matches the filename //console.WriteLine(child["Id"] + " " + child["CreationDate"] + " " + child["Name"]); } } } //console.WriteLine("very very last"); return null; }
/// <summary> /// Update the name and description of an Item. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="itemId">the id of the item to update</param> /// <param name="name">the item name</param> /// <param name="description">the item description</param> public static void UpdateItem(OAuth2Token token, string itemId, string name, string description) { String uri = string.Format("https://{0}/sf/v3/Items({1})", ShareFileV3Sample.GetHostname(token), itemId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); Dictionary<string, object> folder = new Dictionary<string, object>(); folder.Add("Name", name); folder.Add("Description", description); string json = JsonConvert.SerializeObject(folder); //console.WriteLine(json); request.Method = "PATCH"; request.ContentType = "application/json"; using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(json); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject newFolder = JObject.Parse(body); //console.WriteLine("Updated Folder: " + newFolder["Id"]); } }
//return parentid given child id, if itemid is null, then return null, if token is null then return null //if item is not found, then return null, otherwise it will return an itemid public static String getParentofChild(OAuth2Token token, String itemId) { if (token == null) return null; if (String.IsNullOrWhiteSpace(itemId) || String.IsNullOrEmpty(itemId)) { return null; } String uri = string.Format("https://{0}/sf/v3/Items({1})/Parent", ShareFileV3Sample.GetHostname(token), itemId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject item = JObject.Parse(body); return item["Id"].ToString(); ////console.WriteLine(item["Id"] + " " + item["CreationDate"] + " " + item["Name"]); } } catch (Exception web) { //item is not found return null; } // return null; }
/// <summary> /// Get the root level Item for the provided user. To retrieve Children the $expand=Children /// parameter can be added. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="getChildren">retrieve Children Items if true, default is false</param> public static void GetRoot(OAuth2Token token, bool getChildren = false) { String uri = string.Format("https://{0}/sf/v3/Items", ShareFileV3Sample.GetHostname(token)); if (getChildren) { uri += "?$expand=Children"; } //console.WriteLine(uri); //console.WriteLine("Beginning death and destruction!"); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject root = JObject.Parse(body); // just print Id, CreationDate, Name of each element //console.WriteLine(root["Id"] + " " + root["CreationDate"] + " " + root["Name"]); JArray children = (JArray)root["Children"]; if (children != null) { foreach (JObject child in children) { //console.WriteLine(child["Id"] + " " + child["CreationDate"] + " " + child["Name"]); } } } }
public static string GetHostname(OAuth2Token token) { // //console.WriteLine("SubDomain is: " + token.Subdomain); return string.Format("{0}.sf-api.com", token.Subdomain); }
/// <summary> /// Get a single Item by Id. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="id">an item id</param> public static void GetItemById(OAuth2Token token, string id) { String uri = string.Format("https://{0}/sf/v3/Items({1})", ShareFileV3Sample.GetHostname(token), id); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject item = JObject.Parse(body); //console.WriteLine(item["Id"] + " " + item["CreationDate"] + " " + item["Name"]); } }
/// <summary> /// Get a folder using some of the common query parameters that are available. This will /// add the expand, select parameters. The following are used: /// expand=Children to get any Children of the folder /// select=Id,Name,Children/Id,Children/Name,Children/CreationDate to get the Id, Name of the folder and the Id, Name, CreationDate of any Children /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="id">a folder id</param> public static void GetFolderWithQueryParameters(OAuth2Token token, string id) { String uri = string.Format("https://{0}/sf/v3/Items({1})?$expand=Children&$select=Id,Name,Children/Id,Children/Name,Children/CreationDate", ShareFileV3Sample.GetHostname(token), id); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject folder = JObject.Parse(body); // only Id and Name are available because we specifically selected only those two Properties ////console.WriteLine(folder["Id"] + " " + folder["Name"]); JArray children = (JArray)folder["Children"]; if (children != null) { foreach (JObject child in children) { // CreationDate is also available on Children because we specifically selected that property in addition to Id, Name //console.WriteLine(child["Id"] + " " + child["CreationDate"] + " " + child["Name"]); } } } }
/// <summary> /// Downloads a single Item. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="itemId">the id of the item to download</param> /// <param name="localPath">where to download the item to, like "c:\\path\\to\\the.file". If downloading a folder the localPath name should end in .zip.</param> public static void DownloadItem(OAuth2Token token, string itemId, string localPath) { String uri = string.Format("https://{0}/sf/v3/Items({1})/Download", ShareFileV3Sample.GetHostname(token), itemId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); request.AllowAutoRedirect = true; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (var source = new BufferedStream(response.GetResponseStream())) { using (var target = new FileStream(localPath, FileMode.Create)) { int chunkSize = 1024 * 8; byte[] chunk = new byte[chunkSize]; int len = 0; while ((len = source.Read(chunk, 0, chunkSize)) > 0) { target.Write(chunk, 0, len); } //console.WriteLine("Download complete"); } } //console.WriteLine(response.StatusCode); }
/// <summary> /// Delete an Item by Id. /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="itemId">the id of the item to delete</param> public static void DeleteItem(OAuth2Token token, string itemId) { String uri = string.Format("https://{0}/sf/v3/Items({1})", ShareFileV3Sample.GetHostname(token), itemId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); request.Method = "DELETE"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); }
/// <summary> /// Create a new folder in the given parent folder. Returns the FileId of created Folder /// </summary> /// <param name="token">the OAuth2Token returned from Authenticate</param> /// <param name="parentId">the parent folder in which to create the new folder</param> /// <param name="name">the folder name</param> /// <param name="description">the folder description</param> public static String CreateFolder(OAuth2Token token, string parentId, string name, string description) { String uri = string.Format("https://{0}/sf/v3/Items({1})/Folder", ShareFileV3Sample.GetHostname(token), parentId); //console.WriteLine(uri); HttpWebRequest request = WebRequest.CreateHttp(uri); ShareFileV3Sample.addAuthorizationHeader(request, token); Dictionary<string, object> folder = new Dictionary<string, object>(); folder.Add("Name", name); folder.Add("Description", description); string json = JsonConvert.SerializeObject(folder); //console.WriteLine(json); request.Method = "POST"; request.ContentType = "application/json"; using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(json); } try { //try to assert create folder action and get a response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //console.WriteLine(response.StatusCode); using (var reader = new StreamReader(response.GetResponseStream())) { String body = reader.ReadToEnd(); JObject newFolder = JObject.Parse(body); return newFolder["Id"].ToString(); } } catch (Exception e) { //folder already exist, hence return null return null; } }
//HTML API static bool authen() { //authentication first string hostname = "isoa2015.sharefile.com"; string username = "******"; string password = "******"; string clientId = "fZYqiGVX1ZwFZvSWn2UqjZNtOT1uSyWT"; string clientSecret = "7sKJVwIpcIGYHWBLeXnSNcRIXE2al2AgVGihKEgdq0W4CZpJ"; OAuth2Token token = ShareFileV3Sample.ShareFileV3Sample.Authenticate(hostname, clientId, clientSecret, username, password); if (token != null) { //initialize OAuth2Token connectionToken = token; //testground // //console.WriteLine("performing initial actions"); // StringBuilder newString = new StringBuilder(); // //console.WriteLine("Evil Things Are Occurring File" + ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "3455.pub", newString, true)); // //console.WriteLine("StringBuilder String is here: " + newString); // newString.Clear(); // //console.WriteLine("Evil Things Are Occurring Folder" + ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "absolutely.docx", newString, true)); // //console.WriteLine("StringBuilder String is here: " + newString); //clear string builder so it can be used again //newString.Clear(); // //console.WriteLine("Evil Things Are Occurring Folder" + ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "randomnothing", newString, true)); ////console.WriteLine("StringBuilder String is here: " + newString); //get parent of child test // //console.WriteLine("Parent of child moo is: " + ShareFileV3Sample.ShareFileV3Sample.getParentofChild(token, ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "moo", true))); // //console.WriteLine("Parent of child nothing is: " + ShareFileV3Sample.ShareFileV3Sample.getParentofChild(token, ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "nothing", true))); // //console.WriteLine("Parent of child a file is: " + ShareFileV3Sample.ShareFileV3Sample.getParentofChild(token, ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "aaw.jnt", true))); //update file test // ShareFileV3Sample.ShareFileV3Sample.UpdateItem(token, ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "newitem.docx", true), "newerItem.docx", "sickitem"); //update folder test // ShareFileV3Sample.ShareFileV3Sample.UpdateItem(token, ShareFileV3Sample.ShareFileV3Sample.searchExpandFolderById(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "testintest", true), "chickenFolder", "sickitem"); //upload file test //File.SetAttributes("C:\\Users\\Randy\\Desktop\\monitored\\Printer Driver.giberish", FileAttributes.Normal); // ShareFileV3Sample.ShareFileV3Sample.UploadFile(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "C:\\Users\\Randy\\Desktop\\monitored\\Printer Driver.giberish"); //create folder test ////console.WriteLine( ShareFileV3Sample.ShareFileV3Sample.CreateFolder(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "strange", "strangeFolder")); //upload folder test //ShareFileV3Sample.ShareFileV3Sample.UploadFolder(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "C:\\Users\\Randy\\Desktop\\monitored"); //test folder upload wrapper // ShareFileV3Sample.ShareFileV3Sample.UploadFolderWraper(token, "foeefacf-7f53-48ff-a5fd-29adcd016419", "C:\\Users\\Randy\\Desktop\\monitored"); //test iscloudfile //ShareFileV3Sample.ShareFileV3Sample.isCloudFile("fi3jo2iajwoeiaj"); //is //ShareFileV3Sample.ShareFileV3Sample.isCloudFile("fowaoweuaheiauhwiea"); //is not //ShareFileV3Sample.ShareFileV3Sample.isCloudFile("wewafieuaheiauhwiea"); //is not ////console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFile("fi3jo2iajwoeiaj")); ////console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFile("fowaoweuaheiauhwiea")); ////console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFile("wewafieuaheiauhwiea")); //test iscloudfolder //ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("fi3jo2iajwoeiaj"); //is not //ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("fowaoweuaheiauhwiea"); //is //ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("wewafoeuaheiauhwiea"); //is not ////console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("fi3jo2iajwoeiaj")); ////console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("fowaoweuaheiauhwiea")); // //console.WriteLine(ShareFileV3Sample.ShareFileV3Sample.isCloudFolder("wewafoeuaheiauhwiea")); //String samplePath = "C:\\Users\\Randy\\Desktop\\monitored\\Printer Driver.giberish"; //ShareFileV3Sample.ShareFileV3Sample.getLocalParentFolder(samplePath); //filter out files that ends in .tmp //unit tests starts here //tmp //testcase(checkTmp("creates.tmp"), 1, true); //testcase(checkTmp("crea.tmper"), 2, false); //testcase(checkTmp(null), 3, false); //testcase(checkTmp("jw"), 7, false); //wave //bool wavetestflag = true; //if (wavetestflag == true) //{ // testcase(checkWave(null), 4, false); // testcase(checkWave("~muchapprici"), 5, true); // testcase(checkWave("muchappri~"), 6, false); // testcase(checkWave("~"), 8, true); // testcase(checkWave("g"), 9, true); //} //testcaseString(ShareFileV3Sample.ShareFileV3Sample.getParentofChild(connectionToken, "fi983uu9ashwaoeupraw"), 10, null); //testcaseString(ShareFileV3Sample.ShareFileV3Sample.getParentofChild(connectionToken, "fo316ec0-057f-4931-9a28-23afa1695a28"), 11, "fo02dd31-c6ea-4135-a6c5-30d811ace862"); //testcaseString(ShareFileV3Sample.ShareFileV3Sample.getParentofChild(connectionToken, null), 12, null); //testcase( checkFolderCode("fo293u2932ih9as"),13, true); //testcase(checkFolderCode(""), 14, false); //testcase(checkFolderCode(null), 15, false); //testcase(checkFolderCode("fi293uaohshdaweh"), 16, false); return true; } else { //console.WriteLine("Authentication Failure, Abort"); //might as well terminate, nothing can be done without the token return false; } }