public string GetBitmapInfo(/*BitmapImage image*/ Google.Apis.Storage.v1.Data.Object obj) { using (var stream = new MemoryStream()) { //obj.MediaLink = obj.MediaLink + "=s32-c"; //obj.SelfLink = obj.SelfLink + "=s32-c"; storage.DownloadObject(obj, stream); stream?.Seek(0, SeekOrigin.Begin); var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.DecodePixelHeight = 230; bitmap.DecodePixelWidth = 230; bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); bitmap.Freeze(); ////string url = urlSigner.Sign( //// "sample_photos_2017", //// obj.Name, //// TimeSpan.FromMinutes(5), //// System.Net.Http.HttpMethod.Get); // Instantiates a client var client = ImageAnnotatorClient.Create(); AnnotateImageRequest request = new AnnotateImageRequest { //Image = Google.Cloud.Vision.V1.Image.FromUri(url), Features = { new Feature { Type = Feature.Types.Type.LabelDetection }, new Feature { Type = Feature.Types.Type.WebDetection }, new Feature { Type = Feature.Types.Type.FaceDetection }, // By default, no limits are put on the number of results per annotation. // Use the MaxResults property to specify a limit. new Feature { Type = Feature.Types.Type.LandmarkDetection, MaxResults = 5 }, new Feature { Type = Feature.Types.Type.TextDetection }, new Feature { Type = Feature.Types.Type.ImageProperties, MaxResults = 5 }, } }; // Load the image file into memory //var image = bitmap; // Performs label detection on the image file var img = new Image(); //image.StreamSource.Seek(0, SeekOrigin.Begin); var memstream = bitmap.StreamSource as MemoryStream; img.Content = Google.Protobuf.ByteString.FromStream(new MemoryStream(memstream.ToArray())); request.Image = img; var result = client.Annotate(request); //var labels = client.DetectLabels(img); var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Label Annotations:"); //stringBuilder.AppendLine(String.Join(",", labels.Select(s => s.Description))); if (result.LabelAnnotations != null) { stringBuilder.AppendLine(String.Join(", ", result.LabelAnnotations.Select(s => $"{s.Description} [{Math.Round(s.Score * 100,0)}%]"))); } //stringBuilder.AppendLine(); //stringBuilder.AppendLine("Web Info:"); ////var webinfos = client.DetectWebInformation(img); ////stringBuilder.AppendLine(String.Join(",", webinfos.WebEntities.Select(s => s.Description))); //if (result.WebDetection != null && result.WebDetection.WebEntities != null) // stringBuilder.AppendLine(String.Join(", ", result.WebDetection.WebEntities.Select(s => $"{s.Description} [{Math.Round(s.Score * 100, 0)}%]"))); //stringBuilder.AppendLine(); //stringBuilder.AppendLine("LandMark:"); ////var landmarks = client.DetectLandmarks(img); ////stringBuilder.AppendLine(String.Join(",", landmarks.Select(s => s.Description))); //if (result.LandmarkAnnotations != null) // stringBuilder.AppendLine(String.Join(", ", result.LandmarkAnnotations.Select(s => $"{s.Description} [{Math.Round(s.Score * 100, 0)}%]"))); //stringBuilder.AppendLine(); //stringBuilder.AppendLine("Text:"); ////var texts = client.DetectText(img); ////stringBuilder.AppendLine(String.Join(",", texts.Select(s => s.Description))); //if (result.TextAnnotations != null) // stringBuilder.AppendLine(String.Join(", ", result.TextAnnotations.Select(s => $"{s.Description} [{Math.Round(s.Score * 100, 0)}%]"))); //stringBuilder.AppendLine(); //stringBuilder.AppendLine("Color:"); ////var properties = client.DetectImageProperties(img); ////stringBuilder.AppendLine(String.Join(",", properties.DominantColors.Colors.Select(s => ////{ //// System.Drawing.Color thisColor = System.Drawing.Color.FromArgb( //// int.Parse(s.Color.Alpha?.ToString() ?? "0"), //// int.Parse(s.Color.Red.ToString()), //// int.Parse(s.Color.Green.ToString()), //// int.Parse(s.Color.Blue.ToString()) //// ); //// return HexConverter(thisColor); ////}))); //if (result.ImagePropertiesAnnotation != null && result.ImagePropertiesAnnotation.DominantColors != null // && result.ImagePropertiesAnnotation.DominantColors.Colors != null) // stringBuilder.AppendLine(String.Join(", ", result.ImagePropertiesAnnotation.DominantColors.Colors.Select(s => { // System.Drawing.Color thisColor = System.Drawing.Color.FromArgb( // int.Parse(s.Color.Alpha?.ToString() ?? "0"), // int.Parse(s.Color.Red.ToString()), // int.Parse(s.Color.Green.ToString()), // int.Parse(s.Color.Blue.ToString()) // ); // ; // return $"{HexConverter(thisColor)} [{Math.Round(s.Score * 100, 0)}%]"; // }))); return(stringBuilder.ToString()); } }
//// PUT api/logins/5 //public void Put(int id, [FromBody]string value) //{ //} //// DELETE api/login/5 //public void Delete(int id) //{ //} private void sendPicture() { String serviceAccountEmail = "*****@*****.**"; string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/MyFirstProject-db5185b5746d.p12"); var certificate = new X509Certificate2(filePath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { Google.Apis.Storage.v1.StorageService.Scope.DevstorageFullControl } }.FromCertificate(certificate)); Google.Apis.Storage.v1.StorageService ss = new Google.Apis.Storage.v1.StorageService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "My First Project", }); var fileobj = new Google.Apis.Storage.v1.Data.Object() { Bucket = "keepguarantee", Name = "file" }; //FileStream fileStream = null; //var dir = Directory.GetCurrentDirectory(); //var path = Path.Combine(dir, "test.png"); //fileStream = new FileStream(path, FileMode.Open); //var insmedia = new ObjectsResource.InsertMediaUpload(ss, fileobj, "keepguarantee", fileStream, "image/jpeg"); //insmedia.Upload(); }
/// <summary> /// Obtains the media URL of an object from its bucket and name. /// The returned string will always have a query parameter, so later query parameters /// can unconditionally be appended with an "&" prefix. /// </summary> private string GetBaseUri(Object source) { ValidateObject(source, nameof(source)); return(GetBaseUri(source.Bucket, source.Name)); }
/// <summary> /// Updates the metadata for an object in storage synchronously. /// </summary> /// <remarks> /// <para> /// If no preconditions are explicitly set in <paramref name="options"/>, the generation and /// metageneration of <paramref name="obj"/> are used as a precondition for the update, /// unless <see cref="UpdateObjectOptions.ForceNoPreconditions"/> is /// set to <c>true</c>. /// </para> /// </remarks> /// <param name="obj">Object to update. Must not be null, and must have populated <c>Name</c> and /// <c>Bucket</c> properties.</param> /// <param name="options">Additional options for the update. May be null, in which case appropriate /// defaults will be used.</param> /// <returns>The <see cref="Object"/> representation of the updated storage object.</returns> public virtual Object UpdateObject( Object obj, UpdateObjectOptions options = null) { throw new NotImplementedException(); }
/// <inheritdoc /> public override Object PatchObject( Object obj, PatchObjectOptions options = null) => CreatePatchObjectRequest(obj, options).Execute();
/// <inheritdoc /> public override Task <Object> PatchObjectAsync( Object obj, PatchObjectOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) => CreatePatchObjectRequest(obj, options).ExecuteAsync(cancellationToken);
/// <inheritdoc /> public override void DeleteObject(Object obj, DeleteObjectOptions options = null) { CreateDeleteObjectRequest(obj, options).Execute(); }
/// <inheritdoc /> public override Task DeleteObjectAsync(Object obj, DeleteObjectOptions options = null, CancellationToken cancellationToken = default) { return(CreateDeleteObjectRequest(obj, options).ExecuteAsync(cancellationToken)); }
public async Task ImageInfo(BitmapImage image, Google.Apis.Storage.v1.Data.Object obj) { //// Instantiates a client //var client = ImageAnnotatorClient.Create(); var name = obj.Name.Replace("Visualhunt.com/", ""); var client = ImageAnnotatorClient.Create(); AnnotateImageRequest request = new AnnotateImageRequest { Features = { new Feature { Type = Feature.Types.Type.LabelDetection }, new Feature { Type = Feature.Types.Type.WebDetection }, new Feature { Type = Feature.Types.Type.FaceDetection }, // By default, no limits are put on the number of results per annotation. // Use the MaxResults property to specify a limit. new Feature { Type = Feature.Types.Type.LandmarkDetection, MaxResults = 5 }, new Feature { Type = Feature.Types.Type.TextDetection }, new Feature { Type = Feature.Types.Type.ImageProperties, MaxResults = 5 }, } }; var img = new Image(); //image.StreamSource.Seek(0, SeekOrigin.Begin); var memstream = image.StreamSource as MemoryStream; img.Content = Google.Protobuf.ByteString.FromStream(new MemoryStream(memstream.ToArray())); request.Image = img; var result = client.Annotate(request); var stringBuilder = new StringBuilder(); stringBuilder.Append(name); stringBuilder.Append(","); if (result.LabelAnnotations != null) { stringBuilder.AppendLine(String.Join(", ", result.LabelAnnotations.Select(s => $"{s.Description}"))); } stringBuilder.AppendLine(); if (result.WebDetection != null && result.WebDetection.WebEntities != null) { stringBuilder.AppendLine(String.Join(", ", result.WebDetection.WebEntities.Select(s => $"{s.Description}"))); } stringBuilder.AppendLine(); if (result.LandmarkAnnotations != null) { stringBuilder.AppendLine(String.Join(", ", result.LandmarkAnnotations.Select(s => $"{s.Description}"))); } stringBuilder.AppendLine(); if (result.TextAnnotations != null) { stringBuilder.AppendLine(String.Join(", ", result.TextAnnotations.Select(s => $"{s.Description}"))); } stringBuilder.AppendLine(); if (result.ImagePropertiesAnnotation != null && result.ImagePropertiesAnnotation.DominantColors != null && result.ImagePropertiesAnnotation.DominantColors.Colors != null) { stringBuilder.AppendLine(String.Join(", ", result.ImagePropertiesAnnotation.DominantColors.Colors.Select(s => { System.Drawing.Color thisColor = System.Drawing.Color.FromArgb( int.Parse(s.Color.Alpha?.ToString() ?? "0"), int.Parse(s.Color.Red.ToString()), int.Parse(s.Color.Green.ToString()), int.Parse(s.Color.Blue.ToString()) ); return($"{HexConverter(thisColor)}"); }))); } //LuceneService.Context.AddIndexesAsync(name, stringBuilder.ToString(), memstream.ToArray()); }
private List <Object> ListObjects(Object obj, bool versions) => ListObjects(obj.Bucket, obj.Name, versions);
/// <inheritdoc /> public override Object UploadObject( Object destination, Stream source, UploadObjectOptions options = null, IProgress <IUploadProgress> progress = null) => new UploadHelper(this, destination, source, options, progress).Execute();
protected override bool _Run() { try { string sData = null; byte[] bData = null; switch (TargetContainer) { case ContainerType.InstructionSetContainer: if (!InstructionSet.InstructionSetContainer.ContainsKey(ContainerDataKey)) { throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist."); } sData = InstructionSet.InstructionSetContainer[ContainerDataKey] as string; bData = InstructionSet.InstructionSetContainer[ContainerDataKey] as byte[]; break; case ContainerType.Session: if (!STEM.Sys.State.Containers.Session.ContainsKey(ContainerDataKey)) { throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist."); } sData = STEM.Sys.State.Containers.Session[ContainerDataKey] as string; bData = STEM.Sys.State.Containers.Session[ContainerDataKey] as byte[]; break; case ContainerType.Cache: if (!STEM.Sys.State.Containers.Cache.ContainsKey(ContainerDataKey)) { throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist."); } sData = STEM.Sys.State.Containers.Cache[ContainerDataKey] as string; bData = STEM.Sys.State.Containers.Cache[ContainerDataKey] as byte[]; break; } string file = DestinationFile; if (Authentication.FileExists(DestinationFile)) { switch (FileExistsAction) { case STEM.Sys.IO.FileExistsAction.Skip: return(true); case STEM.Sys.IO.FileExistsAction.Throw: throw new System.IO.IOException("File already exists."); case STEM.Sys.IO.FileExistsAction.Overwrite: case STEM.Sys.IO.FileExistsAction.OverwriteIfNewer: Authentication.DeleteFile(file); break; case STEM.Sys.IO.FileExistsAction.MakeUnique: file = Authentication.UniqueFilename(file); break; } } string container = Authentication.ContainerFromPath(file); string prefix = Authentication.PrefixFromPath(file); if (!Authentication.DirectoryExists(STEM.Sys.IO.Path.GetDirectoryName(file))) { Authentication.CreateDirectory(STEM.Sys.IO.Path.GetDirectoryName(file)); } byte[] data = null; if (bData != null && bData.Length > 0) { data = bData; } if (data == null) { if (sData != null && sData.Length > 0) { data = System.Text.Encoding.UTF8.GetBytes(sData); } } Google.Apis.Storage.v1.Data.Object o = new Google.Apis.Storage.v1.Data.Object(); o.Bucket = container; o.Name = prefix; if (data != null) { using (System.IO.Stream s = new System.IO.MemoryStream(data)) { Authentication.Client.UploadObject(o, s); } _SavedFile = file; } else if (CreateEmptyFiles) { using (System.IO.Stream s = new System.IO.MemoryStream()) { Authentication.Client.UploadObject(o, s); } _SavedFile = file; } } catch (AggregateException ex) { foreach (Exception e in ex.InnerExceptions) { AppendToMessage(e.Message); Exceptions.Add(e); } } catch (Exception ex) { AppendToMessage(ex.Message); Exceptions.Add(ex); } return(Exceptions.Count == 0); }
private void UploadToCdn() { try { // one thread only if (Interlocked.CompareExchange(ref work, 1, 0) == 0) { var @continue = false; try { CdnItem item; if (queue.TryDequeue(out item)) { @continue = true; var cdnpath = GetCdnPath(item.Bundle.Path); var key = new Uri(cdnpath).PathAndQuery.TrimStart('/'); var content = Encoding.UTF8.GetBytes(item.Response.Content); var inputStream = new MemoryStream(); var storage = GetStorage(); if (ClientSettings.GZipEnabled) { using (var zip = new GZipStream(inputStream, CompressionMode.Compress, true)) { zip.Write(content, 0, content.Length); zip.Flush(); } } else { inputStream.Write(content, 0, content.Length); } var upload = false; Google.Apis.Storage.v1.Data.Object objInfo = null; try { objInfo = storage.GetObject(_bucket, key); } catch (GoogleApiException ex) { if (ex.HttpStatusCode == HttpStatusCode.NotFound) { upload = true; } else { throw; } } if (objInfo != null) { String contentMd5Hash = String.Empty; using (var sha1 = SHA1.Create()) { byte[] bytes = Encoding.UTF8.GetBytes(item.Response.Content); byte[] hashBytes = sha1.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); foreach (byte b in hashBytes) { sb.Append(b.ToString("X2")); } contentMd5Hash = sb.ToString().ToLower(); } if (String.Compare(objInfo.Md5Hash, contentMd5Hash, StringComparison.InvariantCultureIgnoreCase) != 0) { upload = true; } } if (upload) { UploadObjectOptions uploadObjectOptions = new UploadObjectOptions { PredefinedAcl = PredefinedObjectAcl.PublicRead }; inputStream.Position = 0; var uploaded = storage.UploadObject(_bucket, key, MimeMapping.GetMimeMapping(Path.GetFileName(key)), inputStream, uploadObjectOptions, null); inputStream.Close(); if (uploaded.Metadata == null) { uploaded.Metadata = new Dictionary <String, String>(); } if (ClientSettings.GZipEnabled) { uploaded.ContentEncoding = "gzip"; } var cache = TimeSpan.FromDays(365); uploaded.CacheControl = String.Format("public, maxage={0}", (int)cache.TotalSeconds); uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(365)).ToString("R"); storage.UpdateObject(uploaded); } else { inputStream.Close(); } item.Bundle.CdnPath = cdnpath; } } catch (Exception err) { log.Error(err); } finally { work = 0; if (@continue) { Action upload = () => UploadToCdn(); upload.BeginInvoke(null, null); } } } } catch (Exception fatal) { log.Fatal(fatal); } }
public static async Task UploadMediaToCloud(string filePath) { AETL_Object obj; { //pull data from the strings string fileName = Path.GetFileName(filePath); string projectID = fileName.Substring(0, fileName.IndexOf('-')); fileName = fileName.Substring(fileName.IndexOf('-') + 1); string locationID; if (fileName.IndexOf('-') == -1) { locationID = fileName.Substring(0, fileName.IndexOf(".mp4")); } else { locationID = fileName.Substring(0, fileName.IndexOf('-')); } //fetch resolution string Resolution = Path.GetDirectoryName(filePath); Resolution = Resolution.Substring(Resolution.IndexOf('\\') + 1); Resolution = Resolution.Substring(Resolution.IndexOf('\\') + 1); //if this is a monthly video being uploaded then use the filename, otherwise if its a start-to-end video use full.mp4 if (filePath.Contains("MONTHLY")) { obj = new AETL_Monthly(); string name = fileName.Substring(fileName.IndexOf('-') + 1); name = name.Substring(0, name.IndexOf('.')); obj.Filename = name; } else { obj = new AETL_Full(); obj.Filename = "full"; } //fill object data obj.ProjectID = projectID; obj.LocationID = locationID; obj.Bucket = Properties.Settings.Default.Bucket; obj.Filepath = filePath; obj.VideoRes = Resolution; } using (StorageClient storageClient = StorageClient.Create(googleCredential)) { //check if the subfolder exists for our object obj.GenerateSubfolders(storageClient); //check if the file already exists.... if it does and its not a GENERIC project then we can leave. if (obj.CheckIfFileExists(storageClient) && obj.Type != ProjectType.GENERIC) { return; } //otherwise lets upload the data try { using (var fileStream = new FileStream(filePath, FileMode.Open)) { //upload the file Console.Out.WriteLine("Attempting file upload: " + filePath); Google.Apis.Storage.v1.Data.Object output = await storageClient.UploadObjectAsync(obj.GetObject(), fileStream).ConfigureAwait(false); //report success Console.Out.WriteLine("File uploaded: " + filePath); Console.Out.WriteLine("Object created: " + output.TimeCreated); } //cleanup the file now that its been uploaded Thread.Sleep(10000); File.Delete(filePath); return; } catch (Google.GoogleApiException e) { Console.Error.WriteLine("Google API error: " + e.Message); } catch (Exception e) { Console.Error.WriteLine("Unhandled exception: " + e.Message); } } }
private static List <Object> ListObjects(Object obj, bool versions) { return(ListObjects(obj.Bucket, obj.Name, versions)); }