Ejemplo n.º 1
0
        public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel)
        {
            Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = credentials.TokenInternal;

            var manifest = await derivative.GetManifestAsync(objModel.urn);

            if (manifest.status == "inprogress")
            {
                return(null);                                 // another job in progress
            }
            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(JobPayloadItem.TypeEnum.Ifc)
            };

            JobPayload job = new JobPayload(new JobPayloadInput(objModel.urn), new JobPayloadOutput(outputs));

            // start the translation
            dynamic jobPosted = await derivative.TranslateAsync(job, false /* do not force re-translate */);

            return(jobPosted);
        }
Ejemplo n.º 2
0
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs));

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
Ejemplo n.º 3
0
        /**
         * Example of how to send a translate to SVF job request.
         * Uses the oauth2TwoLegged and twoLeggedCredentials objects that you retrieved previously.
         * @param urn - the urn of the file to translate
         */
        private static dynamic translateToSVF(string urn)
        {
            Console.WriteLine("***** Sending Derivative API translate request");
            JobPayloadInput jobInput = new JobPayloadInput(
                System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(urn))
                );
            JobPayloadOutput jobOutput = new JobPayloadOutput(
                new List <JobPayloadItem> (
                    new JobPayloadItem [] {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum> (
                        new JobPayloadItem.ViewsEnum [] { JobPayloadItem.ViewsEnum._3d }
                        ),
                    null
                    )
            }
                    )
                );
            JobPayload job      = new JobPayload(jobInput, jobOutput);
            dynamic    response = derivativesApi.Translate(job, true);

            Console.WriteLine("***** Response for Translating File to SVF: " + response.ToString());
            return(response);
        }
        public async Task <IActionResult> StartTranslation([FromBody] JObject translateSpecs)
        {
            string urn = translateSpecs["urn"].Value <string>();

            dynamic oauth = await OAuthController.GetInternalAsync();

            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));

            // translationを開始する
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(Ok());
        }
Ejemplo n.º 5
0
        public static InvocationData DeserializePayload(string payload)
        {
            JobPayload jobPayload = null;
            Exception  exception  = null;

            try
            {
                jobPayload = SerializationHelper.Deserialize <JobPayload>(payload);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception == null && jobPayload.TypeName != null && jobPayload.MethodName != null)
            {
                return(new InvocationData(
                           jobPayload.TypeName,
                           jobPayload.MethodName,
                           SerializationHelper.Serialize(jobPayload.ParameterTypes),
                           SerializationHelper.Serialize(jobPayload.Arguments)));
            }

            var data = SerializationHelper.Deserialize <InvocationData>(payload);

            if (data.Type == null || data.Method == null)
            {
                data = SerializationHelper.Deserialize <InvocationData>(payload, SerializationOption.User);
            }

            return(data);
        }
Ejemplo n.º 6
0
        public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            if (string.IsNullOrEmpty(objModel.rootFilename))
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName, true, objModel.rootFilename), new JobPayloadOutput(outputs));
            }


            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true /* force re-translate if already here, required data:write*/);

            return(jobPosted);
        }
Ejemplo n.º 7
0
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await Utility.OAuth.Get2LeggedTokenAsync(new Scope[] { Scope.DataRead, Scope.DataWrite, Scope.DataCreate });

            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            if (string.IsNullOrEmpty(objModel.rootFilename))
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectKey), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectKey, true, objModel.rootFilename), new JobPayloadOutput(outputs));
            }


            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
Ejemplo n.º 8
0
        private async static Task <bool> Translate2Obj(string urn, string guid, JobObjOutputPayloadAdvanced.UnitEnum unit = JobObjOutputPayloadAdvanced.UnitEnum.Meter, JobPayloadDestination.RegionEnum targetRegion = JobPayloadDestination.RegionEnum.US)
        {
            try {
                Console.WriteLine("**** Requesting OBJ translation for: " + urn);
                JobPayloadInput  jobInput  = new JobPayloadInput(urn);
                JobPayloadOutput jobOutput = new JobPayloadOutput(
                    new List <JobPayloadItem> (
                        new JobPayloadItem [] {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Obj,
                        null,
                        //new JobObjOutputPayloadAdvanced (null, guid, new List<int> () { -1 }, unit) // all
                        new JobObjOutputPayloadAdvanced(null, guid, new List <int> ()
                    {
                        1526, 1527
                    }, unit)
                        )
                }
                        ),
                    new JobPayloadDestination(targetRegion)
                    );
                JobPayload            job      = new JobPayload(jobInput, jobOutput);
                bool                  bForce   = true;
                ApiResponse <dynamic> response = await DerivativesAPI.TranslateAsyncWithHttpInfo(job, bForce);

                httpErrorHandler(response, "Failed to register file for OBJ translation");
                return(true);
            } catch (Exception) {
                Console.WriteLine("**** Failed to register file for OBJ translation");
                return(false);
            }
        }
Ejemplo n.º 9
0
        private async static Task <bool> Translate2Stl(string urn, string guid, JobObjOutputPayloadAdvanced.UnitEnum unit = JobObjOutputPayloadAdvanced.UnitEnum.Meter, JobPayloadDestination.RegionEnum targetRegion = JobPayloadDestination.RegionEnum.US)
        {
            try {
                Console.WriteLine("**** Requesting STL translation for: " + urn);
                JobPayloadInput  jobInput  = new JobPayloadInput(urn);
                JobPayloadOutput jobOutput = new JobPayloadOutput(
                    new List <JobPayloadItem> (
                        new JobPayloadItem [] {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Stl,
                        null,
                        new JobStlOutputPayloadAdvanced(JobStlOutputPayloadAdvanced.FormatEnum.Ascii, true, JobStlOutputPayloadAdvanced.ExportFileStructureEnum.Single)
                        )
                }
                        ),
                    new JobPayloadDestination(targetRegion)
                    );
                JobPayload            job      = new JobPayload(jobInput, jobOutput);
                bool                  bForce   = true;
                ApiResponse <dynamic> response = await DerivativesAPI.TranslateAsyncWithHttpInfo(job, bForce);

                httpErrorHandler(response, "Failed to register file for STL translation");
                return(true);
            } catch (Exception) {
                Console.WriteLine("**** Failed to register file for STL translation");
                return(false);
            }
        }
Ejemplo n.º 10
0
        private async Task TranslateFile(string objectId, string rootFileName)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                }
                    )
            };
            JobPayload job;
            string     urn = Base64Encode(objectId);

            if (rootFileName != null)
            {
                job = new JobPayload(new JobPayloadInput(urn, true, rootFileName), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));
            }

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;

            await derivative.TranslateAsync(job);
        }
Ejemplo n.º 11
0
        private async static Task <bool> Translate2Svf2(string urn, JobPayloadDestination.RegionEnum targetRegion = JobPayloadDestination.RegionEnum.US)
        {
            try {
                Console.WriteLine("**** Requesting SVF2 translation for: " + urn);
                JobPayloadInput  jobInput  = new JobPayloadInput(urn);
                JobPayloadOutput jobOutput = new JobPayloadOutput(
                    new List <JobPayloadItem> (
                        new JobPayloadItem [] {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Svf2,
                        new List <JobPayloadItem.ViewsEnum> (
                            new JobPayloadItem.ViewsEnum [] {
                        JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d
                    }
                            ),
                        null
                        )
                }
                        ),
                    new JobPayloadDestination(targetRegion)
                    );
                JobPayload            job      = new JobPayload(jobInput, jobOutput);
                bool                  bForce   = true;
                ApiResponse <dynamic> response = await DerivativesAPI.TranslateAsyncWithHttpInfo(job, bForce);

                httpErrorHandler(response, "Failed to register file for SVF2 translation");
                return(true);
            } catch (Exception) {
                Console.WriteLine("**** Failed to register file for SVF2 translation");
                return(false);
            }
        }
        // Token: 0x06000038 RID: 56 RVA: 0x00002D10 File Offset: 0x00000F10
        protected RetrievedPayload RetrieveJobDistributionPayload(OrganizationId organizationId, Guid jobRunId, int taskId)
        {
            RetrievedPayload      retrievedPayload      = new RetrievedPayload();
            ComplianceJobProvider complianceJobProvider = new ComplianceJobProvider(organizationId);
            Guid tenantGuid = organizationId.GetTenantGuid();

            retrievedPayload.IsComplete = this.HasMoreTasks(organizationId, jobRunId);
            IEnumerable <CompositeTask> enumerable = from x in complianceJobProvider.FindCompositeTasks(tenantGuid, jobRunId, null, null)
                                                     where x.TaskId > taskId
                                                     select x;

            if (enumerable != null)
            {
                foreach (CompositeTask compositeTask in enumerable)
                {
                    JobPayload jobPayload = new JobPayload();
                    jobPayload.Target = new Target
                    {
                        TargetType = Target.Type.MailboxSmtpAddress,
                        Identifier = compositeTask.UserMaster
                    };
                    PayloadReference payloadReference = PayloadHelper.GetPayloadReference(jobRunId, compositeTask.TaskId);
                    jobPayload.Children.Add(ComplianceSerializer.Serialize <PayloadReference>(PayloadReference.Description, payloadReference));
                    retrievedPayload.Children.Add(jobPayload);
                    retrievedPayload.Bookmark = compositeTask.TaskId.ToString();
                }
                return(retrievedPayload);
            }
            throw new ArgumentException(string.Format("Not Task Data Found. TenantId-{0} JobId-{1} and TaskId-{2}", tenantGuid, jobRunId, taskId));
        }
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the webhook callback
            DerivativeWebhooksApi webhook = new DerivativeWebhooksApi();

            webhook.Configuration.AccessToken = oauth.access_token;
            dynamic existingHooks = await webhook.GetHooksAsync(DerivativeWebhookEvent.ExtractionFinished);

            // get the callback from your settings (e.g. web.config)
            string callbackUlr = OAuthController.GetAppSetting("FORGE_WEBHOOK_URL") + "/api/forge/callback/modelderivative";

            bool createHook = true; // need to create, we don't know if our hook is already there...

            foreach (KeyValuePair <string, dynamic> hook in new DynamicDictionaryItems(existingHooks.data))
            {
                if (hook.Value.scope.workflow.Equals(objModel.connectionId))
                {
                    // ok, found one hook with the same workflow, no need to create...
                    createHook = false;
                    if (!hook.Value.callbackUrl.Equals(callbackUlr))
                    {
                        await webhook.DeleteHookAsync(DerivativeWebhookEvent.ExtractionFinished, new System.Guid(hook.Value.hookId));

                        createHook = true; // ops, the callback URL is outdated, so delete and prepare to create again
                    }
                }
            }

            // need to (re)create the hook?
            if (createHook)
            {
                await webhook.CreateHookAsync(DerivativeWebhookEvent.ExtractionFinished, callbackUlr, objModel.connectionId);
            }

            // prepare the payload
            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(objModel.objectName), new JobPayloadOutput(outputs), new JobPayloadMisc(objModel.connectionId));


            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true /* force re-translate if already here, required data:write*/);

            return(jobPosted);
        }
Ejemplo n.º 14
0
        private async void onClickTranslate(object sender, EventArgs e)
        {
            // for now, just one translation at a time
            if (_translationTimer.Enabled)
            {
                return;
            }

            // check level 1 of objects
            if (treeBuckets.SelectedNode == null || treeBuckets.SelectedNode.Level != 1)
            {
                MessageBox.Show("Please select an object", "Objects required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string urn = (string)treeBuckets.SelectedNode.Tag;

            // prepare a SVF translation
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            //if (string.IsNullOrEmpty(objModel.rootFilename))
            job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));
            //else
            //  job = new JobPayload(new JobPayloadInput(objModel.objectKey, true, objModel.rootFilename), new JobPayloadOutput(outputs));

            // start progress bar for translation
            progressBar.Show();
            progressBar.Value      = 0;
            progressBar.Minimum    = 0;
            progressBar.Maximum    = 100;
            progressBar.CustomText = "Starting translation job...";

            // start translation job
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = AccessToken;
            dynamic jobPosted = await derivative.TranslateAsync(job, true);

            // start a monitor job to follow the translation
            _translationTimer.Tick    += new EventHandler(isTranslationReady);
            _translationTimer.Tag      = urn;
            _translationTimer.Interval = 5000;
            _translationTimer.Enabled  = true;
        }
Ejemplo n.º 15
0
        protected override ComplianceMessage CreateStartJobMessage()
        {
            ComplianceMessage complianceMessage = base.CreateStartJobMessage();

            complianceMessage.WorkDefinitionType = WorkDefinitionType.EDiscovery;
            JobPayload jobPayload = new JobPayload();

            jobPayload.JobId     = this.DataObject.JobRunId.ToString();
            jobPayload.Target    = complianceMessage.MessageTarget;
            jobPayload.PayloadId = string.Empty;
            jobPayload.Children.Add(PayloadHelper.GetPayloadReference(this.DataObject.JobRunId, -1));
            jobPayload.Payload        = this.DataObject.GetExchangeWorkDefinition();
            complianceMessage.Payload = ComplianceSerializer.Serialize <JobPayload>(JobPayload.Description, jobPayload);
            return(complianceMessage);
        }
        public JobPayload LoadJob()
        {
            JobPayload j    = new JobPayload();
            var        dict = keyValuePairs();

            j.StartWord             = dict[_s];
            j.EndWord               = dict[_f];
            j.SourceFilePath        = dict[_d];
            j.ResultPublicationPath = dict[_o];
            //[todo: get from cmd line]
            j.TypeOfResult = JobPayload.ResultType.FIRST;
            j.TypeOfSearch = JobPayload.SearchType.BREATH_FIRST;

            return(j);
        }
        public static InvocationData DeserializePayload(string payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            JobPayload jobPayload = null;
            Exception  exception  = null;

            try
            {
                jobPayload = SerializationHelper.Deserialize <JobPayload>(payload);
                if (jobPayload == null)
                {
                    throw new InvalidOperationException("Deserialize<JobPayload> returned `null` for a non-null payload.");
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception == null && jobPayload.TypeName != null && jobPayload.MethodName != null)
            {
                return(new InvocationData(
                           jobPayload.TypeName,
                           jobPayload.MethodName,
                           SerializationHelper.Serialize(jobPayload.ParameterTypes),
                           SerializationHelper.Serialize(jobPayload.Arguments)));
            }

            var data = SerializationHelper.Deserialize <InvocationData>(payload);

            if (data == null)
            {
                throw new InvalidOperationException("Deserialize<InvocationData> returned `null` for a non-null payload.");
            }

            if (data.Type == null || data.Method == null)
            {
                data = SerializationHelper.Deserialize <InvocationData>(payload, SerializationOption.User);
            }

            return(data);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Translate object by safe urn from object.
        /// </summary>
        /// <param name="safeUrn">Object's, that will be translated, URN</param>
        /// <returns>Nothing...</returns>
        public async Task TranslateObject(string safeUrn)
        {
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(safeUrn), new JobPayloadOutput(outputs));
            api = new DerivativesApi();
            api.Configuration.AccessToken = this.token.AccessToken;
            dynamic jobPosted = await api.TranslateAsync(job);

            Dictionary <string, dynamic> callBackData = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(jobPosted.ToString());

            this.URN = callBackData["urn"].ToString();
            string status = callBackData["result"];

            while (status == "inprogress" || status == "pending" || status == "created")
            {
                dynamic resp = await api.GetManifestAsyncWithHttpInfo(this.URN);

                JObject jObject = JsonConvert.DeserializeObject <JObject>(resp.Data.ToString());

                status = jObject["status"].ToString();
            }

            if (status == "success")
            {
                Completed?.Invoke(null, new EventArgs());
            }

            else if (status == "failed" || status == "timeout")
            {
                Failed?.Invoke(null, new EventArgs());
            }

            this.IsTranslated = status == "success";
        }
        public async Task <bool> TranslateFile(string urn)
        {
            if (urn == null)
            {
                throw new ArgumentNullException("urn");
            }

            var isAuthorized = await IsAuthorized();

            if (!isAuthorized)
            {
                _logger.Log(LogType.Error, "Cannot be authorized for translating file");
                return(false);
            }

            var jobPayloadItems = new List <JobPayloadItem>
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };

            var job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(jobPayloadItems));

            var derivative = new DerivativesApi
            {
                Configuration = { AccessToken = AuthenticationToken.AccessToken }
            };

            try
            {
                dynamic jobPosted = await derivative.TranslateAsync(job);
            }
            catch (Exception ex)
            {
                _logger.Log(LogType.Error, "Exception while translating file: " + ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 20
0
        private async Task <bool> TranslateObject(ObservableCollection <ForgeObjectInfo> items, ForgeObjectInfo item)
        {
            try {
                string          urn      = URN((string)BucketsInRegion.SelectedItem, item, false);
                JobPayloadInput jobInput = new JobPayloadInput(
                    urn,
                    System.IO.Path.GetExtension(item.Name).ToLower() == ".zip",
                    item.Name
                    );
                JobPayloadOutput jobOutput = new JobPayloadOutput(
                    new List <JobPayloadItem> (
                        new JobPayloadItem [] {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Svf,
                        new List <JobPayloadItem.ViewsEnum> (
                            new JobPayloadItem.ViewsEnum [] {
                        JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d
                    }
                            ),
                        null
                        )
                }
                        )
                    );
                JobPayload     job    = new JobPayload(jobInput, jobOutput);
                bool           bForce = true;
                DerivativesApi md     = new DerivativesApi();
                md.Configuration.AccessToken = accessToken;
                ApiResponse <dynamic> response = await md.TranslateAsyncWithHttpInfo(job, bForce);

                httpErrorHandler(response, "Failed to register file for translation");
                item.TranslationRequested = StateEnum.Busy;
                item.Manifest             = response.Data;

                JobProgress jobWnd = new JobProgress(item, accessToken);
                jobWnd._callback = new JobCompletedDelegate(this.TranslationCompleted);
                jobWnd.Owner     = this;
                jobWnd.Show();
            } catch (Exception /*ex*/) {
                item.TranslationRequested = StateEnum.Idle;
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Translate object
        /// </summary>
        private async Task <dynamic> TranslateObject(dynamic objModel, string outputFileName)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            string objectIdBase64 = ToBase64(objModel.objectId);
            // prepare the payload
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(
                new JobPayloadInput(objectIdBase64, false, outputFileName),
                new JobPayloadOutput(postTranslationOutput)
                );

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true);

            // check if it is complete.
            dynamic manifest = null;

            do
            {
                System.Threading.Thread.Sleep(1000); // wait 1 second
                try
                {
                    manifest = await derivative.GetManifestAsync(objectIdBase64);
                }
                catch (Exception) { }
            } while (manifest.progress != "complete");
            return(jobPosted.urn);
        }
Ejemplo n.º 22
0
        public async Task <dynamic> TranslateTask(TranslateObject translateObject)
        {
            string Urn          = translateObject.objectName;
            string rootFileName = translateObject.RootFileName;

            JobPayload job = BusinessLogicRunner.RunnerStatmentOptional <JobPayload>((rootFileName != null),
                                                                                     new JobPayload(new JobPayloadInput(Urn, true, rootFileName), new JobPayloadOutput(outputs)),
                                                                                     new JobPayload(new JobPayloadInput(Urn), new JobPayloadOutput(outputs)));

            DerivativesApi derivativesApi =
                GeneralTokenConfigurationSettings <IDerivativesApi> .SetToken(new DerivativesApi(),
                                                                              await _authServiceAdapter.GetSecondaryTokenTask());



            dynamic jobTranslate = await derivativesApi.TranslateAsync(job, true);

            return(jobTranslate);
        }
Ejemplo n.º 23
0
        public async Task <Model> UploadModel(string objectKey, Stream body, string zipEntrypoint)
        {
            await EnsureBucketExists(bucketKey);

            // Upload object
            var objectsApi = new ObjectsApi();

            objectsApi.Configuration.AccessToken = (await GetAccessToken(INTERNAL_TOKEN_SCOPES)).AccessToken;
            var response = await objectsApi.UploadObjectAsync(bucketKey, objectKey, (int)body.Length, body);

            var model = new Model {
                Name = response.objectKey, URN = Base64Encode(response.objectId)
            };

            // Start object translation
            var derivativesApi = new DerivativesApi();

            derivativesApi.Configuration.AccessToken = (await GetAccessToken(INTERNAL_TOKEN_SCOPES)).AccessToken;
            var payload = new JobPayload();

            payload.Input  = new JobPayloadInput(model.URN);
            payload.Output = new JobPayloadOutput(new List <JobPayloadItem>());
            payload.Output.Formats.Add(
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum> {
                JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d
            }
                    )
                );
            if (!string.IsNullOrEmpty(zipEntrypoint))
            {
                payload.Input.CompressedUrn = true;
                payload.Input.RootFilename  = zipEntrypoint;
            }
            await derivativesApi.TranslateAsync(payload);

            return(model);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Translate the uploaded zip file.
        /// </summary>
        private async static Task <dynamic> TranslateZipFile(dynamic newObject)
        {
            string objectIdBase64 = ToBase64(newObject.objectId);
            string rootfilename   = Path.GetFileName(fileList[0]);
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._3d,
                    JobPayloadItem.ViewsEnum._2d
                })
            };

            JobPayload postTranslation = new JobPayload(
                new JobPayloadInput(objectIdBase64, true, rootfilename),
                new JobPayloadOutput(postTranslationOutput));
            DerivativesApi derivativeApi = new DerivativesApi();

            derivativeApi.Configuration.AccessToken = InternalToken.access_token;
            dynamic translation = await derivativeApi.TranslateAsync(postTranslation);

            // check if it is complete.
            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) { }
            } while (progress < 100);
            return(translation);
        }
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayloadInput jobPayloadInput;

            if (objModel.ObjectType == "zipfile3D")
            {
                jobPayloadInput = new JobPayloadInput(objModel.ObjectName, true, "MyWallShelf.iam");
            }
            else if (objModel.ObjectType == "zipfile2D")
            {
                jobPayloadInput = new  JobPayloadInput(objModel.ObjectName, true, "WallShelfDrawings.idw");
            }
            else
            {
                jobPayloadInput = new JobPayloadInput(objModel.ObjectName);
            }
            // start the translation
            JobPayload job = new JobPayload(jobPayloadInput, new JobPayloadOutput(outputs));

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
Ejemplo n.º 26
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "sampleDB",
                 collectionName: "sampleContainer",
                 ConnectionStringSetting = "CosmosDBConnection")] out JobPayload document,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = new StreamReader(req.Body).ReadToEndAsync().Result;

            JobPayload jobData = JsonConvert.DeserializeObject <JobPayload>(requestBody);

            jobData.Id = Guid.NewGuid().ToString();

            // send to cosmosDB
            document = jobData;

            return(jobData != null
                ? (ActionResult) new OkObjectResult($"Job {jobData.Id} submitted for processing")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
        // Token: 0x06000039 RID: 57 RVA: 0x00002E68 File Offset: 0x00001068
        protected RetrievedPayload RetrieveTaskDistributionPayload(OrganizationId organizationId, Guid jobRunId, int taskId)
        {
            RetrievedPayload      retrievedPayload      = new RetrievedPayload();
            ComplianceJobProvider complianceJobProvider = new ComplianceJobProvider(organizationId);
            Guid          tenantGuid    = organizationId.GetTenantGuid();
            CompositeTask compositeTask = complianceJobProvider.FindCompositeTasks(tenantGuid, jobRunId, null, new int?(taskId)).SingleOrDefault <CompositeTask>();

            if (compositeTask != null)
            {
                foreach (string identifier in compositeTask.Users)
                {
                    JobPayload jobPayload = new JobPayload();
                    jobPayload.Target = new Target
                    {
                        TargetType = Target.Type.MailboxSmtpAddress,
                        Identifier = identifier
                    };
                    retrievedPayload.Children.Add(jobPayload);
                }
                return(retrievedPayload);
            }
            throw new ArgumentException(string.Format("No Task data found. TenantId-{0} JobId-{1} and TaskId-{2}", tenantGuid, jobRunId, taskId));
        }
Ejemplo n.º 28
0
        public bool CreateJob(string jobType, string jobName, string jobDescription, WorkspaceModel workspaceModel)
        {
            var cloudComponent = GetCloudComponent(workspaceModel);

            if (cloudComponent == null)
            {
                return(false);
            }

            var numberOfBlocks = cloudComponent.NumberOfBlocks;
            var jobPayload     = new JobPayload
            {
                WorkspaceModel = workspaceModel,
                CreationTime   = DateTime.Now
            };

            var serialize = jobPayload.Serialize();

            var jobID = voluntLib.CreateJob(DefaultWorld, jobType, jobName, jobDescription, serialize,
                                            numberOfBlocks);

            return(jobID != -1);
        }
Ejemplo n.º 29
0
        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);
        }
Ejemplo n.º 30
0
        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 }));
        }