Esempio n. 1
0
        private async Task UploadFilesToAzure(string branch, IFormFileCollection files, string fileName)
        {
            foreach (var file in files)
            {
                byte[] bytes;
                using (var stream = file.OpenReadStream())
                {
                    bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);
                }

                var fileStream = (new MemoryStream(bytes));

                await AzureStorageUtil.UploadFromStream(fileStream, CBranch.ImagesContainer, fileName);

                var uri = AzureStorageUtil.GetUriFromBlob(CBranch.ImagesContainer, fileName);
                _branchImageBusiness.SaveBranchImages(new BranchImages()
                {
                    IdBranch      = new Guid(branch),
                    NameContainer = CBranch.ImagesContainer,
                    NameFile      = fileName,
                    UrlImage      = uri
                });
            }
        }
        public FileResult DownloadFile(int id, int tipo = 0)
        {
            byte[] fichero = new byte[] { };
            var    f       = db.Ficheros.Find(id);

            if (tipo == 0)
            {
                fichero = Convert.FromBase64String(f.datos);
            }
            else if (tipo == 1)
            {
                fichero = f.datosb;
            }
            else if (tipo == 2)
            {
                var cu = ConfigurationManager.AppSettings["AccountnameAzureStorage"];
                var cl = ConfigurationManager.AppSettings["PasswordAzureStorage"];
                var co = ConfigurationManager.AppSettings["ContainerAzureStorage"];

                var sto = new AzureStorageUtil(cu, cl, co);

                fichero = sto.RecuperarFichero(f.datos, co);
            }
            return(File(fichero, System.Net.Mime.MediaTypeNames.Application.Octet, f.nombre));
        }
        public async Task <string> DeleteImageBranch(Guid idImageBranch)
        {
            var imageBranch = _branchImageBusiness.GetBranchImageById(idImageBranch, ApplicationUserCurrent.AccountId);

            AzureStorageUtil.DeleteBlob(CBranch.ImagesContainer, imageBranch.NameFile);
            _branchImageBusiness.DeleteBranchImage(idImageBranch, ApplicationUserCurrent.AccountId);

            return(await GetBranchById(imageBranch.Id.ToString()));
        }
Esempio n. 4
0
        public string DeleteImageBranch(Guid idImageBranch)
        {
            var imageBranch = _branchImageBusiness.GetBranchImageById(idImageBranch, ApplicationUserCurrent.AccountId);

            AzureStorageUtil.DeleteBlob(CBranch.ImagesContainer, imageBranch.NameFile);
            _branchImageBusiness.DeleteBranchImage(idImageBranch, ApplicationUserCurrent.AccountId);

            var itemResult = _branchImageBusiness.GetBranchesImagesList(imageBranch.IdBranch, ApplicationUserCurrent.AccountId);

            return(JSonConvertUtil.Convert(itemResult));
        }
        public ActionResult GetBase64Azure(string nombre)
        {
            var cu = ConfigurationManager.AppSettings["AccountnameAzureStorage"];
            var cl = ConfigurationManager.AppSettings["PasswordAzureStorage"];
            var co = ConfigurationManager.AppSettings["ContainerAzureStorage"];

            var sto = new AzureStorageUtil(cu, cl, co);

            var data = sto.RecuperarFichero(nombre, co);

            return(View(Convert.ToBase64String(data)));
        }
Esempio n. 6
0
        public string GetUrlAzureContainerbyStrem(MemoryStream File, string namefile, string extension)
        {
            DateTime localDate = DateTime.Now;

            MemoryStream stream = File;

            AzureStorageUtil.UploadFromStream(stream, "evidencias", namefile + extension).Wait();
            var uri = AzureStorageUtil.GetUriFromBlob("evidencias", namefile + extension);

            // loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.

            return(uri);
        }
        private async Task <List <BranchImages> > GetBranchImagesInBase64(Guid idBranch)
        {
            //Éste método se encuentra a nivel de controlador debido a que la clase
            //de manejo de azurestorage se encuentra en proyecto Web
            var listResult = _branchImageBusiness.GetBranchesImagesList(idBranch, ApplicationUserCurrent.AccountId);

            foreach (var branchImage in listResult)
            {
                var imageB64 = await AzureStorageUtil.GetBase64FileFromBlob(CBranch.ImagesContainer, branchImage.NameFile);

                branchImage.UrlImage = $"data:image/gif;base64,{imageB64}";
            }
            return(listResult);
        }
Esempio n. 8
0
        public int _SaveImagesAsync(int code)
        {
            // var result = await Task.Run(() => {
            //var equipos = _equipmentBusiness.GetEquipamentFotos(code);

            //foreach (var mod in equipos)
            //{
            var model        = code != 0 ? _equipmentBusiness.GetEquipment(code, ApplicationUserCurrent.AccountId) : null;
            var equipmenturi = _equipament_timeBusiness.GetEquipamentTimeImages(model.Id);

            foreach (var eu in equipmenturi)
            {
                var FotosEqu = _equipament_timeBusiness.GetEquipamentidtype(eu.Idequipament, Convert.ToInt32(eu.idstatus));
                if (FotosEqu.Count == 0)
                {
                    string       sql         = $@"select _uri Uri, _TOP_LEVEL_AURI, [Table], orden, valor from [dbo].[vw_FotosTopsy_P]  where _TOP_LEVEL_AURI = '{eu.aggregateuri}'";
                    var          images      = _equipamentImagesBusiness.GetImageEquipamentusri(sql);
                    MemoryStream imageStream = null;
                    foreach (var i in images)
                    {
                        imageStream = new MemoryStream(i.valor.ToArray());
                        AzureStorageUtil.UploadFromStream(imageStream, "implementacion", i.Uri + ".jpg").Wait();
                        var uri = AzureStorageUtil.GetUriFromBlob("implementacion", i.Uri + ".jpg");
                        var equipamentImages = new EquipamentImages()
                        {
                            IdEquipament  = model.Id,
                            NameContainer = i.Uri,
                            NameFile      = i.Uri + ".jpg",
                            UrlImage      = uri,
                            IdAccount     = Global.AccountId,
                            ORDER         = i.orden,
                            ContentType   = eu.idstatus.ToString()
                        };
                        _equipamentImagesBusiness.InsertImageEquipament(equipamentImages);
                    }
                }
            }
            //}
            return(1);

            /* });
             * return result;*/
        }
        public override async Task <WopiResponse> GetFile(GetFileRequest getFileRequest)
        {
            // Lookup the file in the database
            var itemId   = new Guid(getFileRequest.ResourceId);
            var wopiFile = DocumentDBRepository <DetailedFileModel> .GetItem("Files", file => file.id == itemId);

            // Check for null file
            if (wopiFile != null)
            {
                // Get discovery information
                var fileExt = wopiFile.BaseFileName.Substring(wopiFile.BaseFileName.LastIndexOf('.') + 1).ToLower();
                var actions = await WopiDiscovery.GetActions();

                // Augments the file with additional properties CloseUrl, HostViewUrl, HostEditUrl
                wopiFile.CloseUrl = String.Format("https://{0}", getFileRequest.RequestUri.Authority);
                var view = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "view");
                if (view != null)
                {
                    wopiFile.HostViewUrl = WopiDiscovery.GetActionUrl(view, wopiFile.id.ToString(), getFileRequest.RequestUri.Authority);
                }
                var edit = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "edit");
                if (edit != null)
                {
                    wopiFile.HostEditUrl = WopiDiscovery.GetActionUrl(edit, wopiFile.id.ToString(), getFileRequest.RequestUri.Authority);
                }

                // Get the user from the token (token is already validated)
                wopiFile.UserId = WopiSecurity.GetUserFromToken(getFileRequest.AccessToken);

                // Call the appropriate handler for the WOPI request we received
                // Get the file from blob storage
                var bytes = await AzureStorageUtil.GetFile(wopiFile.id.ToString(), wopiFile.Container);

                // Write the response and return success 200
                return(getFileRequest.ResponseOK(new ByteArrayContent(bytes)));
            }
            else
            {
                return(getFileRequest.ResponseNotFound());
            }
        }
Esempio n. 10
0
        protected override async Task <SessionAllocateInfoContract> CreateAndSubmitSessionJob(
            SessionStartInfoContract startInfo,
            string endpointPrefix,
            bool durable,
            string callId,
            SecureString securePassword,
            ServiceRegistration registration,
            SessionAllocateInfoContract sessionAllocateInfo,
            string traceSwitchValue,
            string serviceName,
            BrokerConfigurations brokerConfigurations,
            string hostpath)
        {
            try
            {
                bool brokerPerfMode = true; // TODO: implement separated broker mode
                if (brokerPerfMode)
                {
                    TraceHelper.TraceEvent(TraceEventType.Information, "[AzureBatchSessionLauncher] .CreateAndSubmitSessionJob: broker perf mode");
                }

                TraceHelper.TraceEvent(
                    TraceEventType.Information,
                    "[AzureBatchSessionLauncher] .CreateAndSubmitSessionJob: callId={0}, endpointPrefix={1}, durable={2}.",
                    callId,
                    endpointPrefix,
                    durable);
                using (var batchClient = AzureBatchConfiguration.GetBatchClient())
                {
                    var pool = await batchClient.PoolOperations.GetPoolAsync(AzureBatchConfiguration.BatchPoolName);

                    ODATADetailLevel detailLevel = new ODATADetailLevel();
                    detailLevel.SelectClause = "affinityId, ipAddress";
                    //detailLevel.FilterClause = @"state eq 'idle'";
                    var nodes = await pool.ListComputeNodes(detailLevel).ToListAsync();

                    if (nodes.Count < 1)
                    {
                        throw new InvalidOperationException("Compute node count in selected pool is less then 1.");
                    }

                    sessionAllocateInfo.Id = string.Empty;

                    // sessionAllocateInfo.BrokerLauncherEpr = new[] { SessionInternalConstants.BrokerConnectionStringToken };
                    IList <EnvironmentSetting> ConstructEnvironmentVariable()
                    {
                        List <EnvironmentSetting> env = new List <EnvironmentSetting>(); // Can change to set to ensure no unintended overwrite

                        foreach (NameValueConfigurationElement entry in registration.Service.EnvironmentVariables)
                        {
                            env.Add(new EnvironmentSetting(entry.Name, entry.Value));
                        }

                        // pass service serviceInitializationTimeout as job environment variables
                        env.Add(new EnvironmentSetting(Constant.ServiceInitializationTimeoutEnvVar, registration.Service.ServiceInitializationTimeout.ToString()));

                        if (startInfo.ServiceHostIdleTimeout == null)
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceHostIdleTimeoutEnvVar, registration.Service.ServiceHostIdleTimeout.ToString()));
                        }
                        else
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceHostIdleTimeoutEnvVar, startInfo.ServiceHostIdleTimeout.ToString()));
                        }

                        if (startInfo.ServiceHangTimeout == null)
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceHangTimeoutEnvVar, registration.Service.ServiceHangTimeout.ToString()));
                        }
                        else
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceHangTimeoutEnvVar, startInfo.ServiceHangTimeout.ToString()));
                        }

                        // pass MessageLevelPreemption switcher as job environment variables
                        env.Add(new EnvironmentSetting(Constant.EnableMessageLevelPreemptionEnvVar, registration.Service.EnableMessageLevelPreemption.ToString()));

                        // pass trace switcher to svchost
                        if (!string.IsNullOrEmpty(traceSwitchValue))
                        {
                            env.Add(new EnvironmentSetting(Constant.TraceSwitchValue, traceSwitchValue));
                        }

                        // pass taskcancelgraceperiod as environment variable to svchosts
                        env.Add(new EnvironmentSetting(Constant.CancelTaskGracePeriodEnvVar, Constant.DefaultCancelTaskGracePeriod.ToString()));

                        // pass service config file name to services
                        env.Add(new EnvironmentSetting(Constant.ServiceConfigFileNameEnvVar, serviceName));

                        // pass maxMessageSize to service hosts
                        int maxMessageSize = startInfo.MaxMessageSize.HasValue ? startInfo.MaxMessageSize.Value : registration.Service.MaxMessageSize;

                        env.Add(new EnvironmentSetting(Constant.ServiceConfigMaxMessageEnvVar, maxMessageSize.ToString()));

                        // pass service operation timeout to service hosts
                        int?serviceOperationTimeout = null;

                        if (startInfo.ServiceOperationTimeout.HasValue)
                        {
                            serviceOperationTimeout = startInfo.ServiceOperationTimeout;
                        }
                        else if (brokerConfigurations != null && brokerConfigurations.LoadBalancing != null)
                        {
                            serviceOperationTimeout = brokerConfigurations.LoadBalancing.ServiceOperationTimeout;
                        }

                        if (serviceOperationTimeout.HasValue)
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceConfigServiceOperatonTimeoutEnvVar, serviceOperationTimeout.Value.ToString()));
                        }

                        if (startInfo.Environments != null)
                        {
                            foreach (KeyValuePair <string, string> entry in startInfo.Environments)
                            {
                                env.Add(new EnvironmentSetting(entry.Key, entry.Value));
                            }
                        }

                        // Each SOA job is assigned a GUID "secret", which is used
                        // to identify soa job owner. When a job running in Azure
                        // tries to access common data, it sends this "secret" together
                        // with a data request to data service.  Data service trusts
                        // the data request only if the job id and job "secret"
                        // match.
                        env.Add(new EnvironmentSetting(Constant.JobSecretEnvVar, Guid.NewGuid().ToString()));

                        // Set CCP_SERVICE_SESSIONPOOL env var of the job
                        if (startInfo.UseSessionPool)
                        {
                            env.Add(new EnvironmentSetting(Constant.ServiceUseSessionPoolEnvVar, bool.TrueString));
                        }

                        void SetBrokerNodeAuthenticationInfo()
                        {
                            // TODO: set the information needed by compute node to authenticate broker node
                            return;
                        }

                        SetBrokerNodeAuthenticationInfo();

                        env.Add(new EnvironmentSetting(BrokerSettingsConstants.Secure, startInfo.Secure.ToString()));
                        env.Add(new EnvironmentSetting(BrokerSettingsConstants.TransportScheme, startInfo.TransportScheme.ToString()));

                        TraceHelper.TraceEvent(
                            TraceEventType.Information,
                            "[AzureBatchSessionLauncher] .CreateAndSubmitSessionJob: callId={0}, set job environment: {1}={2}, {3}={4}.",
                            callId,
                            BrokerSettingsConstants.Secure,
                            startInfo.Secure,
                            BrokerSettingsConstants.TransportScheme,
                            startInfo.TransportScheme);

                        env.Add(new EnvironmentSetting(TelepathyConstants.SchedulerEnvironmentVariableName, Dns.GetHostName()));
                        env.Add(new EnvironmentSetting(Constant.OverrideProcNumEnvVar, "TRUE"));

                        //Establish a link via ev between TELEPATHY_SERVICE_WORKING_DIR and AZ_BATCH_JOB_PREP_WORKING_DIR
                        env.Add(new EnvironmentSetting(TelepathyConstants.ServiceWorkingDirEnvVar, AzureBatchPrepJobWorkingDir));
                        return(env);
                    }
                    var environment = ConstructEnvironmentVariable();

                    ResourceFile GetResourceFileReference(string containerName, string blobPrefix)
                    {
                        var          sasToken = AzureStorageUtil.ConstructContainerSas(this.cloudStorageAccount, containerName, SharedAccessBlobPermissions.List | SharedAccessBlobPermissions.Read);
                        ResourceFile rf;

                        if (string.IsNullOrEmpty(blobPrefix))
                        {
                            rf = ResourceFile.FromStorageContainerUrl(sasToken);
                        }
                        else
                        {
                            rf = ResourceFile.FromStorageContainerUrl(sasToken, blobPrefix: blobPrefix);
                        }

                        return(rf);
                    }

                    async Task <string> CreateJobAsync()
                    {
                        //TODO: need a function to test if all parameters are legal.
                        if (startInfo.MaxUnits != null && startInfo.MaxUnits <= 0)
                        {
                            throw new ArgumentException("Maxunit value is invalid.");
                        }
                        string newJobId = AzureBatchSessionJobIdConverter.ConvertToAzureBatchJobId(AzureBatchSessionIdGenerator.GenerateSessionId());

                        Debug.Assert(batchClient != null, nameof(batchClient) + " != null");
                        var job = batchClient.JobOperations.CreateJob(newJobId, new PoolInformation()
                        {
                            PoolId = AzureBatchConfiguration.BatchPoolName
                        });

                        job.JobPreparationTask = new JobPreparationTask(JobPrepCmdLine);
                        job.JobPreparationTask.UserIdentity  = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task));
                        job.JobPreparationTask.ResourceFiles = new List <ResourceFile>()
                        {
                            GetResourceFileReference(ServiceRegistrationContainer, null),
                            GetResourceFileReference(RuntimeContainer, CcpServiceHostFolder),
                            GetResourceFileReference(ServiceAssemblyContainer, startInfo.ServiceName.ToLower())
                        };

                        job.JobReleaseTask = new JobReleaseTask(JobReleaseCmdLine);
                        job.JobReleaseTask.UserIdentity = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task));

                        // List<ResourceFile> resourceFiles = new List<ResourceFile>();
                        // resourceFiles.Add(GetResourceFileReference(RuntimeContainer, BrokerFolder));
                        // resourceFiles.Add(GetResourceFileReference(ServiceRegistrationContainer, null));

                        // // job.JobManagerTask = new JobManagerTask("Broker",
                        // // $@"cmd /c {AzureBatchTaskWorkingDirEnvVar}\broker\HpcBroker.exe -d --ServiceRegistrationPath {AzureBatchTaskWorkingDirEnvVar} --AzureStorageConnectionString {AzureBatchConfiguration.SoaBrokerStorageConnectionString} --EnableAzureStorageQueueEndpoint True --SvcHostList {string.Join(",", nodes.Select(n => n.IPAddress))}");
                        // job.JobManagerTask = new JobManagerTask("List",
                        // $@"cmd /c dir & set");
                        // job.JobManagerTask.ResourceFiles = resourceFiles;
                        // job.JobManagerTask.UserIdentity = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Task));

                        // Set Meta Data
                        if (job.Metadata == null)
                        {
                            job.Metadata = new List <MetadataItem>();
                        }

                        Dictionary <string, string> jobMetadata = new Dictionary <string, string>()
                        {
                            { BrokerSettingsConstants.ShareSession, startInfo.ShareSession.ToString() },
                            { BrokerSettingsConstants.Secure, startInfo.Secure.ToString() },
                            { BrokerSettingsConstants.TransportScheme, ((int)startInfo.TransportScheme).ToString() },
                            { BrokerSettingsConstants.UseAzureQueue, (startInfo.UseAzureQueue == true).ToString() },
                        };

                        if (startInfo.ServiceVersion != null)
                        {
                            jobMetadata.Add(BrokerSettingsConstants.ServiceVersion, startInfo.ServiceVersion?.ToString());
                        }

                        if (startInfo.MaxUnits != null)
                        {
                            jobMetadata.Add("MaxUnits", startInfo.MaxUnits.ToString());
                        }

                        Dictionary <string, int?> jobOptionalMetadata = new Dictionary <string, int?>()
                        {
                            { BrokerSettingsConstants.ClientIdleTimeout, startInfo.ClientIdleTimeout },
                            { BrokerSettingsConstants.SessionIdleTimeout, startInfo.SessionIdleTimeout },
                            { BrokerSettingsConstants.MessagesThrottleStartThreshold, startInfo.MessagesThrottleStartThreshold },
                            { BrokerSettingsConstants.MessagesThrottleStopThreshold, startInfo.MessagesThrottleStopThreshold },
                            { BrokerSettingsConstants.ClientConnectionTimeout, startInfo.ClientConnectionTimeout },
                            { BrokerSettingsConstants.ServiceConfigMaxMessageSize, startInfo.MaxMessageSize },
                            { BrokerSettingsConstants.ServiceConfigOperationTimeout, startInfo.ServiceOperationTimeout },
                            { BrokerSettingsConstants.DispatcherCapacityInGrowShrink, startInfo.DispatcherCapacityInGrowShrink }
                        };

                        job.Metadata = job.Metadata.Concat(jobMetadata.Select(p => new MetadataItem(p.Key, p.Value)))
                                       .Concat(jobOptionalMetadata.Where(p => p.Value.HasValue).Select(p => new MetadataItem(p.Key, p.Value.ToString()))).ToList();

                        job.DisplayName = $"{job.Id} - {startInfo.ServiceName} - WCF Service";
                        await job.CommitAsync();

                        return(job.Id);
                    }

                    var jobId = await CreateJobAsync();

                    string sessionId = AzureBatchSessionJobIdConverter.ConvertToSessionId(jobId);
                    if (!sessionId.Equals("-1"))
                    {
                        sessionAllocateInfo.Id = sessionId;
                    }
                    else
                    {
                        TraceHelper.TraceEvent(TraceEventType.Error, "[AzureBatchSessionLauncher] .CreateAndSubmitSessionJob: JobId was failed to parse. callId={0}, jobId={1}.", callId, jobId);
                    }

                    Task AddTasksAsync()
                    {
                        int numTasks = startInfo.MaxUnits != null ? (int)startInfo.MaxUnits : nodes.Count;

                        var comparer = new EnvironmentSettingComparer();

                        CloudTask CreateTask(string taskId)
                        {
                            CloudTask cloudTask = new CloudTask(taskId, $@"cmd /c %{TelepathyConstants.ServiceWorkingDirEnvVar}%\ccpservicehost\CcpServiceHost.exe -standalone");

                            cloudTask.UserIdentity        = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Pool));
                            cloudTask.EnvironmentSettings = cloudTask.EnvironmentSettings == null ? environment : environment.Union(cloudTask.EnvironmentSettings, comparer).ToList();
                            return(cloudTask);
                        }

                        CloudTask CreateBrokerTask(bool direct)
                        {
                            List <ResourceFile> resourceFiles = new List <ResourceFile>();

                            resourceFiles.Add(GetResourceFileReference(RuntimeContainer, BrokerFolder));

                            string cmd;

                            if (direct)
                            {
                                cmd =
                                    $@"cmd /c %{TelepathyConstants.ServiceWorkingDirEnvVar}%\broker\HpcBroker.exe -d --SvcHostList {string.Join(",", nodes.Select(n => n.IPAddress))}";
                            }
                            else
                            {
                                cmd =
                                    $@"cmd /c %{TelepathyConstants.ServiceWorkingDirEnvVar}%\broker\HpcBroker.exe -d --AzureStorageConnectionString {AzureBatchConfiguration.SoaBrokerStorageConnectionString} --EnableAzureStorageQueueEndpoint True --SvcHostList {string.Join(",", nodes.Select(n => n.IPAddress))}";
                            }

                            CloudTask cloudTask = new CloudTask("Broker", cmd);

                            cloudTask.ResourceFiles       = resourceFiles;
                            cloudTask.UserIdentity        = new UserIdentity(new AutoUserSpecification(elevationLevel: ElevationLevel.Admin, scope: AutoUserScope.Pool));
                            cloudTask.EnvironmentSettings = cloudTask.EnvironmentSettings == null ? environment : environment.Union(cloudTask.EnvironmentSettings, comparer).ToList();
                            return(cloudTask);
                        }

                        //TODO: task id type should be changed from int to string
                        var tasks = Enumerable.Range(0, numTasks - 1).Select(_ => CreateTask(Guid.NewGuid().ToString())).ToArray();

                        if (!brokerPerfMode)
                        {
                            tasks = tasks.Union(new[] { CreateBrokerTask(true) }).ToArray();
                        }
                        else
                        {
                            tasks = tasks.Union(new[] { CreateTask(Guid.NewGuid().ToString()) }).ToArray();
                        }

                        return(batchClient.JobOperations.AddTaskAsync(jobId, tasks));
                    }

                    await AddTasksAsync();

                    async Task WaitBatchBrokerLauncher()
                    {
                        var brokerTask = await batchClient.JobOperations.GetTaskAsync(jobId, "Broker");

                        TaskStateMonitor monitor = batchClient.Utilities.CreateTaskStateMonitor();
                        await monitor.WhenAll(new[] { brokerTask }, TaskState.Running, SchedulingTimeout);

                        await brokerTask.RefreshAsync();

                        var brokerNodeIp = nodes.First(n => n.AffinityId == brokerTask.ComputeNodeInformation.AffinityId).IPAddress;

                        sessionAllocateInfo.BrokerLauncherEpr = new[] { SoaHelper.GetBrokerLauncherAddress(brokerNodeIp) };
                    }

                    if (brokerPerfMode)
                    {
                        //If broker node and session launcher node is not the same node, this line should be modified.
                        sessionAllocateInfo.BrokerLauncherEpr = new[] { SoaHelper.GetBrokerLauncherAddress(Environment.MachineName) };
                    }
                    else
                    {
                        await WaitBatchBrokerLauncher();
                    }

                    return(sessionAllocateInfo);
                }
            }
            catch (Exception ex)
            {
                TraceHelper.TraceEvent(TraceEventType.Error, $"[{nameof(AzureBatchSessionLauncher)}] .{nameof(this.CreateAndSubmitSessionJob)}: Exception happens: {ex.ToString()}");
                throw;
            }
        }
        public override async Task <WopiResponse> PutFile(PutFileRequest putFileRequest)
        {
            WopiResponse wopiResponse = null;
            var          file         = DocumentDBRepository <DetailedFileModel> .GetItem("Files", i => i.id.ToString() == putFileRequest.ResourceId);

            // Check for null file
            if (file != null)
            {
                var inputStream = await putFileRequest.Content.ReadAsStreamAsync();

                // Ensure the file has a valid lock
                if (String.IsNullOrEmpty(file.LockValue))
                {
                    // If the file is 0 bytes, this is document creation
                    if (inputStream.Length == 0)
                    {
                        // Update the file in blob storage
                        var bytes = new byte[inputStream.Length];
                        inputStream.Read(bytes, 0, bytes.Length);
                        file.Size = bytes.Length;
                        await AzureStorageUtil.UploadFile(file.id.ToString(), file.Container, bytes);

                        // Update version
                        file.Version++;
                        await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), file);

                        // Return success 200
                        wopiResponse = putFileRequest.ResponseOK();
                    }
                    else
                    {
                        // File isn't locked...pass empty Lock in mismatch response
                        wopiResponse = putFileRequest.ResponseLockConflict(String.Empty, "File isn't locked");
                    }
                }
                else if (file.LockExpires != null && file.LockExpires < DateTime.Now)
                {
                    // File lock expired, so clear it out
                    file.LockValue   = null;
                    file.LockExpires = null;
                    await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), file);

                    // File isn't locked...pass empty Lock in mismatch response
                    wopiResponse = putFileRequest.ResponseLockConflict(String.Empty, "File isn't locked");
                }
                else if (putFileRequest.Lock != file.LockValue)
                {
                    // File lock mismatch...pass Lock in mismatch response
                    wopiResponse = putFileRequest.ResponseLockConflict(file.LockValue, "Lock mismatch");
                }
                else
                {
                    // Update the file in blob storage
                    var bytes = new byte[inputStream.Length];
                    inputStream.Read(bytes, 0, bytes.Length);
                    file.Size = bytes.Length;
                    await AzureStorageUtil.UploadFile(file.id.ToString(), file.Container, bytes);

                    // Update version
                    file.Version++;
                    await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), (FileModel)file);

                    // Return success 200
                    wopiResponse = putFileRequest.ResponseOK();
                }
            }
            else
            {
                wopiResponse = putFileRequest.ResponseNotFound();
            }
            return(wopiResponse);
        }
Esempio n. 12
0
        public ActionResult Subida(Ficheros model, HttpPostedFileBase fichero)
        {
            if (model.tipo == "interno")
            {
                var n = GestionarFicheros.GuardarFicheroDisco(fichero, Server);

                if (n != null)
                {
                    model.datos = n;
                    db.Ficheros.Add(model);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            else if (model.tipo == "base64")
            {
                var data = GestionarFicheros.ToBinario(fichero);
                if (data != null)
                {
                    model.datos  = Convert.ToBase64String(data);
                    model.nombre = fichero.FileName;
                    db.Ficheros.Add(model);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            else if (model.tipo == "binario")
            {
                var datab = GestionarFicheros.ToBinario(fichero);
                if (datab != null)
                {
                    model.nombre = fichero.FileName;
                    model.datosb = datab;
                    model.datos  = "";
                    db.Ficheros.Add(model);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            else if (model.tipo == "azure")
            {
                var cu = ConfigurationManager.AppSettings["AccountnameAzureStorage"];
                var cl = ConfigurationManager.AppSettings["PasswordAzureStorage"];
                var co = ConfigurationManager.AppSettings["ContainerAzureStorage"];

                var az  = new AzureStorageUtil(cu, cl, co);
                var n   = Guid.NewGuid();
                var ext = fichero.FileName.Substring(fichero.FileName.LastIndexOf("."));
                az.SubirFichero(fichero.InputStream, n + ext);
                model.datos  = n + ext;
                model.nombre = fichero.FileName;

                db.Ficheros.Add(model);
                db.SaveChanges();
            }


            return(RedirectToAction("Index"));
        }