public MediaResponse IsFileExists(MediaRequest request) { try { Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: IsFileExists is started"); bool result; if (request.MediaId % 2 == 0) { result = IsFileExists(_uowPhotoSQL, request.MediaType, request.MediaId); } else { result = IsFileExists(_uowPhotoMongo, request.MediaType, request.MediaId); } Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: IsFileExists is successfully completed"); return(MediaResponse.NoErrorWithResult(result)); } catch (Exception ex) { Log.Instance.ExceptionInfo(ex).LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: Error"); return(MediaResponse.ErrorWithMessage(ex.Message)); } }
public async Task <byte[]> ReadAttachment(string id) { Document doc = client.CreateDocumentQuery(collection.DocumentsLink) .Where(d => d.Id == id) .AsEnumerable() .FirstOrDefault(); if (doc == null) { return(null); } //Query for document for attachment for attachments Attachment attachment = client.CreateAttachmentQuery(doc.SelfLink).AsEnumerable().FirstOrDefault(); //Use DocumentClient to read the Media content if (attachment == null) { return(null); } MediaResponse content = await client.ReadMediaAsync(attachment.MediaLink); byte[] bytes = new byte[content.ContentLength]; await content.Media.ReadAsync(bytes, 0, (int)content.ContentLength); return(bytes); }
private static async Task UseAttachments(string colSelfLink) { dynamic documentWithAttachment = new { id = "PO1800243243470", CustomerId = 1092, TotalDue = 985.018m, }; Document doc = await client.CreateDocumentAsync(colSelfLink, documentWithAttachment); //This attachment could be any binary you want to attach. Like images, videos, word documents, pdfs etc. it doesn't matter using (FileStream fileStream = new FileStream(@".\Attachments\text.txt", FileMode.Open)) { //Create the attachment await client.CreateAttachmentAsync(doc.AttachmentsLink, fileStream, new MediaOptions { ContentType = "text/plain", Slug = "text.txt" }); } //Query the documents for attachments Attachment attachment = client.CreateAttachmentQuery(doc.SelfLink).AsEnumerable().FirstOrDefault(); //Use DocumentClient to read the Media content MediaResponse content = await client.ReadMediaAsync(attachment.MediaLink); byte[] bytes = new byte[content.ContentLength]; await content.Media.ReadAsync(bytes, 0, (int)content.ContentLength); string result = Encoding.UTF8.GetString(bytes); }
public static async Task RunAsync(string[] args) { var client = DocumentDbExtension.CreateClient(); var database = await client.GetDatabaseAsync("IoTEvents"); var temperatureSamplesInsert = await client.GetCollectionAsync(database, "temperatureSamplesInsert"); Document document = await client.NewTemperatureSampleDocumentAsync(temperatureSamplesInsert.SelfLink, "Pordenone", Region.North, 45, 12, Guid.NewGuid(), SensorClass.A, 24); //This attachment could be any binary you want to attach. Like images, videos, word documents, pdfs etc. it doesn't matter using (FileStream fileStream = new FileStream(@".\Attachments\LoremIpsum.txt", FileMode.Open)) { //Create the attachment await client.CreateAttachmentAsync(document.AttachmentsLink, fileStream, new MediaOptions { ContentType = "text/plain", Slug = "LoremIpsum.txt" }); } //Query for document for attachment for attachments Attachment attachment = client.CreateAttachmentQuery(document.SelfLink).AsEnumerable().FirstOrDefault(); //Use DocumentClient to read the Media content MediaResponse content = await client.ReadMediaAsync(attachment.MediaLink); byte[] bytes = new byte[content.ContentLength]; await content.Media.ReadAsync(bytes, 0, (int)content.ContentLength); string result = Encoding.UTF8.GetString(bytes); Console.ReadLine(); }
private void button1_Click(object sender, EventArgs e) { ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); MediaRequest request = new MediaRequest(); request.Nota1 = Convert.ToDouble(txtP1.Text); request.Nota2 = Convert.ToDouble(txtP2.Text); MediaResponse response = client.CalcularMedia(request); txtResultado.Text = response.Resultado; txtMedia.Text = response.Media.ToString(); client.Close(); }
public MediaViewModel(MediaResponse resp) { Title = resp.Title; ReleaseYear = resp.ReleaseYear; IMDBId = resp.IMDBId; Plot = resp.Plot; Actors = resp.Actors; PosterUrl = resp.PosterUrl; }
private void dumpTerseResponse(MediaResponse msg) { Console.WriteLine("---\ntitle: {0}\nquality:", msg.Title); foreach (var stream in msg.Stream) { var qty = stream.Quality; Console.WriteLine( " profile: {0}\n width: {1}\n height: {2}", stream.Quality.Profile, stream.Quality.Width, stream.Quality.Height); } }
private TAttachment DeserialiseAttachment <TDocument, TAttachment>( AttachmentTypeMapping <TDocument, TAttachment> attachmentMapping, MediaResponse mediaResponse) { try { return(attachmentMapping.Reader(mediaResponse.Media)); } catch (Exception e) { throw new NebulaStoreException("Failed to deserialise document attachment", e); } }
public async Task <MediaResponse> GetAttachmentMediaAsync(string documentId, string attachmentId) { var attachmentResponse = await _documentClient.ReadAttachmentAsync(UriFactory.CreateAttachmentUri(_applicationConfig.Database, _applicationConfig.Collection, documentId, attachmentId)); MediaResponse response = null; if (attachmentResponse != null) { response = await _documentClient.ReadMediaAsync(attachmentResponse.Resource.MediaLink); } return(response); }
/// <summary> /// Get list of media videos /// </summary> /// <param name="tenantId"></param> /// <param name="searchCriteria"></param> /// <param name="sortAndPaginationQueryModel"></param> /// <returns></returns> public MediaSiteResponse <MediaResponse> GetMediaVideos(string tenantId, string searchCriteria, SortAndPaginationQueryModel sortAndPaginationQueryModel) { var videoList = _mediaContext.GetPresentations(searchCriteria, sortAndPaginationQueryModel.Offset, sortAndPaginationQueryModel.Limit, sortAndPaginationQueryModel.SortDirection); var mediaResponse = new MediaResponse { Offset = sortAndPaginationQueryModel.Offset, Limit = sortAndPaginationQueryModel.Limit }; if (videoList == null) { return(ServiceResponse.Instance.BuildResponse(ResponseCodes.Ok, mediaResponse)); } mediaResponse.VideoPresentation = videoList; return(ServiceResponse.Instance.BuildResponse(ResponseCodes.Ok, mediaResponse)); }
public List <Media> GetMedias(string username, int count = 20, string maxId = null) { string endpoint = Endpoints.ACCOUNT_MEDIAS.Replace("{username}", username).Replace("{count}", count.ToString()); List <Media> medias = new List <Media>(); bool isMoreAvailable = true; while (isMoreAvailable) { // pass in maxId, if this is a loop from moreAvailable, the maxId will be the oldest post in the previous pass HttpResponse <string> response = Unirest.get(endpoint.Replace("{max_id}", maxId)).asString(); // if http response is success, we will continue, if not, we cannot do much more so we will just say no more available // and return whatever we currently have if (response.Code == 200) { MediaResponse mediaResponse = JsonConvert.DeserializeObject <MediaResponse>(response.Body); // the instagram response also has a status, if ok continue if (mediaResponse.status == "ok") { medias.AddRange(mediaResponse.items); // Assumption: more_available will be false if there are ever less than specified COUNT items returned // as long as that variable is correctly set, we exit the loop // If there is at least one entry, we will capture the oldest one's id and set that as maxId in case // we need to do another pass in the while loop if (mediaResponse.items.Count() > 0) { maxId = mediaResponse.items.OrderBy(i => i.CreateDate).First().Id; } } isMoreAvailable = mediaResponse.more_available; } else { isMoreAvailable = false; } } return(medias); }
public override async Task ExecuteAsync(string generator, WebHookHandlerContext context) { // Convert the incoming data to a collection of InstagramNotifications var notifications = context.GetDataOrDefault <InstagramNotificationCollection>(); // Get the config used by InstaSharp client InstagramConfig config = Dependencies.InstagramConfig; // Access media references in notifications foreach (var notification in notifications) { // If we have an access token then get the media using InstaSharp. OAuthResponse auth; if (Dependencies.Tokens.TryGetValue(notification.UserId, out auth)) { var media = new Media(config, auth); MediaResponse mediaResponse = await media.Get(notification.Data.MediaId); } } }
public async Task <IActionResult> AddMedia([FromBody] MediaRequest mediaRequest) { MediaAbs media = await m_mediaFactory.CreateMedia(mediaRequest); if (media == null) { return(BadRequest(new { Error = "Media Type Not Found" })); } await m_mediaService.AddMedia(media); var baseUri = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}://media"; var locationUrl = baseUri + "/" + media.Id.ToString(); var response = new MediaResponse() { Name = media.Name, Id = media.Id }; return(Created(locationUrl, response)); }
public MediaResponse UploadFile(MediaFile file) { try { Log.Instance.LogAsInfo(nameof(ImageDbFileSource), nameof(UploadFile), "UploadFile is started"); bool result; Log.Instance.LogAsInfo(nameof(ImageDbFileSource), nameof(UploadFile), "Convert Stream to bytes array"); long size = file.Size; byte[] fileBytes = new byte[size]; int bytesRead = 0; do { bytesRead = file.FileByteStream.Read(fileBytes, bytesRead, (int)size - bytesRead); } while (bytesRead > 0); Log.Instance.LogAsInfo(nameof(ImageDbFileSource), nameof(UploadFile), "Convert Stream to bytes array is complet"); if (file.MediaId % 2 == 0) { result = UploadFile(_uowPhotoSQL, fileBytes, file.MediaType, file.MediaId); } else { result = UploadFile(_uowPhotoMongo, fileBytes, file.MediaType, file.MediaId); } Log.Instance.LogAsInfo(nameof(ImageDbFileSource), nameof(UploadFile), "UploadFile is successfully completed"); return(MediaResponse.NoErrorWithResult(result)); } catch (Exception ex) { Log.Instance.ExceptionInfo(ex).LogAsInfo(nameof(ImageDbFileSource), nameof(UploadFile), " Error"); return(MediaResponse.ErrorWithMessage(ex.Message)); } }
private Task MediaHandler(MediaResponse response) { return(HandleMessage(response, "Media", new MediaEvent(response))); }
public MediaEvent(MediaResponse response) { Type = response.Type; Receiving = response.Receiving; }
private async static Task DownloadAttachmentsAsync() { Console.WriteLine("Clearing target directory ..."); DirectoryInfo targetDirectory = new DirectoryInfo("target"); foreach (FileInfo file in targetDirectory.EnumerateFiles()) { file.Delete(); } Console.WriteLine("Downloading attachments ..."); int totalCount = 0; string docContinuation = null; do { FeedResponse <dynamic> response = await cosmosClient.ReadDocumentFeedAsync( UriFactory.CreateDocumentCollectionUri(cosmosDatabaseName, cosmosCollectionName), new FeedOptions { MaxItemCount = -1, RequestContinuation = docContinuation, MaxDegreeOfParallelism = -1 }); docContinuation = response.ResponseContinuation; foreach (Document document in response) { string attachmentContinuation = null; do { FeedResponse <Attachment> attachments = await cosmosClient.ReadAttachmentFeedAsync( document.SelfLink, new FeedOptions { PartitionKey = new PartitionKey(document.Id), RequestContinuation = attachmentContinuation } ); attachmentContinuation = attachments.ResponseContinuation; foreach (var attachment in attachments) { MediaResponse content = await cosmosClient.ReadMediaAsync(attachment.MediaLink); byte[] buffer = new byte[content.ContentLength]; await content.Media.ReadAsync(buffer, 0, buffer.Length); using (FileStream targetFileStream = File.OpenWrite(targetDirectory.FullName + "\\" + attachment.Id)) { await targetFileStream.WriteAsync(buffer, 0, buffer.Length); } Console.WriteLine("Downloaded attachment: {0}", document.Id); totalCount++; } } while (!string.IsNullOrEmpty(attachmentContinuation)); } }while (!string.IsNullOrEmpty(docContinuation)); Console.WriteLine("Finished downloading {0} attachments", totalCount); }
private async static Task CopyAttachmentsToBlobsAsync() { Console.WriteLine("Copying Azure Cosmos DB attachments to Azure Blob storage..."); int totalCount = 0; string docContinuation = null; // Iterate through each document (item in v3+) in the Azure Cosmos DB collection (container in v3+) to look for attachments. do { FeedResponse <dynamic> response = await cosmosClient.ReadDocumentFeedAsync( UriFactory.CreateDocumentCollectionUri(cosmosDatabaseName, cosmosCollectionName), new FeedOptions { MaxItemCount = -1, RequestContinuation = docContinuation, MaxDegreeOfParallelism = -1 }); docContinuation = response.ResponseContinuation; foreach (Document document in response) { string attachmentContinuation = null; // Iterate through each attachment within the document (if any). do { FeedResponse <Attachment> attachments = await cosmosClient.ReadAttachmentFeedAsync( document.SelfLink, new FeedOptions { PartitionKey = new PartitionKey(document.Id), RequestContinuation = attachmentContinuation } ); attachmentContinuation = attachments.ResponseContinuation; foreach (var attachment in attachments) { // Download the attachment in to local memory. MediaResponse content = await cosmosClient.ReadMediaAsync(attachment.MediaLink); byte[] buffer = new byte[content.ContentLength]; await content.Media.ReadAsync(buffer, 0, buffer.Length); // Upload the locally buffered attachment to blob storage string blobId = String.Concat(document.Id, "-", attachment.Id); Azure.Response <BlobContentInfo> uploadedBob = await storageContainerClient.GetBlobClient(blobId).UploadAsync( new MemoryStream(buffer, writable: false), true ); Console.WriteLine("Copied attachment ... Document Id: {0} , Attachment Id: {1}, Blob Id: {2}", document.Id, attachment.Id, blobId); totalCount++; } } while (!string.IsNullOrEmpty(attachmentContinuation)); } }while (!string.IsNullOrEmpty(docContinuation)); Console.WriteLine("Finished copying {0} attachments to blob storage", totalCount); }