public async Task CtorWhenPermissionIsOutOfRangeNumberThenPermissionIsBlob()
        {
            // ARRANGE
            var client    = CloudStorageAccount.Parse(DefaultConnectionString).CreateCloudBlobClient();
            var container = client.GetContainerReference(DefaultContainerName);

            await container.DeleteIfExistsAsync();

            var configuration = new MediaStorageConfiguration
            {
                ConnectionString = DefaultConnectionString,
                Container        = DefaultContainerName,
                Permission       = "100",
            };

            // ACT
            _ = new AzureBlob(configuration);

            // ASSERT
            container = client.GetContainerReference(DefaultContainerName);

            Assert.True(await container.ExistsAsync());

            var blobContainerPermissions = await container.GetPermissionsAsync();

            Assert.Equal(BlobContainerPublicAccessType.Blob, blobContainerPermissions.PublicAccess);
        }
Esempio n. 2
0
        private async Task monthlyReport()
        {
            DBHandler    db      = new linqDBHandler();
            ExcelBuilder builder = new ExcelBuilder();
            AzureBlob    blob    = new AzureBlob();

            foreach (Company c in db.getAllCompanies())
            {
                List <string> columns = new List <string>();
                columns.Add("userName");
                columns.Add("Start Time");
                columns.Add("End Time");
                List <List <string> > rows  = new List <List <string> >();
                DateTime     monthDate      = new DateTime();
                TimeZoneInfo israelTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Israel Standard Time");
                monthDate = TimeZoneInfo.ConvertTime(monthDate, israelTimeZone);

                int year  = monthDate.Year;
                int month = monthDate.Month - 1;
                if (month == 0)
                {
                    month = 12;
                    year -= 1;
                }

                monthDate = new DateTime(year, month, 1);

                foreach (User u in db.getAllCompanyWorkers(c.id))
                {
                    long         userId = u.id;
                    List <Clock> clocks = db.getClocks(userId, monthDate);

                    foreach (Clock shift in clocks)
                    {
                        List <string> row = new List <string>();
                        row.Add(u.name);
                        row.Add(shift.startTime.ToString());
                        row.Add(shift.endTime.ToString());

                        rows.Add(row);
                    }
                }


                Workbook workBook = builder.write(columns, rows);
                workBook.SaveAs("temp.xlsx");
                string url = await blob.uploadFileAsync("temp.xlsx", c.id + "_" + monthDate + ".xlsx");

                File.Delete("temp.xlsx");

                Report report = new Report();
                report.companyId = c.id;
                report.date      = monthDate;
                report.url       = url;

                db.addReport(report);

                Trace.TraceInformation("new report : " + url);
            }
        }
Esempio n. 3
0
        public string Save(Stream filestream)
        {
            try
            {
#if AZURE
                IStorage container = new AzureBlob(Constants.AZURE_CONTAINER_IMAGES, BlobContainerPublicAccessType.Container);
                bool     ok        = container.AddBlobItem(blobname, imageUpload.InputStream);
                var      url       = filename;
#else
                SaveFile(filestream, url);
#if RACKSPACE
                new Thread(() => Img.UploadImageSizes(url)).Start();
#endif
#endif
                // get filesize
                var fileinfo = new FileInfo(GeneralConstants.APP_ROOT_DIR + url);
                size = fileinfo.Length;
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                return("");
            }
            finally
            {
                filestream.Flush();
                filestream.Close();
            }
            return(url);
        }
Esempio n. 4
0
 public AzurePackageRelatedStorageItem(AzureStorageFeed feed, PackageName packageName, AzureBlob itemBlob, RelatedPackageTable relatedPackageTable)
 {
     this.feed                = feed;
     this.packageName         = packageName;
     this.itemBlob            = itemBlob;
     this.relatedPackageTable = relatedPackageTable;
 }
        public AzureBlobTests()
        {
            Workbench.Instance.Reset();

            Workbench.Instance.AddToCache(WorkbenchServiceType.Repository, _fakeLightRepository);

            _sut = new AzureBlob(new MediaStorageConfiguration
            {
                ConnectionString = DefaultConnectionString,
                Container        = _fixture.Create <string>().ToLower(CultureInfo.CurrentCulture),
            });

            _expectedData = _fixture.Create <string>();

            _stream = ToMemoryStream(_expectedData);

            _lightAttachment = new LightAttachment
            {
                ContentType = ContentType,
                Id          = _fixture.Create <string>() + ".txt",
                MediaLink   = _fixture.Create <string>(),
                MediaStream = _stream,
                Name        = _fixture.Create <string>(),
                ResourceId  = _fixture.Create <string>(),
            };
        }
Esempio n. 6
0
        public BatchFile AddBatchFile(Guid batchId, string fileName, string mimeType, string contentSize)
        {
            Batch batch = _batchContext.Batches
                          .FirstOrDefault(p => p.BatchId.Equals(batchId));

            BatchFile batchFile = new BatchFile();

            if (batch != null)
            {
                bool fileExists = _batchContext.BatchFiles
                                  .Any(p => p.Batch.BatchId.Equals(batchId) && p.FileName.Equals(fileName));
                if (!fileExists)
                {
                    batchFile.Batch    = batch;
                    batchFile.FileName = fileName;
                    batchFile.FileType = mimeType;
                    batchFile.FileSize = contentSize;

                    _batchContext.BatchFiles.Add(batchFile);
                    _batchContext.SaveChanges();

                    AzureBlob azureBlob = new AzureBlob(_storageAccountKey, _storageAccountName, _containerName);

                    string path = System.AppDomain.CurrentDomain.BaseDirectory;
                    //azureBlob.UploadFileinBlocks(@"D:\Sums\Practice\UKHG\Batch.API\Uploads\sample.txt", fileName);
                    azureBlob.UploadFileinBlocks($"{path}/Uploads/sample.txt", fileName);
                }
            }
            return(batchFile);
        }
Esempio n. 7
0
        public async Task LoadFileTestSecureURLAsync()
        {
            MemoryStream stream = new MemoryStream();

            string fileLoc = Path.Combine(configuration["TestFolderAddress"], "LoadFile", "TestFile.txt");

            using (var file = File.OpenRead(fileLoc))
            {
                file.Position = 0;
                await file.CopyToAsync(stream);
            }

            var azureBlob = new AzureBlob();

            FileSetOptions fileSetOptions = new FileSetOptions()
            {
                FileAccess = FileAccessLevel._public, ConfigurationString = configuration["AzureStorageConnectionString"], Folder = "LoadFilePrivate", Key = "TestFile.txt", _stream = stream
            };

            var fileName = await azureBlob.SaveAsync(fileSetOptions);

            FileGetOptions fileGetOptions = new FileGetOptions()
            {
                ConfigurationString = configuration["AzureStorageConnectionString"], Folder = "LoadFilePrivate", Key = "TestFile.txt", FileTransfer = FileTransferOptions.SecureUrl, SecureLinkTimeToLive = new TimeSpan(0, 0, 5)
            };

            FileData data = await azureBlob.GetAsync(fileGetOptions);

            HttpClient webClient = new HttpClient();

            var fileData = await webClient.GetStringAsync(data.Loc);

            Assert.IsTrue(fileData.Length > 0);
        }
Esempio n. 8
0
        /// <summary>
        /// Attempts to read stored object from file system
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns>Object (or null if not exists)</returns>
        public static T GetItem <T>(string fileName, int?cacheDurationSeconds = null)
        {
            try
            {
                lock (padlock)
                {
                    int expirationSeconds = (cacheDurationSeconds != null) ? (int)cacheDurationSeconds : Config.ExpirationSeconds;

                    //will first check if blob is stale (expired), if not will download and turn
                    string res  = AzureBlob.DownloadBlob(fileName, expirationSeconds);
                    T      resp = JsonConvert.DeserializeObject <T>(res);

                    if (resp is T)
                    {
                        //we know that if we've arrive here, both mem and file cache are empty
                        //save resp in file cache (which will push into memory)
                        FileCache.AddItem(resp, fileName, cacheDurationSeconds);

                        return(resp);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(default(T));
        }
Esempio n. 9
0
        public async Task SaveFilePublicTest()
        {
            MemoryStream stream = new MemoryStream();

            string fileLoc = Path.Combine(configuration["TestFolderAddress"], "LoadFile", "TestFile.txt");

            using (var file = File.OpenRead(fileLoc))
            {
                file.Position = 0;
                await file.CopyToAsync(stream);
            }


            var azureBlob = new AzureBlob();

            FileSetOptions fileSetOptions = new FileSetOptions()
            {
                FileAccess = FileAccessLevel._public, ConfigurationString = configuration["AzureStorageConnectionString"], Folder = "SaveFilePublic", Key = "TestFile.txt", _stream = stream
            };

            var fileName = await azureBlob.SaveAsync(fileSetOptions);

            HttpClient clinet = new HttpClient();
            var        rfile  = await clinet.GetStringAsync("http://127.0.0.1:10000/devstoreaccount1/savefile/TestFile.txt");

            Assert.IsTrue(rfile.Length > 0);
        }
        public ActionResult Upload(HttpPostedFileBase file)
        {
            ClaimsPrincipal cp    = ClaimsPrincipal.Current;
            string          email = cp.Identity.Name.ToString();

            LOGGER.Info("Document upload link called by " + email + " with the filename " + file.FileName);
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    LOGGER.Info("Document upload to azure blob container started for " + email + " with the filename " + file.FileName);

                    CloudBlobContainer _azureBlob = AzureBlob.AzureBlobContainer(DocContainerName);
                    CloudBlockBlob     blockBlob  = _azureBlob.GetBlockBlobReference(file.FileName);
                    using (var fileStream = file.InputStream)
                    {
                        blockBlob.UploadFromStream(fileStream);
                    }
                    LOGGER.Info("Document upload to azure blob container completed successfully for " + email + " with the filename " + file.FileName);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    LOGGER.Error("Document uplod has failed for " + email + " with the filename " + file.FileName + "due to " + ex.Message.ToString());
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return(View("UploadDocument"));
        }
        public async Task CtorWhenContainersDoesntExistsAndAccessTypeIsAnyStringCreatesWithAccessTypeBlob(string accessType)
        {
            // ARRANGE
            var client    = CloudStorageAccount.Parse(DefaultConnectionString).CreateCloudBlobClient();
            var container = client.GetContainerReference(DefaultContainerName);

            await container.DeleteIfExistsAsync();

            var configuration = new MediaStorageConfiguration
            {
                ConnectionString = DefaultConnectionString,
                Container        = DefaultContainerName,
                Permission       = accessType,
            };

            // ACT
            _ = new AzureBlob(configuration);

            // ASSERT
            container = client.GetContainerReference(DefaultContainerName);

            Assert.True(await container.ExistsAsync());

            var blobContainerPermissions = await container.GetPermissionsAsync();

            Assert.Equal(BlobContainerPublicAccessType.Blob, blobContainerPermissions.PublicAccess);
        }
Esempio n. 12
0
        public IHttpActionResult GetBlobList()
        {
            var blob = new AzureBlob(3);

            var reply = blob.GetBlobList().Select(x => new { name = x, url = String.Format("https://storagephotog2.blob.core.windows.net/db-backup/{0}", x) });

            return(Ok(reply));
        }
Esempio n. 13
0
        public async Task TestUri()
        {
            CloudBlockBlob blob = await CreateEmptyBlob("blob");

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.AreEqual(blob.Uri.ToString(), azureBlob.Uri);
        }
Esempio n. 14
0
        public async Task TestName()
        {
            string         blobName = "blob";
            CloudBlockBlob blob     = await CreateEmptyBlob(blobName);

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.AreEqual(blobName, azureBlob.Name);
        }
Esempio n. 15
0
        public static string UploadAvatar(ImageManipulation img, string id)
        {
            string  pathAvatar;
            HMACMD5 md5           = new HMACMD5(NimbusConfig.GeneralHMACKey);
            var     nomeImgAvatar = "avatar-" + id;

            md5.ComputeHash(Encoding.Unicode.GetBytes(nomeImgAvatar));
            var nomeHashExt = Base32.ToString(md5.Hash).ToLower() + ".jpg";

            nomeImgAvatar = "av130x130/" + nomeHashExt;
            var nomeImgAvatar180x100 = "av180x100/" + nomeHashExt;
            var nomeImgAvatar35x35   = "av35x35/" + nomeHashExt;
            var nomeImgAvatar60x60   = "av60x60/" + nomeHashExt;


            //envia as imagens redimensionadas
            Task <string> img1 = Task.Run(() =>
            {
                var clone = new ImageManipulation(img);
                clone.FitSize(200, 200); //muito embora a url é av130x130, o tamanho do avatar é 200x200.
                var blob = new AzureBlob(Const.Azure.AvatarContainer, nomeImgAvatar);
                blob.UploadStreamToAzure(clone.SaveToJpeg());
                return(blob.BlockBlob.Uri.AbsoluteUri.Replace("https://", "http://").Replace("***REMOVED***", "storage.portalnimbus.com.br"));
            });

            Task <string> img2 = Task.Run(() =>
            {
                var clone = new ImageManipulation(img);
                clone.FitSize(180, 100);
                var blob180x100 = new AzureBlob(Const.Azure.AvatarContainer, nomeImgAvatar180x100);
                blob180x100.UploadStreamToAzure(clone.SaveToJpeg());
                return(string.Empty);
            });

            Task <string> img3 = Task.Run(() =>
            {
                var clone = new ImageManipulation(img);
                clone.FitSize(60, 60);
                var blob60x60 = new AzureBlob(Const.Azure.AvatarContainer, nomeImgAvatar60x60);
                blob60x60.UploadStreamToAzure(clone.SaveToJpeg());
                return(string.Empty);
            });

            Task <string> img4 = Task.Run(() =>
            {
                var clone = new ImageManipulation(img);
                clone.FitSize(35, 35);
                var blob35x35 = new AzureBlob(Const.Azure.AvatarContainer, nomeImgAvatar35x35);
                blob35x35.UploadStreamToAzure(clone.SaveToJpeg());
                return(string.Empty);
            });

            Task.WaitAll(img1, img2, img3, img4);
            pathAvatar = img1.Result;
            return(pathAvatar);
        }
Esempio n. 16
0
        public void UpdateDestinations()
        {
            // As of right now we only support one destination
            destinations.Clear();

            // Add the AzureBlob Destination Endpoint
            var blobDestination = new AzureBlob(appSettings.BlobAccountName, appSettings.BlobAccountKey);

            destinations.Add(blobDestination);
        }
Esempio n. 17
0
        public async Task TestDownloadText()
        {
            string         text = "some text in the blob";
            CloudBlockBlob blob = await CreateEmptyBlob("blob");

            blob.UploadText(text);

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.AreEqual(text, azureBlob.DownloadText().Result);
        }
Esempio n. 18
0
        public async Task TestExists()
        {
            CloudBlockBlob blob = await CreateEmptyBlob("blob");

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.IsTrue(await azureBlob.Exists());

            blob.Delete();
            Assert.IsFalse(await azureBlob.Exists());
        }
Esempio n. 19
0
        private async Task weeklyReport()
        {
            DBHandler    db      = new linqDBHandler();
            ExcelBuilder builder = new ExcelBuilder();
            AzureBlob    blob    = new AzureBlob();

            // TODO: Replace the following with your own logic.

            foreach (Company c in db.getAllCompanies())
            {
                List <string> columns = new List <string>();
                columns.Add("userName");
                columns.Add("Start Time");
                columns.Add("End Time");
                List <List <string> > rows = new List <List <string> >();

                DateTime     weekDate       = new DateTime();
                TimeZoneInfo israelTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Israel Standard Time");
                weekDate = TimeZoneInfo.ConvertTime(weekDate, israelTimeZone);

                foreach (User u in db.getAllCompanyWorkers(c.id))
                {
                    long         userId = u.id;
                    List <Clock> clocks = db.getClocks(userId, weekDate);

                    foreach (Clock shift in clocks)
                    {
                        List <string> row = new List <string>();
                        row.Add(u.name);
                        row.Add(shift.startTime.ToString());
                        row.Add(shift.endTime.ToString());

                        rows.Add(row);
                    }
                }


                Workbook workBook = builder.write(columns, rows);
                workBook.SaveAs("temp.xlsx");
                string url = await blob.uploadFileAsync("temp.xlsx", c.id + "_" + weekDate + ".xlsx");

                File.Delete("temp.xlsx");

                Report report = new Report();
                report.companyId = c.id;
                report.date      = weekDate;
                report.url       = url;

                db.addReport(report);

                Trace.TraceInformation("new report : " + url);
            }
        }
Esempio n. 20
0
        public Batch AddBatch(Batch batch)
        {
            batch.BatchId = Guid.NewGuid();
            _batchContext.Batches.Add(batch);
            _batchContext.SaveChanges();

            AzureBlob azureBlob = new AzureBlob();

            azureBlob.InitializeBlobContainer(_storageAccountKey, _storageAccountName, _containerName);

            return(batch);
        }
Esempio n. 21
0
        public ActionResult Upload()
        {
            //tamanho da imagem: 150x100, olhe a chamada para o metodo image.FitSize().

            if (Request.Files.Count != 1)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return(Json(new { error = "Bad Request" }));
            }

            var file = Request.Files[0];

            if (file.ContentLength > 5 * 1024 * 1024) // 5MB
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.RequestEntityTooLarge;
                return(Json(new { error = "Too Large" }));
            }

            //nome do arquivo: /container/tp150x100/md5(timestamp + nome arquivo).jpg
            var filename     = Path.GetFileNameWithoutExtension(file.FileName);
            var timeFileName = DateTime.UtcNow.ToFileTimeUtc().ToString() + filename;

            HMACMD5 md5 = new HMACMD5(NimbusConfig.GeneralHMACKey);

            md5.ComputeHash(Encoding.Unicode.GetBytes(timeFileName));
            var fileHash = Base32.ToString(md5.Hash).ToLower() + ".jpg";
            var uploadFileName150x100 = "tp150x100/" + fileHash;
            var uploadFileName60x60   = "tp60x60/" + fileHash;

            var image = new ImageManipulation(Request.Files[0].InputStream);

            //faz upload da imagem 150x100
            image.FitSize(150, 100);
            var imageStream = image.SaveToJpeg();
            var blob        = new AzureBlob(Const.Azure.TopicContainer, uploadFileName150x100);

            blob.UploadStreamToAzure(imageStream);

            image.FitSize(60, 60);
            var image60x60Stream = image.SaveToJpeg();
            var blob60x60        = new AzureBlob(Const.Azure.TopicContainer, uploadFileName60x60);

            blob60x60.UploadStreamToAzure(image60x60Stream);


            var pathFinal = blob.BlockBlob.Uri.AbsoluteUri.Replace("https://", "http://").Replace("***REMOVED***", "storage.portalnimbus.com.br");

            //retorna apenas a 150x100.
            return(Json(new { url = pathFinal }));
        }
Esempio n. 22
0
 /// <summary>
 /// Attempts to delete file
 /// </summary>
 /// <param name="fileName"></param>
 public static void RemoveItem(string fileName)
 {
     try
     {
         lock (padlock)
         {
             AzureBlob.DeleteBlob(fileName);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 23
0
        public async Task TestDownload()
        {
            CloudBlockBlob blob = await CreateEmptyBlob("blob");

            AzureBlob azureBlob = new AzureBlob(blob);

            string path = Path.Combine(Path.GetTempPath(), "azureblobtest");

            File.Delete(path);

            await azureBlob.Download(path);

            Assert.IsTrue(File.Exists(path));
        }
Esempio n. 24
0
        public IHttpActionResult UploadProfilePic()
        {
            var            file   = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
            photogEntities db     = new photogEntities();
            var            studio = db.Studios.FirstOrDefault(x => x.id == StudioID);

            if (file != null && file.ContentLength > 0)
            {
                AzureBlob BlobManagerObj = new AzureBlob(4);
                string    FileName       = BlobManagerObj.UploadFileAPI(file, null);
                FileName = FileName.Substring(FileName.IndexOf('/') + 1);
                return(Ok(FileName));
            }
            return(BadRequest());
        }
        /// <summary>
        /// Removes the package after uploading it to the storage account
        /// </summary>
        private void RemovePackage()
        {
            Debug.Assert(
                !string.IsNullOrEmpty(_deploymentSettings.ServiceSettings.StorageAccountName),
                "StorageAccountName cannot be null or empty.");

            if (!SkipUpload)
            {
                RetryCall(subscription =>
                          AzureBlob.RemovePackageFromBlob(
                              CreateChannel(),
                              _deploymentSettings.ServiceSettings.StorageAccountName,
                              subscription));
            }
        }
Esempio n. 26
0
        public async Task TestNameOfBlobInDirectory()
        {
            string blobName = "blob";

            CloudBlobContainer container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();
            CloudBlobDirectory directory = container.GetDirectoryReference("directory");
            CloudBlockBlob     blob      = directory.GetBlockBlobReference(blobName);
            await BlobUtils.CreateEmptyBlob(blob);

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.AreEqual(blobName, azureBlob.Name);
        }
        /// <summary>
        /// Upload the package to our blob storage account.
        /// </summary>
        /// <returns>Uri to the uploaded package.</returns>
        private Uri UploadPackage()
        {
            Debug.Assert(
                !string.IsNullOrEmpty(_azureService.Paths.CloudPackage),
                "CloudPackage cannot be null or empty.");
            Debug.Assert(
                !string.IsNullOrEmpty(_deploymentSettings.ServiceSettings.StorageAccountName),
                "StorageAccountName cannot be null or empty.");

            string packagePath = _azureService.Paths.CloudPackage;

            Validate.ValidateFileFull(packagePath, Resources.Package);

            Uri packageUri = null;

            if (packagePath.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                packagePath.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                packageUri = new Uri(packagePath);
            }
            else
            {
                SafeWriteObjectWithTimestamp(String.Format(Resources.PublishVerifyingStorageMessage,
                                                           _deploymentSettings.ServiceSettings.StorageAccountName));

                if (!StorageAccountExists())
                {
                    CreateStorageAccount();
                }

                SafeWriteObjectWithTimestamp(Resources.PublishUploadingPackageMessage);

                if (!SkipUpload)
                {
                    packageUri = RetryCall(subscription =>
                                           AzureBlob.UploadPackageToBlob(
                                               CreateChannel(),
                                               _deploymentSettings.ServiceSettings.StorageAccountName,
                                               subscription,
                                               ResolvePath(packagePath)));
                }
                else
                {
                    packageUri = new Uri(packagePath);
                }
            }
            return(packageUri);
        }
Esempio n. 28
0
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            AzureQueue   queue   = new AzureQueue();
            DBHandler    db      = new linqDBHandler();
            ExcelBuilder builder = new ExcelBuilder();
            AzureBlob    blob    = new AzureBlob();

            while (!cancellationToken.IsCancellationRequested)
            {
                var message = await queue.deleteMessageAsync();

                string[] splitted = message.Split(',');
                DateTime weekDate = DateTime.Parse(splitted[1]);
                long     userId;
                long.TryParse(splitted[0], out userId);
                List <Clock>  clocks  = db.getClocks(userId, weekDate);
                List <string> columns = new List <string>();
                columns.Add("Company");
                columns.Add("Start Time");
                columns.Add("End Time");

                List <List <string> > rows = new List <List <string> >();
                foreach (Clock shift in clocks)
                {
                    List <string> row = new List <string>();
                    row.Add(shift.Shift.Company.name);
                    row.Add(shift.startTime.ToString());
                    row.Add(shift.endTime.ToString());

                    rows.Add(row);
                }

                Workbook workBook = builder.write(columns, rows);
                workBook.SaveAs("temp.xlsx");
                string url = await blob.uploadFileAsync("temp.xlsx", userId + "_" + weekDate + ".xlsx");

                File.Delete("temp.xlsx");

                WorkerReport workerReport = new WorkerReport();
                workerReport.workerId = userId;
                workerReport.url      = url;
                workerReport.date     = weekDate;

                db.addWorkerReport(workerReport);

                Trace.TraceInformation("new report : " + url);
            }
        }
        public string CalculateMD5Hash()
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = MD5.Create();

            byte[] inputBytes = Encoding.ASCII.GetBytes(AzureBlob.ToString());
            byte[] md5Hash    = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < md5Hash.Length; i++)
            {
                sb.Append(md5Hash[i].ToString("X2"));
            }
            return(sb.ToString());
        }
        public ActionResult Upload(HttpPostedFileBase file)
        {
            ClaimsPrincipal cp    = ClaimsPrincipal.Current;
            string          email = cp.Identity.Name.ToString();

            LOGGER.Info("video upload link called by " + email + " with the filename " + file.FileName);

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    LOGGER.Info("video upload to azure blob container started for " + email + "with the filename " + file.FileName);
                    string             message    = "";
                    CloudBlobContainer _azureBlob = AzureBlob.AzureBlobContainer(VideoContainerName);
                    CloudBlockBlob     blockBlob  = _azureBlob.GetBlockBlobReference(file.FileName);
                    using (var fileStream = file.InputStream)
                    {
                        try
                        {
                            blockBlob.UploadFromStream(fileStream, accessCondition: Microsoft.WindowsAzure.Storage.AccessCondition.GenerateIfNoneMatchCondition("*"));
                            LOGGER.Info("video upload to azure blob container completed successfully for " + email + " with the filename " + file.FileName);
                            message = "File Uploaded Successfully";
                        }
                        catch (StorageException ex)
                        {
                            if (ex.RequestInformation.HttpStatusCode == (int)System.Net.HttpStatusCode.Conflict)
                            {
                                LOGGER.Info("The video is already exisit in the " + email + " with the filename " + file.FileName);
                                message = "File Already Exisit";
                            }
                        }
                    }
                    ViewBag.Message = message;
                }
                catch (Exception ex)
                {
                    LOGGER.Error("video uplod has failed for " + email + " with the filename " + file.FileName + "due to " + ex.Message.ToString());
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return(View("UploadVideo"));
        }