示例#1
0
        private static void LoadDefaultUrl(string path, string notImage, TypeTable typeTable)
        {
            if (!File.Exists(path))
            {
                throw new Exception("File not found - " + path);
            }

            using var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            switch (typeTable)
            {
            case TypeTable.Certificates:
                HelperDefaulter.UrlCertificates = AzureBlobHelper.UploadFileToStorage(stream,
                                                                                      fileName: "default" + Path.GetExtension(notImage).ToLower(),
                                                                                      typeTable).GetAwaiter().GetResult();
                break;

            case TypeTable.Users:
                HelperDefaulter.UrlUsers = AzureBlobHelper.UploadFileToStorage(stream,
                                                                               fileName: "default" + Path.GetExtension(notImage).ToLower(),
                                                                               typeTable).GetAwaiter().GetResult();
                break;

            case TypeTable.Events:
                HelperDefaulter.UrlEvents = AzureBlobHelper.UploadFileToStorage(stream,
                                                                                fileName: "default" + Path.GetExtension(notImage).ToLower(),
                                                                                typeTable).GetAwaiter().GetResult();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(typeTable), typeTable, null);
            }
        }
示例#2
0
        public static async Task LoadCertificates(IEnumerable <O2CCertificate> list)
        {
            foreach (var item in list)
            {
                var filename  = item.Serial + item.Number;
                var pathPhoto = "Files/PFR_Photos/" + filename + ".jpg";
                if (!File.Exists(pathPhoto))
                {
                    continue;
                }

                var photo = new O2CPhoto
                {
                    FileName = filename.ToUpper().ToString() + '_' + DateTime.Now.ConvertToUnixTime() +
                               Path.GetExtension(pathPhoto).ToLower()
                };
                using (var stream = new FileStream(pathPhoto, FileMode.Open, FileAccess.Read))
                {
                    photo.Url = AzureBlobHelper.UploadFileToStorage(stream,
                                                                    fileName: photo.FileName,
                                                                    TypeTable.Certificates).GetAwaiter().GetResult();
                    photo.IsMain = true;
                    item.Photos.Add(photo);
                }
            }
        }
示例#3
0
        /// <summary>
        /// 查看Blob已上传文件的目录
        /// </summary>
        /// <returns></returns>
        public ActionResult GetBlobList()
        {
            string containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
            var    container     = AzureBlobHelper.GetContainer(containername);

            StringBuilder sb = new StringBuilder();

            // Loop over items within the container and output the length and URI.
            foreach (IListBlobItem item in container.ListBlobs(null, false))
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;

                    sb = sb.AppendFormat("Block blob of length {0}: {1}\n", blob.Properties.Length, blob.Uri);
                }
                else if (item.GetType() == typeof(CloudPageBlob))
                {
                    CloudPageBlob pageBlob = (CloudPageBlob)item;

                    sb = sb.AppendFormat("Page blob of length {0}: {1}\n", pageBlob.Properties.Length, pageBlob.Uri);
                }
                else if (item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory directory = (CloudBlobDirectory)item;

                    sb = sb.AppendFormat("Directory: {0}\n", directory.Uri);
                }
            }

            return(Content(sb.ToString()));
        }
示例#4
0
        private async Task <BlobContainerClient> GetClient()
        {
            var containerName = _configuration["output:azureBlob:container"];
            var client        = AzureBlobHelper.GetClient(_configuration, "output:azureBlob", containerName);
            var container     = client.CreateIfNotExists().Value;

            return(client);
        }
示例#5
0
 public AdminController()
 {
     db  = new dbOperation();
     vm  = new StartUpViewModel();
     Cvm = new ContactVM();
     AB  = new AzureBlobHelper();
     pfm = new postedFileModel();
     ws  = new Webshop();
 }
示例#6
0
 public HomeController()
 {
     db  = new dbOperation();
     vm  = new StartUpViewModel();
     Cvm = new ContactVM();
     AB  = new AzureBlobHelper();
     pfm = new postedFileModel();
     ES  = new EmailService();
 }
 public void TestCleanup()
 {
     var helper = new AzureBlobHelper(Account, ContainerName);
     var blobsToDelete = helper.GetBlobItemsByDirectory(ContainerName);
     foreach (var blob in blobsToDelete)
     {
         var b = blob as CloudBlockBlob;
         b.DeleteIfExists();
     }
 }
        private static CloudBlobContainer GetContainer()
        {
            var storageConnection = ConfigurationManager.ConnectionStrings["AzureTableStorage"].ConnectionString;
            var storageAccount    = CloudStorageAccount.Parse(storageConnection);
            var blobClient        = storageAccount.CreateCloudBlobClient();

            var azureBlobHelper = new AzureBlobHelper(blobClient);

            return(azureBlobHelper.GetContainerFor("ReadModels"));
        }
        public void BlobHelperAddOrCreateBlobShouldSucceed()
        {
            var stream = Serializer.SerializeToByteArray(TestString);
            var helper = new AzureBlobHelper(Account, ContainerName);
            helper.CreateOrUpdate(BlobId, stream);
            stream.Close();

            var createdSuccessfully = helper.Exists(BlobId);
            createdSuccessfully.Should().BeTrue("The blob failed to be created or uploaded");
        }
示例#10
0
文件: Startup.cs 项目: zsybupt/Perf
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ThreadPool.SetMinThreads(128, 128);
            ServicePointManager.DefaultConnectionLimit = 128;

            string          azureStorageConnectionString = Configuration["AzureStorageConnectionString"];
            AzureBlobHelper azureBlobHelper = new AzureBlobHelper(azureStorageConnectionString);

            services.AddSingleton <AzureBlobHelper>(azureBlobHelper);
            services.AddControllers();
        }
 public MetaFileLinksController(
     ILogger <MetaFileLinksController> logger,
     IMapper mapper,
     IMetaFileLinkRepository metaFileLinkRepository,
     IUnitOfWork unitOfWork,
     AzureBlobHelper blobHelper)
 {
     _logger = logger;
     _mapper = mapper;
     _metaFileLinkRepository = metaFileLinkRepository;
     _unitOfWork             = unitOfWork;
     _blobHelper             = blobHelper;
 }
        public void BlobHelperDeleteBlobShouldSucceed()
        {
            var serializedKey = Serializer.SerializeToByteArray(TestString);
            var helper = new AzureBlobHelper(Account, ContainerName);
            helper.CreateOrUpdate(BlobId, serializedKey);

            var createdSuccessfully = helper.Exists(BlobId);
            createdSuccessfully.Should().BeTrue("The create or upload operation failed");

            helper.Delete(BlobId);

            var blobDoesExist = helper.Exists(BlobId);
            blobDoesExist.Should().BeFalse("The delete operation failed");
        }
        private async Task <Guid> CreateNewScenarioAsync()
        {
            CloudBlobContainer formRecognizerCloudContainer = null;

            try
            {
                ScenarioSetupState = FormRecognizerScenarioSetupState.Running;

                // create cloud storage container and upload local files
                formRecognizerCloudContainer = AzureBlobHelper.GetCloudBlobContainer(StorageAccount, StorageKey, Guid.NewGuid().ToString());
                await AzureBlobHelper.UploadStorageFilesToContainerAsync(LocalFileCollection, formRecognizerCloudContainer);

                string containerFullSASUrl = AzureBlobHelper.GetContainerSasToken(formRecognizerCloudContainer, sharedAccessStartTimeInMinutes: 5, sharedAccessExpiryTimeInMinutes: 5);

                // create and train the custom model
                Guid modelId = await this.formRecognizerService.TrainCustomModelAsync(containerFullSASUrl);

                ModelResultResponse model = await this.formRecognizerService.GetCustomModelAsync(modelId);

                // check creation status
                string status = (model?.ModelInfo?.Status ?? string.Empty).ToLower();
                switch (status)
                {
                case "created":
                case "ready":
                    ScenarioSetupState = FormRecognizerScenarioSetupState.Completed;
                    return(modelId);

                case "invalid":
                default:
                    ScenarioSetupState = FormRecognizerScenarioSetupState.Error;
                    break;
                }
            }
            catch (Exception ex)
            {
                ScenarioCreationErrorDetails = ex.Message;
                ScenarioSetupState           = FormRecognizerScenarioSetupState.Error;
            }
            finally
            {
                if (formRecognizerCloudContainer != null)
                {
                    await formRecognizerCloudContainer.DeleteIfExistsAsync();
                }
            }

            return(Guid.Empty);
        }
示例#14
0
 public ContractController(
     IMediator mediator,
     ApplicationDbContext dbContext,
     AzureBlobHelper azureBlobHelper,
     AzureBlobSavingService azureBlobSavingService,
     IConfiguration configuration,
     UserManager <ApplicationUser> userManager)
 {
     _mediator               = mediator;
     _dbContext              = dbContext;
     _azureBlobHelper        = azureBlobHelper;
     _azureBlobSavingService = azureBlobSavingService;
     _configuration          = configuration;
     _userManager            = userManager;
 }
        public IEnumerable <FileItem> getFiles()
        {
            CloudBlobContainer container = AzureBlobHelper.GetWebApiContainer();

            foreach (CloudBlockBlob blob in container.ListBlobs())
            {
                yield return(new FileItem
                {
                    Name = blob.Name,
                    SizeInMB = string.Format("{0:f2}MB", blob.Properties.Length / (1024.0 * 1024.0)),
                    ContentType = blob.Properties.ContentType,
                    Path = blob.Uri.AbsoluteUri
                });
            }
        }
示例#16
0
        private static async Task <O2EvPhoto> PreparePhoto(O2EvEvent existEvent,
                                                           O2EvEventPhotoDto o2EvEventPhotoDto = null)
        {
            const string notImage = "not_image.jpg";
            const string path     = "Files/" + notImage;

            var o2EvPhoto = new O2EvPhoto();

            //load default photo
            if (o2EvEventPhotoDto == null)
            {
                if (!System.IO.File.Exists(path))
                {
                    throw new Exception("File not found - " + path);
                }

                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    o2EvPhoto.FileName = existEvent.Id.ToString() + '_' + DateTime.Now.ConvertToUnixTime() +
                                         Path.GetExtension(notImage).ToLower();
                    o2EvPhoto.Url = await AzureBlobHelper.UploadFileToStorage(stream,
                                                                              fileName : o2EvPhoto.FileName,
                                                                              TypeTable.Events);

                    o2EvPhoto.IsMain = true;

                    return(o2EvPhoto);
                }
            }

            //prepare file
            var file = o2EvEventPhotoDto.File;

            if (file.Length > 0)
            {
                using (Stream stream = file.OpenReadStream())
                {
                    o2EvPhoto.Url = await AzureBlobHelper.UploadFileToStorage(stream,
                                                                              existEvent.Id.ToString() + '_' + DateTime.Now.ConvertToUnixTime() +
                                                                              Path.GetExtension(notImage).ToLower(),
                                                                              TypeTable.Events);

                    return(o2EvPhoto);
                }
            }

            throw new Exception("File is empty");
        }
示例#17
0
        public void Setup()
        {
            var services = new ServiceCollection();

            ConfigureServices(services);

            var serviceProvider = services.BuildServiceProvider();

            petRepository        = serviceProvider.GetService <IPetRepository>();
            petHandler           = serviceProvider.GetService <IPetHandler>();
            unitOfWork           = serviceProvider.GetService <IUnitOfWork>();
            traitRepository      = serviceProvider.GetService <ITraitRepository>();
            cityRepository       = serviceProvider.GetService <ICityRepository>();
            animalTypeRepository = serviceProvider.GetService <IAnimalTypeRepository>();
            userRepository       = serviceProvider.GetService <IUserRepository>();

            _azureBlobHelper = new AzureBlobHelper(new Common.ImageHelper());
        }
        public async Task <List <TClass> > AddRangeAsync(List <TClass> listEntities, bool cleanData)
        {
            if (cleanData)
            {
                var all = await GetAllAsync();

                foreach (var getEntity in all)
                {
                    if (getEntity.Photos != null && getEntity.Photos.Any())
                    {
                        foreach (var photo in getEntity.Photos)
                        {
                            AzureBlobHelper.DeletePhoto(photo.FileName, TypeTable.Certificates);
                            DataContext.Entry(photo).State = EntityState.Deleted;
                        }
                    }

                    if (getEntity.Contacts != null && getEntity.Contacts.Any())
                    {
                        foreach (var contact in getEntity.Contacts)
                        {
                            DataContext.Entry(contact).State = EntityState.Deleted;
                        }
                    }

                    if (getEntity.Locations != null && getEntity.Locations.Any())
                    {
                        foreach (var location in getEntity.Locations)
                        {
                            DataContext.Entry(location).State = EntityState.Deleted;
                        }
                    }


                    // DataContext.Entry(getEntity).Collection("Locations").Load();
                    // DataContext.Entry(getEntity).Collection("Photos").Load();
                    // DataContext.Entry(getEntity).Collection("Contacts").Load();
                    DataContext.Entry(getEntity).State = EntityState.Deleted;
                }
            }

            DataContext.SaveChanges();
            return(await base.AddRangeAsync(listEntities));
        }
示例#19
0
        /// <summary>
        /// 查看BlobFile内容
        /// </summary>
        /// <param name="blobName"></param>
        /// <returns></returns>
        public ActionResult ViewBlob(string blobName)
        {
            if (blobName == "")
            {
                return(Content("无内容"));
            }

            ViewBag.FileUrl = AzureBlobHelper.GetSAS(blobName);
            //ViewBag.FileType = blobName.Split('.').LastOrDefault().ToLower() == "pdf" ? "pdf": "img";

            return(View());
            //可以下载文本形式
            //string text;
            //using (var memoryStream = new MemoryStream())
            //{
            //    blockBlob2.DownloadToStream(memoryStream);
            //    text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            //}
        }
        public Task <List <FileItem> > uploadFile()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var multipartStreamProvider = new AzureBlobStorageMultipartProvider(AzureBlobHelper.GetWebApiContainer());

            return(Request.Content.ReadAsMultipartAsync <AzureBlobStorageMultipartProvider>(multipartStreamProvider).ContinueWith <List <FileItem> >(t =>
            {
                if (t.IsFaulted)
                {
                    throw t.Exception;
                }

                AzureBlobStorageMultipartProvider provider = t.Result;
                return provider.Files;
            }));
        }
示例#21
0
        //public void WriteLog(Logs _logs)
        //{
        //    filePath = GetPath("aPathJsonLocal", 1);
        //    var str = File.ReadAllText(filePath);
        //    var configs = JsonSerializer.Deserialize<AppJson>(str);
        //    configs.Logs = _logs;
        //    File.WriteAllText(filePath, JsonSerializer.Serialize(configs));
        //}

        public async Task <List <SizeFile> > GetListFileFromCloud(string storageConnectionString)
        {
            var cloudFiles = new List <SizeFile>();
            var containers = await AzureBlobHelper.ListContainersAsync(storageConnectionString);

            foreach (var item in containers)
            {
                var blobContainer = GetBlobContainerV2(item.Name, storageConnectionString).GetBlobsAsync();
                await foreach (var blobItem in blobContainer)
                {
                    var fsi = new SizeFile
                    {
                        Lenght = blobItem.Properties.ContentLength
                    };
                    cloudFiles.Add(fsi);
                }
            }

            return(cloudFiles);
        }
        /// <summary>
        /// Identifies person from temporary image taken from App
        /// </summary>
        /// <returns>Name of identified person</returns>
        public async Task <string> Identify(string name)
        {
            var    azureBlobHelper = new AzureBlobHelper();
            string takenImageUri   = null;

            takenImageUri = azureBlobHelper.GetImageUri(name);
            if (takenImageUri == null)
            {
                throw new ManagerException(RecognitionErrorMessages.WrongUriError);
            }

            var memoryStream = new MemoryStream();

            memoryStream = RecUtil.GetStreamFromUri(takenImageUri);

            var faces = await _faceServiceClient.DetectAsync(memoryStream);

            if (faces.Length == 0 || faces == null)
            {
                throw new ManagerException(RecognitionErrorMessages.NoFacesFoundError);
            }

            var faceIds = faces.Select(face => face.FaceId).ToArray();

            var results = await _faceServiceClient.IdentifyAsync(_groupId, faceIds);

            if (results.Length == 0 || results == null || results[0].Candidates.Length == 0 || results[0].Candidates[0] == null)
            {
                throw new ManagerException(RecognitionErrorMessages.NoOneIdentifiedError);
            }

            var candidateId = results[0].Candidates[0].PersonId;
            var person      = await _faceServiceClient.GetPersonAsync(_groupId, candidateId);

            azureBlobHelper.DeletePhoto(name);

            return(person.Name);
        }
示例#23
0
        /// <summary>
        /// 删除blobFile
        /// </summary>
        /// <param name="drawingBlobId"></param>
        /// <returns></returns>
        public ActionResult DeleteBlob(int drawingBlobId)
        {
            var drawingFile = _fileVersionService.Get(f => f.Id == drawingBlobId);

            if (drawingFile == null)
            {
                return(Json(new
                {
                    result = false,
                    errmsg = "文件未找到"
                }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                string         containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
                var            container     = AzureBlobHelper.GetContainer(containername);
                CloudBlockBlob blockBlob     = container.GetBlockBlobReference(drawingFile.BIMFileId);

                // Delete the blob.
                blockBlob.Delete();
                _fileVersionService.Delete(drawingFile);

                return(Json(new
                {
                    result = true,
                    errmsg = "已删除"
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    result = true,
                    errmsg = $"已删除,无需再删除:{ex.Message}"
                }, JsonRequestBehavior.AllowGet));
            }
        }
示例#24
0
 public ParserBase(AzureBlobHelper azureBlobHelper)
 {
     _azureBlobHelper = azureBlobHelper;
 }
        public void BlobHelperGetShouldReturnTheCorrectObject()
        {
            var serializedKey = Serializer.SerializeToByteArray(TestString);
            var helper = new AzureBlobHelper(Account, ContainerName);
            helper.CreateOrUpdate(BlobId, serializedKey);

            var createdSuccessfully = helper.Exists(BlobId);
            createdSuccessfully.Should().BeTrue("The create or upload operation failed");

            var stream = helper.Get(BlobId);
            stream.Should().NotBeNull("Failed to get memory stream from blob");

            var deserializedObject = Serializer.DeserializeFromStream(stream);
            deserializedObject.Should().NotBeNull("Object was created successfully");
            
            TestString.ShouldBeEquivalentTo(deserializedObject);
        }
 public void BlobHelperExistsShouldReturnFalseForInexistentBlob()
 {
     var helper = new AzureBlobHelper(Account, ContainerName);
     var blobExists = helper.Exists("RandomId");
     blobExists.Should().BeFalse("No blob with RandomId should exist");
 }
示例#27
0
 public RlaParser(AzureBlobHelper azureBlobHelper) : base(azureBlobHelper)
 {
 }
 public HomeController(ILogger<HomeController> logger, AzureBlobHelper azureBlobHelper)
 {
     _logger = logger;
     this.azureBlobHelper = azureBlobHelper;
 }
 public void BlobHelperInitializationShouldSucceed()
 {
     var helper = new AzureBlobHelper(Account, ContainerName);
     helper.Should().NotBeNull("Initialization has failed");
 }
示例#30
0
 // GET: Gallery
 public GalleryController()
 {
     AB  = new AzureBlobHelper();
     gvm = new GalleryViewModel();
     pfm = new postedFileModel();
 }
 public static void TearDown()
 {
     var helper = new AzureBlobHelper(Account, ContainerName);
     helper.DeleteBlobContainer(ContainerName);
 }
示例#32
0
 public ZipStreamController(AzureBlobHelper blobHelper)
 {
     this._blobHelper = blobHelper;
 }
示例#33
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    //if (await IsAllow())
                    //{
                    var tasks = new List <Task>();

                    foreach (var folder in _options.CurrentValue.Folders)
                    {
                        if (await IsAllow(folder))
                        {
                            var t = Task.Run(async() =>
                            {
                                try
                                {
                                    var appsetting = _options.CurrentValue.AppSettings.FirstOrDefault(x => x.IdAppSetting == folder.IdAppSetting);
                                    IAzureBlobHelper _azureBlobHelper = new AzureBlobHelper(appsetting, folder);
                                    await _azureBlobHelper.Compare();
                                }
                                catch (Exception e)
                                {
                                    NLogManager.PublishException(e);
                                }
                            });

                            tasks.Add(t);

                            await Task.WhenAll(tasks);

                            //await WriteLog("LastRunTime", DateTime.Now.ToString());

                            //}
                            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                            await new MainUtility().WriteLastRunTime("appsettings", DateTime.Now.ToString(), folder);
                            //await Task.Delay( 10000, stoppingToken);
                        }
                    }
                    // sau timerRun phút sẽ chạy lại 1 lần
                }
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }
            //new TransferWorker.Utility.MainUtility().Write("appsettings", DateTime.Now.ToString());
            //new TransferWorker.Utility.MainUtility().LoadLog();
            //new TransferWorker.Utility.SendMail().kk();
            // var con = _appSettings.StorageConnectionString;
            // await _azureBlobHelper.UploadFile();


            //Authenticate and create a data factory management client
            //var context = new AuthenticationContext("https://login.windows.net/" + tenantID);
            //ClientCredential cc = new ClientCredential(applicationId, authenticationKey);
            //AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result;
            //ServiceClientCredentials cred = new TokenCredentials(result.AccessToken);
            //var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId };
        }
示例#34
0
        public ActionResult PostPicture(FormCollection form)
        {
            //向BIM上传model
            string uploadLicenceUri = "";
            var    file             = Request.Files["licencePicture"];

            //var file = Request.Files[0];
            if (file != null && file.ContentLength > 0)
            {
                string filehouzhui = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1, file.FileName.Length - file.FileName.LastIndexOf('.') - 1);
                if (filehouzhui.ToLower() == "jpg" || filehouzhui.ToLower() == "png" || filehouzhui.ToLower() == "jpeg")
                {
                    System.Guid addToTheEnd  = System.Guid.NewGuid();
                    string      fileRealName = file.FileName.Substring(0, file.FileName.LastIndexOf('.'));

                    string fileNameValue = fileRealName + addToTheEnd + "." + filehouzhui;
                    Stream uploadStream  = file.InputStream;


                    //上传至Azure

                    string containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
                    var    container     = AzureBlobHelper.GetContainer(containername);

                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileNameValue);
                    blockBlob.Properties.ContentType = "application/octet-stream";
                    blockBlob.UploadFromStream(uploadStream);

                    var fileBlobUrl = AzureBlobHelper.GetSAS(fileNameValue).Split('?').FirstOrDefault();

                    ////文件名的key和value
                    //string savePath = Server.MapPath("~/upload/BusinessLicencePicture");
                    //if (!System.IO.Directory.Exists(savePath))
                    //{
                    //    System.IO.Directory.CreateDirectory(savePath);
                    //    //加访问权限
                    //   // AddpathPower(savePath, "Users");
                    //}
                    ////防止文件名重复
                    //System.Guid addToTheEnd = System.Guid.NewGuid();
                    //string fileRealName = file.FileName.Substring(0, file.FileName.LastIndexOf('.'));

                    //string filepath = savePath + "\\" + fileRealName + addToTheEnd + "." + filehouzhui;
                    //file.SaveAs(filepath);
                    uploadLicenceUri = fileBlobUrl;
                    return(Json(new
                    {
                        Result = true,
                        Message = uploadLicenceUri
                    }));
                }
                else
                {
                    return(Json(new
                    {
                        Result = false,
                        Message = "请上传正确格式的图片文件!"
                    }));
                }
            }
            else
            {
                return(Json(new
                {
                    Result = false,
                    Message = "请上传jpg或jpeg格式的图片!"
                }));

                //InfoAllRight = false;
                //backMessage = backMessage + "上传图片有误/n";
            }
        }
示例#35
0
        /// <summary>
        /// Write a data item into data container and flush
        /// </summary>
        /// <param name="data">data content to be written</param>
        public void AddDataAndFlush(DataContent data)
        {
            TraceHelper.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "[BlobDataContainer] .AddDataAndFlush");

            using (MemoryStream ms = new MemoryStream())
            {
                // dump all data into a memory stream
                data.Dump(ms);

                // create timer that updates "CommonDataLastUpdateTime" metadata peoriodically
                Timer updateMetadataTimer = new Timer(
                    this.MarkBlobAsBeingUploaded,
                    null,
                    TimeSpan.FromMilliseconds(Constant.LastUpdateTimeUpdateIntervalInMilliseconds),
                    TimeSpan.FromMilliseconds(Constant.LastUpdateTimeUpdateIntervalInMilliseconds));

                // write data
                Exception transferException = null;
                try
                {
                    BlobTransferOptions transferOptions = new BlobTransferOptions
                    {
                        Concurrency = Environment.ProcessorCount * 8,
                    };

                    using (BlobTransferManager transferManager = new BlobTransferManager(transferOptions))
                    {
                        transferManager.QueueUpload(
                            this.dataBlob,
                            ms,
                            null,
                            delegate(object userData, double speed, double progress)
                        {
                            TraceHelper.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "[BlobDataContainer] .AddDataAndFlush: progress={0}%", progress);
                        },
                            delegate(object userData, Exception ex)
                        {
                            if (ex != null)
                            {
                                transferException = ex;
                            }
                        },
                            null);

                        transferManager.WaitForCompletion();
                    }
                }
                finally
                {
                    updateMetadataTimer.Dispose();
                }

                TraceHelper.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "[BlobDataContainer] .AddDataAndFlush: data transfer done");

                DataException dataException = null;
                if (transferException != null)
                {
                    dataException = TranslateTransferExceptionToDataException(transferException);
                }

                try
                {
                    int    errorCode    = DataErrorCode.Success;
                    string errorMessage = string.Empty;
                    if (dataException != null)
                    {
                        errorCode    = dataException.ErrorCode;
                        errorMessage = dataException.Message;
                    }

                    AzureBlobHelper.MarkBlobAsCompleted(this.dataBlob, errorCode.ToString(), errorMessage);
                }
                catch (StorageException ex)
                {
                    TraceHelper.TraceSource.TraceEvent(
                        TraceEventType.Error,
                        0,
                        "[BlobDataContainer] .AddDataAndFlush: failed to mark blob as completed. blob url={0}. error code={1}, exception={2}",
                        this.dataBlob.Uri.AbsoluteUri,
                        BurstUtility.GetStorageErrorCode(ex),
                        ex);
                }
                catch (Exception ex)
                {
                    TraceHelper.TraceSource.TraceEvent(
                        TraceEventType.Error,
                        0,
                        "[BlobDataContainer] .AddDataAndFlush: failed to mark blob as completed. blob url={0}. Exception={1}",
                        this.dataBlob.Uri.AbsoluteUri,
                        ex);
                }

                if (dataException != null)
                {
                    throw dataException;
                }
            }
        }
示例#36
0
 public JspcaParser(AzureBlobHelper azureBlobHelper) : base(azureBlobHelper)
 {
 }
示例#37
0
 public RehovotSpaParser(AzureBlobHelper azureBlobHelper) : base(azureBlobHelper)
 {
 }