PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/UploadToShareFile/ShareFileSample.cs

https://github.com/RickyLin/DotNetUtilities
C# | 459 lines | 302 code | 66 blank | 91 comment | 17 complexity | 3555cd46f15427c6769e52edb89c66b6 MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Net;
  8. using System.Web;
  9. using System.IO;
  10. using Newtonsoft.Json.Linq;
  11. using Newtonsoft.Json;
  12. /// Copyright (c) 2013 Citrix Systems, Inc.
  13. ///
  14. /// Permission is hereby granted, free of charge, to any person obtaining a
  15. /// copy of this software and associated documentation files (the "Software"),
  16. /// to deal in the Software without restriction, including without limitation
  17. /// the rights to use, copy, modify, merge, publish, distribute, sublicense,
  18. /// and/or sell copies of the Software, and to permit persons to whom the
  19. /// Software is furnished to do so, subject to the following conditions:
  20. ///
  21. /// The above copyright notice and this permission notice shall be included in
  22. /// all copies or substantial portions of the Software.
  23. ///
  24. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27. /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  29. /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  30. /// IN THE SOFTWARE.
  31. namespace ShareFileSampleCode
  32. {
  33. /// <summary>
  34. /// Methods in this class make use of ShareFile API. Please see api.sharefile.com for more information.
  35. /// Requirements:
  36. ///
  37. /// Json.NET library. see http://json.codeplex.com/
  38. ///
  39. /// Optional parameters can be passed to functions as a Dictionary as follows:
  40. ///
  41. /// ex:
  42. ///
  43. /// Dictionary<string, object> optionalParameters = new Dictionary<string, object>();
  44. /// optionalParameters.Add("company", "ACompany");
  45. /// optionalParameters.Add("password", "Apassword");
  46. /// optionalParameters.Add("addshared", true);
  47. /// sample.usersCreate("firstname", "lastname", "an@email.com", false, optionalParameters);
  48. ///
  49. /// See api.sharefile.com for optional parameter names for each operation.
  50. /// </summary>
  51. class ShareFileSample
  52. {
  53. string subdomain;
  54. string tld;
  55. string authId;
  56. /// <summary>
  57. /// Calls getAuthID to retrieve an authid that will be used for subsequent calls to API.
  58. ///
  59. /// If you normally login to ShareFile at an address like https://mycompany.sharefile.com,
  60. /// then your subdomain is mycompany and your tld is sharefile.com
  61. /// </summary>
  62. /// <param name="subdomain">your subdomain</param>
  63. /// <param name="tld">your top level domain</param>
  64. /// <param name="username">your username</param>
  65. /// <param name="password">your password</param>
  66. /// <returns>true if login was successful, false otherwise.</returns>
  67. public bool Authenticate(string subdomain, string tld, string username, string password)
  68. {
  69. this.subdomain = subdomain;
  70. this.tld = tld;
  71. string requestUrl = string.Format("https://{0}.{1}/rest/getAuthID.aspx?fmt=json&username={2}&password={3}",
  72. subdomain, tld, HttpUtility.UrlEncode(username), HttpUtility.UrlEncode(password));
  73. Console.WriteLine(requestUrl);
  74. JObject jsonObj = InvokeShareFileOperation(requestUrl);
  75. if (!(bool)jsonObj["error"])
  76. {
  77. string authId = (string)jsonObj["value"];
  78. this.authId = authId;
  79. return (true);
  80. }
  81. else
  82. {
  83. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  84. return (false);
  85. }
  86. }
  87. /// <summary>
  88. /// Prints out a folder list for the specified path or root if none is provided. Currently prints out id, filename, creationdate, type.
  89. /// </summary>
  90. /// <param name="path">folder to list</param>
  91. public void FolderList(string path)
  92. {
  93. if (string.IsNullOrEmpty(path))
  94. {
  95. path = "/";
  96. }
  97. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  98. requiredParameters.Add("path", path);
  99. String url = BuildUrl("folder", "list", requiredParameters);
  100. JObject jsonObj = InvokeShareFileOperation(url);
  101. if (!(bool)jsonObj["error"])
  102. {
  103. JArray items = (JArray)jsonObj["value"];
  104. foreach (JObject item in items)
  105. {
  106. Console.WriteLine(item["id"] + " " + item["filename"] + " " + item["creationdate"] + " " + item["type"]);
  107. }
  108. }
  109. else
  110. {
  111. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  112. }
  113. }
  114. /// <summary>
  115. /// Uploads a file to ShareFile.
  116. /// </summary>
  117. /// <param name="localPath">full path to local file, i.e. c:\\path\\to\\local.file</param>
  118. /// <param name="optionalParameters">name/value optional parameters</param>
  119. public void FileUpload(string localPath, Dictionary<string, object> optionalParameters)
  120. {
  121. FileInfo file = new FileInfo(localPath);
  122. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  123. requiredParameters.Add("filename", file.Name);
  124. string url = BuildUrl("file", "upload", requiredParameters, optionalParameters);
  125. JObject jsonObj = InvokeShareFileOperation(url);
  126. if (!(bool)jsonObj["error"])
  127. {
  128. string uploadUrl = (string)jsonObj["value"];
  129. Console.WriteLine(uploadUrl);
  130. string rv = UploadMultiPartFile(file, uploadUrl);
  131. Console.WriteLine(rv);
  132. }
  133. else
  134. {
  135. throw new ApplicationException(string.Format("Failed to request upload: {0}, {1}", jsonObj["errorCode"], jsonObj["errorMessage"]));
  136. }
  137. }
  138. /// <summary>
  139. /// Downloads a file from ShareFile.
  140. /// </summary>
  141. /// <param name="fileId">id of the file to download</param>
  142. /// <param name="localPath">complete path to download file to, i.e. c:\\path\\to\\local.file</param>
  143. public void FileDownload(string fileId, string localPath)
  144. {
  145. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  146. requiredParameters.Add("id", fileId);
  147. String url = BuildUrl("file", "download", requiredParameters);
  148. JObject jsonObj = InvokeShareFileOperation(url);
  149. if (!(bool)jsonObj["error"])
  150. {
  151. string downloadUrl = (string)jsonObj["value"];
  152. Console.WriteLine("downloadUrl = " + downloadUrl);
  153. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadUrl);
  154. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  155. BufferedStream source = new BufferedStream(response.GetResponseStream());
  156. FileStream target = new FileStream(localPath, FileMode.Create);
  157. byte[] chunk = new byte[8192];
  158. int len = 0;
  159. while ((len = source.Read(chunk, 0, 8192)) > 0)
  160. {
  161. target.Write(chunk, 0, len);
  162. }
  163. Console.WriteLine("Download complete");
  164. response.Close();
  165. }
  166. else
  167. {
  168. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  169. }
  170. }
  171. /// <summary>
  172. /// Sends a Send a File email.
  173. /// </summary>
  174. /// <param name="path">path to file in ShareFile to send</param>
  175. /// <param name="to">email address to send to</param>
  176. /// <param name="subject">subject of the email</param>
  177. /// <param name="optionalParameters">name/value optional parameters</param>
  178. public void FileSend(string path, string to, string subject, Dictionary<string, object> optionalParameters)
  179. {
  180. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  181. requiredParameters.Add("path", path);
  182. requiredParameters.Add("to", to);
  183. requiredParameters.Add("subject", subject);
  184. String url = BuildUrl("file", "send", requiredParameters, optionalParameters);
  185. JObject jsonObj = InvokeShareFileOperation(url);
  186. if (!(bool)jsonObj["error"])
  187. {
  188. string value = (string)jsonObj["value"];
  189. Console.WriteLine(value);
  190. }
  191. else
  192. {
  193. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  194. }
  195. }
  196. /// <summary>
  197. /// Creates a client or employee user in ShareFile.
  198. /// </summary>
  199. /// <param name="firstName">first name</param>
  200. /// <param name="lastName">last name</param>
  201. /// <param name="email">email address</param>
  202. /// <param name="isEmployee">true to create an employee, false to create a client</param>
  203. /// <param name="optionalParameters">name/value optional parameters</param>
  204. public void usersCreate(string firstName, string lastName, string email, bool isEmployee, Dictionary<string, object> optionalParameters)
  205. {
  206. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  207. requiredParameters.Add("firstname", firstName);
  208. requiredParameters.Add("lastname", lastName);
  209. requiredParameters.Add("email", email);
  210. requiredParameters.Add("isemployee", isEmployee);
  211. String url = BuildUrl("users", "create", requiredParameters, optionalParameters);
  212. JObject jsonObj = InvokeShareFileOperation(url);
  213. if (!(bool)jsonObj["error"])
  214. {
  215. JObject user = (JObject)jsonObj["value"];
  216. Console.WriteLine(user["id"] + " " + user["primaryemail"]);
  217. }
  218. else
  219. {
  220. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  221. }
  222. }
  223. /// <summary>
  224. /// Creates a distribution group in ShareFile.
  225. /// </summary>
  226. /// <param name="name">name of group</param>
  227. /// <param name="optionalParameters">name/value optional parameters</param>
  228. public void GroupCreate(string name, Dictionary<string, object> optionalParameters)
  229. {
  230. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  231. requiredParameters.Add("name", name);
  232. String url = BuildUrl("group", "create", requiredParameters, optionalParameters);
  233. JObject jsonObj = InvokeShareFileOperation(url);
  234. if (!(bool)jsonObj["error"])
  235. {
  236. JObject group = (JObject)jsonObj["value"];
  237. Console.WriteLine(group["id"] + " " + group["name"]);
  238. }
  239. else
  240. {
  241. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  242. }
  243. }
  244. /// <summary>
  245. /// Searches for items in ShareFile.
  246. /// </summary>
  247. /// <param name="query">search term</param>
  248. /// <param name="optionalParameters">name/value optional parameters</param>
  249. public void Search(string query, Dictionary<string, object> optionalParameters)
  250. {
  251. Dictionary<string, object> requiredParameters = new Dictionary<string, object>();
  252. requiredParameters.Add("query", query);
  253. String url = BuildUrl("search", "search", requiredParameters, optionalParameters);
  254. JObject jsonObj = InvokeShareFileOperation(url);
  255. if (!(bool)jsonObj["error"])
  256. {
  257. JArray items = (JArray)jsonObj["value"];
  258. if (items.Count == 0)
  259. {
  260. Console.WriteLine("No Results");
  261. return;
  262. }
  263. string path = "";
  264. foreach (JObject item in items)
  265. {
  266. path = "/";
  267. if (((string)item["parentid"]).Equals("box"))
  268. {
  269. path = "/File Box";
  270. }
  271. else
  272. {
  273. path = (string)item["parentsemanticpath"];
  274. }
  275. Console.WriteLine(path + "/" + item["filename"] + " " + item["creationdate"] + " " + item["type"]);
  276. }
  277. }
  278. else
  279. {
  280. Console.WriteLine(jsonObj["errorCode"] + " : " + jsonObj["errorMessage"]);
  281. }
  282. }
  283. // ------------------------------------------- Utility Functions -------------------------------------------
  284. private string BuildUrl(string endpoint, string op, Dictionary<string, object> requiredParameters)
  285. {
  286. return (BuildUrl(endpoint, op, requiredParameters, new Dictionary<string, object>()));
  287. }
  288. private string BuildUrl(string endpoint, string op, Dictionary<string, object> requiredParameters, Dictionary<string, object> optionalParameters)
  289. {
  290. requiredParameters.Add("authid", this.authId);
  291. requiredParameters.Add("op", op);
  292. requiredParameters.Add("fmt", "json");
  293. ArrayList parameters = new ArrayList();
  294. foreach (KeyValuePair<string, object> kv in requiredParameters)
  295. {
  296. parameters.Add(string.Format("{0}={1}", HttpUtility.UrlEncode(kv.Key), HttpUtility.UrlEncode(kv.Value.ToString())));
  297. }
  298. foreach (KeyValuePair<string, object> kv in optionalParameters)
  299. {
  300. parameters.Add(string.Format("{0}={1}", HttpUtility.UrlEncode(kv.Key), HttpUtility.UrlEncode(kv.Value.ToString())));
  301. }
  302. String url = string.Format("https://{0}.{1}/rest/{2}.aspx?{3}", this.subdomain, this.tld, endpoint, String.Join("&", parameters.ToArray()));
  303. Console.WriteLine(url);
  304. return (url);
  305. }
  306. private JObject InvokeShareFileOperation(string requestUrl)
  307. {
  308. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
  309. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  310. StreamReader reader = new StreamReader(response.GetResponseStream());
  311. String json = reader.ReadToEnd();
  312. response.Close();
  313. return JObject.Parse(json);
  314. }
  315. private string UploadMultiPartFile(FileInfo fileInfo, string fileUploadUrl)
  316. {
  317. string contentType;
  318. byte[] uploadData = CreateMultipartFormUpload(fileInfo, fileInfo.Name, out contentType);
  319. string rv = Send(fileUploadUrl, contentType, uploadData);
  320. return (rv);
  321. }
  322. private Byte[] CreateMultipartFormUpload(FileInfo fileInfo, string remoteFilename, out string contentType)
  323. {
  324. string boundaryGuid = "upload-" + Guid.NewGuid().ToString("n");
  325. contentType = "multipart/form-data; boundary=" + boundaryGuid;
  326. MemoryStream ms = new MemoryStream();
  327. byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundaryGuid + "\r\n");
  328. // Write MIME header
  329. ms.Write(boundaryBytes, 2, boundaryBytes.Length - 2);
  330. string header = String.Format(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""" +
  331. "\r\nContent-Type: application/octet-stream\r\n\r\n", "File1", remoteFilename);
  332. byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
  333. ms.Write(headerBytes, 0, headerBytes.Length);
  334. // Load the file into the byte array
  335. using (FileStream file = fileInfo.OpenRead())
  336. {
  337. byte[] buffer = new byte[1024 * 1024];
  338. int bytesRead;
  339. while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
  340. {
  341. ms.Write(buffer, 0, bytesRead);
  342. }
  343. }
  344. // Write MIME footer
  345. boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundaryGuid + "--\r\n");
  346. ms.Write(boundaryBytes, 0, boundaryBytes.Length);
  347. byte[] retVal = ms.ToArray();
  348. ms.Close();
  349. return retVal;
  350. }
  351. private string Send(string url, string contenttype, byte[] postBytes)
  352. {
  353. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  354. request.Timeout = 1000 * 60 * 30; // 60 seconds * 30 = 30 minutes
  355. request.Method = "POST";
  356. request.ContentType = contenttype;
  357. request.ContentLength = postBytes.Length;
  358. request.Credentials = CredentialCache.DefaultCredentials;
  359. using (Stream postStream = request.GetRequestStream())
  360. {
  361. int chunkSize = 512 * 1024;
  362. int remaining = postBytes.Length;
  363. int offset = 0;
  364. do
  365. {
  366. if (chunkSize > remaining) { chunkSize = remaining; }
  367. postStream.Write(postBytes, offset, chunkSize);
  368. remaining -= chunkSize;
  369. offset += chunkSize;
  370. } while (remaining > 0);
  371. postStream.Close();
  372. }
  373. String retVal;
  374. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  375. {
  376. StreamReader rdr = new StreamReader(response.GetResponseStream());
  377. retVal = rdr.ReadToEnd();
  378. response.Close();
  379. }
  380. return retVal;
  381. }
  382. public static void SampleMain(string[] args)
  383. {
  384. ShareFileSample sample = new ShareFileSample();
  385. Dictionary<string, object> optionalParameters = new Dictionary<string, object>();
  386. bool loginStatus = sample.Authenticate("mysubdomain", "sharefile.com", "my@email.address", "mypassword");
  387. if (loginStatus)
  388. {
  389. sample.FolderList("/MyFolder");
  390. }
  391. }
  392. }
  393. }