public async Task <IActionResult> Upload(IFormFile image) { if (image == null) { return(BadRequest()); } // 1. step - convert image to byte array byte[] imageBytes; using (var stream = new MemoryStream()) { await image.CopyToAsync(stream); imageBytes = stream.ToArray(); } // 2. step - use Utilities/AzureStorageUtility.cs class to upload bytes to Azure storage // Move this data to configuration!!!! string storageAccountName = "csharpfer"; string storageAccountKey = "LjVQujwELHihaRmAMgUq90DjTi4ygYCT9cHQPcdA45aNh05oWuafLT4IeELpG0fS1INZoy1B81JRN9WMYJeMsw=="; string storageContainerName = "images"; var uploader = new AzureStorageUtility(storageAccountName, storageAccountKey); var url = await uploader.Upload(storageContainerName, imageBytes); return(RedirectToAction("Image", new { url = url })); }
public async Task <IActionResult> Index(UserUploadModel model) { if (!ModelState.IsValid) { return(View(model)); } ApplicationUser appUser = await _userManager.GetUserAsync(HttpContext.User); User user = _repository.GetUser(Guid.Parse(appUser.Id)); user.Name = model.Name; user.Surname = model.Surname; if (model.Picture != null) { byte[] imageBytes; using (var stream = new MemoryStream()) { await model.Picture.CopyToAsync(stream); imageBytes = stream.ToArray(); } var uploader = new AzureStorageUtility(_configuration["storageAccountName"], _configuration["storageAccountKey"]); user.Picture = await uploader.Upload(_configuration["storageContainerName"], imageBytes); } _repository.UpdateUser(user); return(Redirect("/group")); }
public async Task <ActionResult> ChangeProfilePicture(ChangeProfilePictureVM model) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; if (model.ProfilePictureUpload != null) { if (!validImageTypes.Contains(model.ProfilePictureUpload.ContentType)) { ModelState.AddModelError("CustomError", "Please choose either a GIF, JPG or PNG image."); return(View()); } } if (ModelState.IsValid) { ApplicationUser applicationUser = await _userManager.GetUserAsync(HttpContext.User); UserProfile currentUser = await _repository.GetUserByIdAsync(new Guid(applicationUser.Id)); if (currentUser == null) { return(RedirectToAction("MakeNewProfile", "Main")); } Picture profilePicture = currentUser.ProfilePicture; byte[] data = null; BinaryReader reader = new BinaryReader(model.ProfilePictureUpload.OpenReadStream()); data = reader.ReadBytes((int)model.ProfilePictureUpload.Length); var azureStorageUtility = new AzureStorageUtility(_storageAccountName, _storageAccountKey); Picture oldProfilepicture = profilePicture; profilePicture = await azureStorageUtility.Upload(_storageContainerName, data); profilePicture.UserId = currentUser.Id; try { await _repository.DeletePictureAsync(oldProfilepicture, currentUser.Id); currentUser.ProfilePicture = profilePicture; await _repository.UpdateUserAsync(currentUser); await azureStorageUtility.Delete(_storageContainerName, oldProfilepicture.Id); } catch (UnauthorizedAttemptException) { return(View("~/Views/Shared/InvalidAttempt.cshtml")); } return(RedirectToAction("Index")); } else { return(View()); } }
public void ListBlobsTest() { IEnumerable <IListBlobItem> expected = null; IEnumerable <IListBlobItem> actual; actual = AzureStorageUtility.ListBlobs(); Assert.AreEqual(expected, actual); }
/// <summary> /// Entry point to the application. /// </summary> /// <param name="args"> /// None - Uploads the articles to Cosmos /// seed - Creates the database and collections (not needed) /// query - Performs a query on processed images /// </param> static void Main(string[] args) { List <String> arguments = new List <string>(args); ///////////////////////////////////////////////////////////////////////////////////////////////////// // Load the configuration settings that contain the CosmosDB, Azure Storage, and RSS feed information ///////////////////////////////////////////////////////////////////////////////////////////////////// Configuration config = Configuration.GetConfiguration(); ///////////////////////////////////////////////////////////////////////////////////////////////////// // Creat the Azure Storage Utility ///////////////////////////////////////////////////////////////////////////////////////////////////// AzureStorageUtility storageUtility = new AzureStorageUtility(config.StorageConnectionString); ///////////////////////////////////////////////////////////////////////////////////////////////////// // Create the CosmosDB Client ///////////////////////////////////////////////////////////////////////////////////////////////////// String returnResult = "Jobs completed"; bool bWaitForUser = true; using (CosmosDbClient client = new CosmosDbClient(config.CosmosUri, config.CosmosKey)) { if (arguments.Contains("seed")) { bWaitForUser = false; returnResult = Program.SeedDatabase(config, client); } else if (arguments.Contains("query")) { returnResult = Program.QueryProcessedRecords(config, client); } else { returnResult = Program.UploadRssFeeds(config, client, storageUtility); } } ///////////////////////////////////////////////////////////////////////////////////////////////////// // Dispose of the static hash algorithm ///////////////////////////////////////////////////////////////////////////////////////////////////// if (HashGenerator.HashAlgorithm != null) { HashGenerator.HashAlgorithm.Dispose(); } Console.WriteLine(returnResult); if (bWaitForUser) { Console.WriteLine("Press any key to exit."); Console.ReadLine(); } }
public void ReadBlobFileTest() { string fileName = "Bermuda/Bermuda.Azure.cspkg"; string expected = null; string actual; actual = AzureStorageUtility.ReadBlobFile(fileName); // AzureStorageUtility.UploadBlobFile(actual, "Bermuda/Test.cspkg"); Assert.AreEqual(expected, actual); }
public async Task <IActionResult> AddNewPicture(AddNewPictureVM model) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; if (ModelState.IsValid) { if (!validImageTypes.Contains(model.Picture.ContentType)) { ModelState.AddModelError("CustomError", "Please choose either a GIF, JPG or PNG image."); model.Picture = null; return(View(model)); } else { ApplicationUser applicationUser = await _userManager.GetUserAsync(HttpContext.User); Guid currentUserId = new Guid(applicationUser.Id); if (!await _repository.ContainsUserAsync(currentUserId)) { return(RedirectToAction("MakeNewProfile", "Main")); } BinaryReader reader = new BinaryReader(model.Picture.OpenReadStream()); byte[] data = reader.ReadBytes((int)model.Picture.Length); Album album = await _repository.GetAlbumAsync(model.AlbumId); var uploader = new AzureStorageUtility(_storageAccountName, _storageAccountKey); Picture picture = await uploader.Upload(_storageContainerName, data); picture.UserId = currentUserId; picture.Description = model.Description; picture.Album = album; await _repository.AddPictureAsync(picture, currentUserId); return(RedirectToAction("Index", album.Id)); } } return(View(model)); }
public async Task <IActionResult> DeletePicture(Guid pictureId) { ApplicationUser applicationUser = await _userManager.GetUserAsync(HttpContext.User); Guid currentUserId = new Guid(applicationUser.Id); if (!await _repository.ContainsUserAsync(currentUserId)) { return(RedirectToAction("MakeNewProfile", "Main")); } Picture picture = await _repository.GetPictureAsync(pictureId); if (picture == null) { return(View("~/Views/Shared/InvalidAttempt.cshtml")); } Guid albumId = picture.Album.Id; List <string> roles = (List <string>) await _userManager.GetRolesAsync(applicationUser); bool isAdmin = roles.Contains("Admin"); if (isAdmin) { currentUserId = picture.UserId; } try { await _repository.DeletePictureAsync(picture, currentUserId); var azureUtility = new AzureStorageUtility(_storageAccountName, _storageAccountKey); await azureUtility.Delete(_storageContainerName, picture.Id); } catch (UnauthorizedAttemptException) { return(View("~/Views/Shared/InvalidAttempt.cshtml")); } return(RedirectToAction("Index", "ManageAlbum", new { id = albumId })); }
private static String UploadRssFeeds(Configuration config, CosmosDbClient client, AzureStorageUtility storageUtility) { ///////////////////////////////////////////////////////////////////////////////////////////////// // Looop through each of the RSS feeds, collect the articles, then upload them. ///////////////////////////////////////////////////////////////////////////////////////////////// foreach (RssFeedInfo feed in config.Feeds) { Console.WriteLine("Processing feed : " + feed.RSSFeed); using (RSSFeedReader rssReader = new RSSFeedReader(feed.RSSFeed)) { ///////////////////////////////////////////////////////////////////////////////////////// // The the batch of articles..... ///////////////////////////////////////////////////////////////////////////////////////// int feedItemCount = 0; List <RSSFeedItem> feedItems = rssReader.ReadFeed(); Console.WriteLine("Feed : " + feed.RSSFeed + " has " + feedItems.Count + " items"); ///////////////////////////////////////////////////////////////////////////////////////// // For each article, upload it's image(s) and content. ///////////////////////////////////////////////////////////////////////////////////////// foreach (RSSFeedItem item in feedItems) { Console.WriteLine("Inserting : " + item.Title); Article mainArticle = new Article(); List <Article> imageContent = new List <Article>(); // Set up the images foreach (RSSImageItem image in item.Images) { String blobUri = storageUtility.UploadBlob(image.Path, feed.AzureStorageContainer).Result; if (!String.IsNullOrEmpty(blobUri)) { Article media = new Article(); media.ArtifactType = "image"; media.AssetHash = image.Hash; media.UniqueIdentifier = image.Id; media.SetProperty(ArticleProperties.RetrievalDate, DateTime.Now.ToString("O")); media.SetProperty(ArticleProperties.OriginalUri, image.Uri); media.SetProperty(ArticleProperties.InternalUri, blobUri); imageContent.Add(media); } } // Now set up the article iteself mainArticle.SetProperty(ArticleProperties.OriginalUri, item.Uri); mainArticle.SetProperty(ArticleProperties.RetrievalDate, DateTime.Now.ToString("O")); mainArticle.SetProperty(ArticleProperties.PostDate, item.PublishedDate); mainArticle.SetProperty(ArticleProperties.Title, Program.CleanInput(item.Title)); mainArticle.SetProperty(ArticleProperties.Body, Program.CleanInput(item.Summary)); List <Dictionary <string, string> > childFiles = new List <Dictionary <string, string> >(); foreach (Article file in imageContent) { Dictionary <String, String> obj = new Dictionary <string, string>(); obj.Add(Article.MEDIA_ID, file.UniqueIdentifier); obj.Add(Article.MEDIA_ORIG_URI, file.GetProperty(ArticleProperties.OriginalUri).ToString()); obj.Add(Article.MEDIA_INTERNAL_URI, file.GetProperty(ArticleProperties.InternalUri).ToString()); childFiles.Add(obj); } mainArticle.SetProperty(ArticleProperties.ChildImages, childFiles); mainArticle.SetProperty(ArticleProperties.ChildVideos, null); mainArticle.SetProperty(ArticleProperties.Author, null); mainArticle.SetProperty(ArticleProperties.HeroImage, null); // Insert the media files first foreach (Article imageArticle in imageContent) { try { bool imageResult = client.CreateDocument(config.CosmosDatabase, config.CosmosIngestCollection, imageArticle).Result; Console.WriteLine("Image Insert: " + imageResult.ToString()); } catch (Exception ex) { } } // Wait briefly.... System.Threading.Thread.Sleep(500); bool articleResult = client.CreateDocument(config.CosmosDatabase, config.CosmosIngestCollection, mainArticle).Result; Console.WriteLine("Article Insert: " + articleResult.ToString()); // Only allow one for each feed for now if (++feedItemCount > 5) { break; } } } } return("Finished uploading current articles."); }
public async Task <ActionResult> MakeNewProfile(AddUserProfileVM model) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; if (model.ProfilePictureUpload != null) { if (!validImageTypes.Contains(model.ProfilePictureUpload.ContentType)) { ModelState.AddModelError("CustomError", "Please choose either a GIF, JPG or PNG image."); model.ProfilePictureUpload = null; return(View(model)); } } if (ModelState.IsValid) { ApplicationUser applicationUser = await _userManager.GetUserAsync(HttpContext.User); Guid currentUserId = new Guid(applicationUser.Id); if (await _repository.ContainsUserAsync(currentUserId)) { return(RedirectToAction("Index")); } UserProfile currentUser = new UserProfile(currentUserId); currentUser.UserName = model.UserName; try { await _repository.AddUserAsync(currentUser); } catch (DuplicateItemException) { ModelState.AddModelError("CustomError", "This user name is already taken!"); model.ProfilePictureUpload = null; model.UserName = null; return(View(model)); } Picture profilePicture = null; byte[] data = null; if (model.ProfilePictureUpload != null && model.ProfilePictureUpload.Length > 0) { BinaryReader reader = new BinaryReader(model.ProfilePictureUpload.OpenReadStream()); data = reader.ReadBytes((int)model.ProfilePictureUpload.Length); var uploader = new AzureStorageUtility(_storageAccountName, _storageAccountKey); profilePicture = await uploader.Upload(_storageContainerName, data); profilePicture.UserId = currentUserId; } else { var webRoot = _hostingEnvironment.WebRootPath; var file = Path.Combine(webRoot, "Content\\default-profile-picture.png"); data = System.IO.File.ReadAllBytes(file); var uploader = new AzureStorageUtility(_storageAccountName, _storageAccountKey); profilePicture = await uploader.Upload(_storageContainerName, data); profilePicture.UserId = currentUserId; } if (profilePicture != null) { profilePicture.User = currentUser; currentUser.ProfilePicture = profilePicture; } await _repository.UpdateUserAsync(currentUser); return(RedirectToAction("Index")); } return(View()); }
public String CreateDeployment(String subscriptionId, List <Byte> certificateBytes, String serviceName, String deploymentName, String deploymentSlot, String label, int instanceCount = 1) { String requestId = string.Empty; try { // Go read the Blob Urls for the Azure Deployment Package and // Configuration files. List <CloudBlob> blobList = AzureStorageUtility.ListBlobs(); string configUri = string.Empty; string packageUri = string.Empty; foreach (CloudBlob blob in blobList) { if (blob.Attributes.Uri.ToString().ToLower().EndsWith(".cscfg")) { configUri = blob.Attributes.Uri.ToString(); Logger.Write("Config Url: " + configUri); } if (blob.Attributes.Uri.ToString().ToLower().EndsWith(".cspkg")) { packageUri = blob.Attributes.Uri.ToString(); Logger.Write("Package Url: " + packageUri); } } // Construct paths to Configuration File in Blob Storage string deploymentPackageFolder = ConfigurationManager.AppSettings["DeploymentPackageFolder"].ToString(); string fileName = configUri.ToString().Substring(configUri.IndexOf("/" + deploymentPackageFolder + "/") + deploymentPackageFolder.Length + 2); Logger.Write("Config File Name: " + fileName); string configurationString = AzureStorageUtility.ReadBlobFile(fileName); // Strip off first non-viewable character configurationString = configurationString.Substring(1); Logger.Write("Configuration String: " + configurationString); // Change instance count to the selected amount AzurePackageManager azPackageMgr = new AzurePackageManager(); string modifiedConfigurationString = azPackageMgr.ChangeDeploymentInstanceCount(instanceCount, configurationString); String uri = String.Format(createDeploymentFormat, subscriptionId, serviceName, deploymentSlot); XDocument payload = CreatePayload(deploymentName, packageUri, modifiedConfigurationString, label); ServiceManagementOperation operation = new ServiceManagementOperation(certificateBytes); requestId = operation.Invoke(uri, payload); } catch (Exception ex) { Trace.WriteLine(string.Format("Error in CreateDeployment() Error: {0}", ex.Message)); requestId = string.Empty; } return(requestId); }