public async Task <dynamic> CreateBucket([FromBody] BucketModel bucket) { dynamic NewBucket = null; BucketsApi buckets = new BucketsApi(); dynamic token = await OAuthController.GetInternalAsync(); buckets.Configuration.AccessToken = token.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(string.Format("{0}-{1}", ClientId, bucket.bucketKey.ToLower()), null, PostBucketsPayload.PolicyKeyEnum.Transient); try { NewBucket = await buckets.CreateBucketAsync(bucketPayload, bucketRegion); } catch (Exception e) { if (e.Message == "Error calling CreateBucket: {\"reason\":\"Bucket already exists\"}") { dynamic allBuckets = await buckets.GetBucketsAsync("US", 100); foreach (KeyValuePair <string, dynamic> actualBucket in new DynamicDictionaryItems(allBuckets.items)) { string bucketName = actualBucket.Value.bucketKey; if (bucketName.Contains(BucketName)) //kitchenconfig designautomation { NewBucket = actualBucket; } } } } return(NewBucket); }
public async Task <bool> CreateBucket(string bucketKey) { if (bucketKey == null) { throw new ArgumentNullException("bucketKey"); } var isAuthorized = await IsAuthorized(); if (!isAuthorized) { _logger.Log(LogType.Error, "Cannot be authorized for creating bucket"); return(false); } var bucketsApi = new BucketsApi { Configuration = { AccessToken = AuthenticationToken.AccessToken } }; var postBuckets = new PostBucketsPayload(bucketKey.ToLower(), null, PostBucketsPayload.PolicyKeyEnum.Transient); try { await bucketsApi.CreateBucketAsync(postBuckets); } catch (Exception e) { _logger.Log(LogType.Error, "Exception when creating the Bucket: " + e); return(false); } return(true); }
/// <summary> /// The RunAsync. /// </summary> /// <returns>The <see cref="Task"/>.</returns> public async Task RunAsync() { if (string.IsNullOrEmpty(Owner)) { Console.WriteLine("Please provide non-empty Owner."); return; } if (string.IsNullOrEmpty(UploadUrl)) { Console.WriteLine($"Creating Bucket...."); dynamic oauth = await GetInternalAsync(); // 1. ensure bucket existis string bucketKey = Owner.ToLower(); Console.WriteLine($"Creating Bucket {bucketKey}...."); BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); dynamic bucketsRes = await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { // in case bucket already exists Console.WriteLine($"\tBucket {bucketKey} exists"); }; ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; //2. Upload input file and get signed URL string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(FilePaths.InputFile)); Console.WriteLine($"Uploading input file {inputFileNameOSS} to {bucketKey}..... "); using (StreamReader streamReader = new StreamReader(FilePaths.InputFile)) { dynamic res = await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } try { PostBucketsSigned bucketsSigned = new PostBucketsSigned(60); dynamic signedResp = await objects.CreateSignedResourceAsync(bucketKey, inputFileNameOSS, bucketsSigned, "read"); downloadUrl = signedResp.signedUrl; Console.WriteLine($"\tSuccess: File uploaded to... \n\t{downloadUrl}"); } catch { } } if (!await SetupOwnerAsync()) { Console.WriteLine("Exiting."); return; } await SubmitWorkItemAsync(ActivityName); }
/** * Example of how to create a new bucket using Forge SDK. * Uses the oauth2TwoLegged and twoLeggedCredentials objects that you retrieved previously. */ private static void createBucket() { Console.WriteLine("***** Sending createBucket request"); PostBucketsPayload payload = new PostBucketsPayload(BUCKET_KEY, null, PostBucketsPayload.PolicyKeyEnum.Persistent); dynamic response = bucketsApi.CreateBucket(payload, "US"); Console.WriteLine("***** Response for createBucket: " + response.ToString()); }
/// <summary> /// Create bucket with given name /// </summary> /// <param name="bucketKey">The bucket name.</param> public async Task CreateBucketAsync(string bucketKey) { await WithBucketApiAsync(async api => { var payload = new PostBucketsPayload(bucketKey, /*allow*/ null, PostBucketsPayload.PolicyKeyEnum.Persistent); await api.CreateBucketAsync(payload, /* use default (US region) */ null); }); }
public async Task<dynamic> CreateBucket([FromBody] CreateBucketModel bucket) { BucketsApi buckets = new BucketsApi(); dynamic token = await OAuthController.GetInternalAsync(); buckets.Configuration.AccessToken = token.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(string.Format("{0}-{1}", ClientId, bucket.bucketKey.ToLower()), null, PostBucketsPayload.PolicyKeyEnum.Transient); return await buckets.CreateBucketAsync(bucketPayload, "US"); }
public async Task <dynamic> CreateBucketAsync([FromBody] BucketModel bucket) { BucketsApi buckets = new BucketsApi(); dynamic token = await OAuthController.GetInternalAsync(); buckets.Configuration.AccessToken = token.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucket.bucketKey, null, bucket.policyKey); return(await buckets.CreateBucketAsync(bucketPayload, "US")); }
/// <summary> /// Create a bucket. /// </summary> private async static Task <dynamic> CreateBucket() { string bucketKey = "forgeapp" + Guid.NewGuid().ToString("N").ToLower(); PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient /* erase after 24h*/); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = InternalToken.access_token; //bearer is returned from 2 legged token dynamic newBucket = await bucketsApi.CreateBucketAsync(postBucket); return(newBucket); }
/// <summary> /// Creates Bucket /// </summary> /// <returns>Newly created bucket</returns> private async static Task <dynamic> CreateBucket() { string bucketKey = "inventorio" + Guid.NewGuid().ToString("N").ToLower(); PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = InternalToken.access_token; dynamic newBucket = await bucketsApi.CreateBucketAsync(postBucket); return(newBucket); }
public async Task RunAsync() { if (string.IsNullOrEmpty(Owner)) { Console.WriteLine("Please provide non-empty Owner."); return; } if (string.IsNullOrEmpty(UploadUrl)) { Console.WriteLine("Creating Bucket and OSS Object"); dynamic oauth = await GetInternalAsync(); // 1. ensure bucket existis string bucketKey = Owner.ToLower(); BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; dynamic bucketsRes = null; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); bucketsRes = await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { Console.WriteLine($"\tBucket {bucketKey} exists"); }; // in case bucket already exists string outputFileNameOSS = "output.zip"; ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; try { PostBucketsSigned bucketsSigned = new PostBucketsSigned(60); dynamic signedResp = await objects.CreateSignedResourceAsync(bucketKey, outputFileNameOSS, bucketsSigned, "readwrite"); UploadUrl = signedResp.signedUrl; } catch {} } if (!await SetupOwnerAsync()) { Console.WriteLine("Exiting."); return; } var myApp = await SetupAppBundleAsync(); var myActivity = await SetupActivityAsync(myApp); await SubmitWorkItemAsync(myActivity); }
private static dynamic CreateBucket() { try { Console.WriteLine("**** Creating bucket: " + BucketKey); PostBucketsPayload.PolicyKeyEnum bucketType = PostBucketsPayload.PolicyKeyEnum.Persistent; PostBucketsPayload payload = new PostBucketsPayload(BucketKey, null, bucketType); dynamic response = BucketAPI.CreateBucketAsyncWithHttpInfo(payload, region.ToString()); return(response); } catch (Exception) { Console.WriteLine("**** Failed creating bucket: " + BucketKey); return(null); } }
public async Task <dynamic> CreateBucket([FromBody] CreateBucketModel bucket) { BucketsApi buckets = new BucketsApi(); // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // //dynamic token = await OAuthController.GetInternalAsync(); buckets.Configuration.AccessToken = credentials.TokenInternal; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucket.bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); return(await buckets.CreateBucketAsync(bucketPayload, "US")); }
private async void btnCreateBucket_Click(object sender, EventArgs e) { string bucketKey = string.Empty; if (Prompt.ShowDialog("Enter bucket name: ", "Create new bucket", txtClientId.Text.ToLower() + DateTime.Now.Ticks.ToString(), out bucketKey) == DialogResult.OK) { BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = AccessToken; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey.ToLower(), null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, cmbRegion.Text); btnRefreshToken_Click(null, null); } }
private async Task <dynamic> CreateBucketsApi(BucketsApi bucketsApi, string bucketKey) { try { PostBucketsPayload postBucketsPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); var result = await bucketsApi.CreateBucketAsync(postBucketsPayload, "US"); return(result); } catch (Exception e) { throw e; } }
public async Task <dynamic> CreateBucket([FromBody] CreateBucketModel bucket) { if (!Utility.Buckets.IsValidBucketKey(bucket.bucketKey)) { return(null); } BucketsApi buckets = new BucketsApi(); dynamic token = await Utility.OAuth.Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate }); buckets.Configuration.AccessToken = token.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucket.bucketKey, null, bucket.policyKey); return(await buckets.CreateBucketAsync(bucketPayload, Enum.GetName(typeof(Region), bucket.region))); }
public async Task <dynamic> CreateTask(BucketKey key) { IBucketsApi buckets = GeneralTokenConfigurationSettings <IBucketsApi> .SetToken(new BucketsApi(), await _authServiceAdapter.GetSecondaryTokenTask()); var clientId = AppSettings.GetAppSetting("FORGE_CLIENT_ID").ToLower(); var bucketKey = key.bucketKey.ToLower(); PostBucketsPayload bucketPayload = new PostBucketsPayload(string.Format("{0}{1}", bucketKey, clientId.Substring(0, 18)), null, PostBucketsPayload.PolicyKeyEnum.Transient); var result = await buckets.CreateBucketAsync(bucketPayload, "US"); return(result); }
/// <summary> /// Creates Bucket /// </summary> /// <returns>Newly created bucket</returns> public async static Task <dynamic> CreateBucket() { string bucketKey = "inventorilogicda" + ConsumerKey.ToLower(); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = InternalToken.access_token; dynamic buckets = await bucketsApi.GetBucketsAsync(); bool bucketExists = buckets.items.ToString().Contains(bucketKey); if (!bucketExists) { PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); dynamic newbucket = await bucketsApi.CreateBucketAsync(postBucket); } return(bucketKey); }
public async Task <IActionResult> Upload([FromForm] StartWorkitemInput input) { JObject workItemData = JObject.Parse(input.data); browserConnectionId = workItemData["browserConnectionId"].Value <string>(); var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) { await input.inputFile.CopyToAsync(stream); } dynamic oauth = await GetInternalASync(); // upload file to OSS Bucket // 1. ensure bucket exists BucketKey = String.Format("{0}_{1}", BucketKey, DateTime.Now.ToString("yyyyMMddhhmmss").ToLower()); BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(BucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding object res = default; using (StreamReader streamReader = new StreamReader(fileSavePath)) { res = await objects.UploadObjectAsync(BucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } var json = JsonConvert.SerializeObject(res, Formatting.Indented); var response = Response; await response.WriteJsonAsync(json); // delete server copy System.IO.File.Delete(fileSavePath); return(new EmptyResult()); }
public async Task <IActionResult> UploadOssFiles([FromBody] JObject appBundleSpecs) { if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true") { return(Unauthorized()); } System.Diagnostics.Debug.WriteLine("UploadOssFiles"); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; DerivativesApi derivatives = new DerivativesApi(); derivatives.Configuration.AccessToken = oauth.access_token; // upload file to OSS Bucket // 1. ensure bucket existis BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(BucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists string [] filePaths = System.IO.Directory.GetFiles(LocalFilesFolder); foreach (string filePath in filePaths) { string fileName = System.IO.Path.GetFileName(filePath); using (StreamReader streamReader = new StreamReader(filePath)) { dynamic res = await objects.UploadObjectAsync(BucketKey, fileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); TranslateFile(res.objectId, null); } } return(Ok()); }
private async void CreateBucket_Click(object sender, RoutedEventArgs e) { Handled(e); CreateBucket wnd = new CreateBucket(); wnd.Owner = this; Nullable <bool> dialogResult = wnd.ShowDialog(); if (dialogResult.Value == false) { return; } try { BucketsApi ossBuckets = new BucketsApi(); ossBuckets.Configuration.AccessToken = accessToken; PostBucketsPayload.PolicyKeyEnum bucketType = (PostBucketsPayload.PolicyKeyEnum)Enum.Parse(typeof(PostBucketsPayload.PolicyKeyEnum), wnd.BucketType.Text, true); string region = wnd.BucketRegion.Text; PostBucketsPayload payload = new PostBucketsPayload(wnd.BucketName.Text, null, bucketType); ApiResponse <dynamic> response = await ossBuckets.CreateBucketAsyncWithHttpInfo(payload, region); httpErrorHandler(response, "Failed to create bucket"); if (region == (string)ForgeRegion.SelectedItem) { BucketsInRegion.Items.Add(wnd.BucketName.Text); BucketsInRegion.SelectedItem = wnd.BucketName.Text; } else { MessageBox.Show("Bucket successfully created!", APP_NAME, MessageBoxButton.OK, MessageBoxImage.Information); } } catch (ApiException apiex) { if (apiex.ErrorCode != 409) // Already exists - we're good { MessageBox.Show("Exception when calling BucketsApi.CreateBucketAsyncWithHttpInfo: " + apiex.Message, APP_NAME, MessageBoxButton.OK, MessageBoxImage.Error); } else { MessageBox.Show("This bucket already exist, choose another name!", APP_NAME, MessageBoxButton.OK, MessageBoxImage.Warning); } } catch (Exception ex) { MessageBox.Show("Exception when calling BucketsApi.CreateBucketAsyncWithHttpInfo: " + ex.Message, APP_NAME, MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Create Bucket /// </summary> private async Task <IActionResult> CreateBucket() { dynamic oauth = await OAuthController.GetInternalAsync(); string bucketkey = "inventorilogicda" + nickName.ToLower(); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = oauth.access_token; dynamic buckets = await bucketsApi.GetBucketsAsync(); bool bucketExists = buckets.items.ToString().Contains(bucketkey); if (!bucketExists) { PostBucketsPayload postBucket = new PostBucketsPayload(bucketkey, null, PostBucketsPayload.PolicyKeyEnum.Transient); dynamic newbucket = await bucketsApi.CreateBucketAsync(postBucket); } return(Ok()); }
private async Task <bool> UploadToBucket(string bucketKey, string objectName, string filePath) { // get the bucket... dynamic oauth = await OAuthController2L.GetInternalAsync(); ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; // upload file to OSS Bucket // 1. ensure bucket existis BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // upload the file/object, which will create a new object dynamic uploadedObj; using (StreamReader streamReader = new StreamReader(filePath)) { uploadedObj = await objects.UploadObjectAsync( bucketKey, objectName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } // cleanup System.IO.File.Delete(filePath); return(true); }
public async Task UploadDataSetAsync() { dynamic oauth = await OAuthController.GetInternalAsync(); var nickname = await GetNicknameAsync(); string bucketKey = nickname.ToLower() + BucketKey; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { var postBuckets = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Persistent); dynamic result = buckets.CreateBucket(postBuckets); //Console.WriteLine("bucket: " + result.ToString()); } catch (Exception) { // Most likely bucket already exists, we'll just skip this error and catch any real errors on upload } ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; var objectName = ObjectName; // string | URL-encoded object name var contentLength = 56; // int? | Indicates the size of the request body. System.IO.Stream body = File.OpenRead(DataSet); /// path / to / file.txt; // System.IO.Stream | try { var result = objects.UploadObject(bucketKey, objectName, contentLength, body); } catch (Exception e) { Console.WriteLine("Error uploading data set: " + e.Message); } }
protected async Task <XrefTreeArgument> BuildUploadURL(string resultFilename) { BucketsApi buckets = new BucketsApi(); dynamic token = await Credentials.Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate, Scope.DataWrite }); buckets.Configuration.AccessToken = token.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(Utils.BucketName, null, PostBucketsPayload.PolicyKeyEnum.Transient); try { await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { } ObjectsApi objects = new ObjectsApi(); dynamic signedUrl = await objects.CreateSignedResourceAsyncWithHttpInfo(Utils.BucketName, resultFilename, new PostBucketsSigned(5), "readwrite"); return(new XrefTreeArgument() { Url = (string)(signedUrl.Data.signedUrl), Verb = Verb.Put }); }
public async Task <string> UploadObject() { HttpRequest req = HttpContext.Current.Request; // we must have 1 file on the request (multiple files not handles on this sample) if (req.Files.Count != 1) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unexpected number of files")); } HttpPostedFile file = req.Files[0]; // save the file on the server string bucketKey = Utils.GenerateRandomBucketName(); var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), bucketKey, file.FileName); if (!Directory.Exists(fileSavePath)) { Directory.CreateDirectory(fileSavePath); } file.SaveAs(fileSavePath); try { // authenticate with Forge dynamic oauth = await Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate, Scope.DataRead, Scope.DataCreate, Scope.DataWrite }); // create the bucket BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); dynamic bucketResult = await buckets.CreateBucketAsync(bucketPayload); // upload the file/object, which will create a new object ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; dynamic uploadedObj; using (StreamReader streamReader = new StreamReader(fileSavePath)) { uploadedObj = await objects.UploadObjectAsync(bucketKey, file.FileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); } // start translating the file List <JobPayloadItem> outputs = new List <JobPayloadItem>() { new JobPayloadItem( JobPayloadItem.TypeEnum.Svf, new List <JobPayloadItem.ViewsEnum>() { JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d }) }; JobPayload job = new JobPayload(new JobPayloadInput(Utils.Base64Encode(uploadedObj.objectId)), new JobPayloadOutput(outputs)); DerivativesApi derivative = new DerivativesApi(); derivative.Configuration.AccessToken = oauth.access_token; dynamic jobPosted = await derivative.TranslateAsync(job); } catch (System.Exception ex) { // for this testing app, let's throw a full descriptive expcetion, // which is not a good idea in production throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message + ex.InnerException)); } // cleanup server File.Delete(fileSavePath); return(bucketKey); }
public ActionResult Upload(HttpPostedFileBase file) { if (file == null || file.ContentLength == 0) { return(RedirectToAction("Index")); } string fileName = Path.GetFileName(file.FileName); string fileSavePath = Path.Combine(Server.MapPath("~/App_Data/"), fileName); file.SaveAs(fileSavePath); // get a write enabled token TwoLeggedApi oauthApi = new TwoLeggedApi(); dynamic bearer = oauthApi.Authenticate( WebConfigurationManager.AppSettings["FORGE_CLIENT_ID"], WebConfigurationManager.AppSettings["FORGE_CLIENT_SECRET"], "client_credentials", new Scope[] { Scope.BucketCreate, Scope.DataCreate, Scope.DataWrite, Scope.DataRead }); // create a randomg bucket name (fixed prefix + randomg guid) string bucketKey = "forgeapp" + Guid.NewGuid().ToString("N").ToLower(); // create the Forge bucket PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient /* erase after 24h*/); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = bearer.access_token; dynamic newBucket = bucketsApi.CreateBucket(postBucket); // upload file (a.k.a. Objects) ObjectsApi objectsApi = new ObjectsApi(); oauthApi.Configuration.AccessToken = bearer.access_token; dynamic newObject; using (StreamReader fileStream = new StreamReader(fileSavePath)) { newObject = objectsApi.UploadObject(bucketKey, fileName, (int)fileStream.BaseStream.Length, fileStream.BaseStream, "application/octet-stream"); } // translate file string objectIdBase64 = ToBase64(newObject.objectId); List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>() { new JobPayloadItem( JobPayloadItem.TypeEnum.Svf /* Viewer*/, new List <JobPayloadItem.ViewsEnum>() { JobPayloadItem.ViewsEnum._3d, JobPayloadItem.ViewsEnum._2d }) }; JobPayload postTranslation = new JobPayload( new JobPayloadInput(objectIdBase64), new JobPayloadOutput(postTranslationOutput)); DerivativesApi derivativeApi = new DerivativesApi(); derivativeApi.Configuration.AccessToken = bearer.access_token; dynamic translation = derivativeApi.Translate(postTranslation); // check if is ready int progress = 0; do { System.Threading.Thread.Sleep(1000); // wait 1 second try { dynamic manifest = derivativeApi.GetManifest(objectIdBase64); progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value)); } catch (Exception ex) { } } while (progress < 100); // clean up System.IO.File.Delete(fileSavePath); //Directory.Delete(fileSavePath, true); return(RedirectToAction("DisplayModel", "Home", new { characterName = objectIdBase64 })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { // basic input validation JObject workItemData = JObject.Parse(input.data); string widthParam = workItemData["width"].Value <string>(); string heigthParam = workItemData["height"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); // save the file on the server var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "-designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.Width = widthParam; inputJson.Height = heigthParam; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { // basic input validation JObject workItemData = JObject.Parse(input.data); string widthParam = workItemData["width"].Value <string>(); string heigthParam = workItemData["height"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); // save the file on the server var fileSavePath = Path.Combine(_env.ContentRootPath, input.inputFile.FileName); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "_designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), input.inputFile.FileName); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file JObject inputFileArgument = new JObject { new JProperty("url", string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS)), new JProperty("headers", new JObject { new JProperty("Authorization", "Bearer " + oauth.access_token) }) }; // 2. input json dynamic inputJson = new JObject(); inputJson.Width = widthParam; inputJson.Height = heigthParam; JObject inputJsonArgument = new JObject { new JProperty("url", "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")) }; // ToDo: need to improve this // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), input.inputFile.FileName); // avoid overriding JObject outputFileArgument = new JObject { new JProperty("verb", "PUT"), new JProperty("url", string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS)), new JProperty("headers", new JObject { new JProperty("Authorization", "Bearer " + oauth.access_token) }) }; // prepare & submit workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}", OAuthController.GetAppSetting("FORGE_WEBHOOK_CALLBACK_HOST"), browerConnectionId); WorkItem workItemSpec = new WorkItem( null, activityName, new Dictionary <string, JObject>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, //{ "onProgress", new JObject { new JProperty("verb", "POST"), new JProperty("url", callbackUrl) }}, { "onComplete", new JObject { new JProperty("verb", "POST"), new JProperty("url", callbackUrl) } } }, null); WorkItemsApi workItemApi = new WorkItemsApi(); workItemApi.Configuration.AccessToken = oauth.access_token;; WorkItemStatus newWorkItem = await workItemApi.WorkItemsCreateWorkItemsAsync(null, null, workItemSpec); return(Ok(new { WorkItemId = newWorkItem.Id })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { try { DataSetBuilder dataSetBuilder = new DataSetBuilder(LocalDataSetFolder, "DataSet"); dataSetBuilder.SaveJsonData(input.shelfData, "params.json"); dataSetBuilder.ZipFolder("MyWallShelf.zip"); } catch (Exception ex) { return(Ok(new { WorkItemId = ex.Message }));; } JObject connItemData = JObject.Parse(input.forgeData); string uniqueActivityName = string.Format("{0}.{1}+{2}", NickName, ActivityName, Alias); string browerConnectionId = connItemData["browerConnectionId"].Value <string>(); // TODO - this piece of cod will be used for sending picture in Visualization module // save the file on the server var fileSavePath = Path.Combine(LocalDataSetFolder, "MyWallShelf.zip"); //using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, bucketRegion); //TODO - use EMEA buckets also } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "MyShelf.zip"); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); //System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Verb = Verb.Get, LocalName = "Wall_shelf", PathInZip = "MyWallShelf.iam", Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json /*dynamic inputJson = new JObject(); * inputJson.Width = widthParam; * inputJson.Height = heigthParam; * XrefTreeArgument inputJsonArgument = new XrefTreeArgument() * { * Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") * };*/ // 3. output file // TODO - output file name should be passed from client string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Result.zip"); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 3a. output pdf fajl out of zipping string outputPDFFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Result.pdf"); // avoid overriding XrefTreeArgument outputPDFFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputPDFFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format( "{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", //OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), "https://webwallshelfbuilder.herokuapp.com", browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = uniqueActivityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, //{ "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "outputPDFFile", outputPDFFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; try { WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); } catch (Exception e) { return(Ok(new { WorkItemId = e.Message })); } }
protected async void uploadAndTranslate(object sender, EventArgs e) { // create a randomg bucket name (fixed prefix + randomg guid) string bucketKey = "forgeapp" + Guid.NewGuid().ToString("N").ToLower(); // upload the file (to your server) string fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), bucketKey, FileUpload1.FileName); Directory.CreateDirectory(Path.GetDirectoryName(fileSavePath)); FileUpload1.SaveAs(fileSavePath); // get a write enabled token TwoLeggedApi oauthApi = new TwoLeggedApi(); dynamic bearer = await oauthApi.AuthenticateAsync( WebConfigurationManager.AppSettings["FORGE_CLIENT_ID"], WebConfigurationManager.AppSettings["FORGE_CLIENT_SECRET"], "client_credentials", new Scope[] { Scope.BucketCreate, Scope.DataCreate, Scope.DataWrite, Scope.DataRead }); // create the Forge bucket PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient /* erase after 24h*/); BucketsApi bucketsApi = new BucketsApi(); bucketsApi.Configuration.AccessToken = bearer.access_token; dynamic newBucket = await bucketsApi.CreateBucketAsync(postBucket); // upload file (a.k.a. Objects) ObjectsApi objectsApi = new ObjectsApi(); oauthApi.Configuration.AccessToken = bearer.access_token; dynamic newObject; using (StreamReader fileStream = new StreamReader(fileSavePath)) { newObject = await objectsApi.UploadObjectAsync(bucketKey, FileUpload1.FileName, (int)fileStream.BaseStream.Length, fileStream.BaseStream, "application/octet-stream"); } // translate file string objectIdBase64 = ToBase64(newObject.objectId); List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>() { new JobPayloadItem( JobPayloadItem.TypeEnum.Svf /* Viewer*/, new List <JobPayloadItem.ViewsEnum>() { JobPayloadItem.ViewsEnum._3d, JobPayloadItem.ViewsEnum._2d }) }; JobPayload postTranslation = new JobPayload( new JobPayloadInput(objectIdBase64), new JobPayloadOutput(postTranslationOutput)); DerivativesApi derivativeApi = new DerivativesApi(); derivativeApi.Configuration.AccessToken = bearer.access_token; dynamic translation = await derivativeApi.TranslateAsync(postTranslation); // check if is ready int progress = 0; do { System.Threading.Thread.Sleep(1000); // wait 1 second try { dynamic manifest = await derivativeApi.GetManifestAsync(objectIdBase64); progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value)); } catch (Exception ex) { } } while (progress < 100); // ready!!!! // register a client-side script to show this model Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowModel", string.Format("<script>showModel('{0}');</script>", objectIdBase64)); // clean up Directory.Delete(Path.GetDirectoryName(fileSavePath), true); }