Sometimes taken picture not get from device - c#

I am creating Project in Xamarin Form PCL. The issue is sometimes and some device picture are not getting back from Android device. I am using Plugin.Media.CrossMedia to take a picture. The first user can take multiple pictures and then, I am uploading the pictures.
Pic:
if (RPic == null)
{
RPic = new List<RImage>();
}
RImage ri = new RImage();
var photo = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
{
CompressionQuality = 92,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (photo != null)
{
ri.OrderID_ = _OrderId;
ri.Gid_ = 0;
ri.Latitude_ = Lat;
ri.Longitude_ = Long;
ri.ImagePath_ = photo.Path;
ri.dateTime_ = dateTime;
RPic.Add(ri);
}
After this code, i am getting pictures from ri.ImagePath_. But some device this code miss to take the picture from the device. Maybe somebody faces the same issue so, I can get the suggestions. Thanks for your suggestion and rectified code.

Related

Xamarin iOS post image to Instagram

Goal: Using an iOS native method, push a user made picture onto their Instagram feed in C#.
public bool ShareImage(byte[] imageByte)
{
bool result = false;
//string fileName = "xxx.png";
//string path = Path.Combine(FileSystem.CacheDirectory, fileName);
//File.WriteAllBytes(path, imageByte);
NSData data = NSData.FromArray(imageByte);
UIImage image = UIImage.LoadFromData(data);
//NSUrl url = NSUrl.FromString($"instagram://library?AssetPath={path}"); // Only opens
NSUrl url = NSUrl.FromString($"instagram://library?LocalIdentifier={1}");
if (UIApplication.SharedApplication.CanOpenUrl(url))
{
UIApplication.SharedApplication.OpenUrl(url);
}
return result;
}
As far as I'm aware the way I have to do this is to save my image to the device and get a Local Identifier for this.
I have constructed this from the snippets of objective-c code I have seen. Sharing photos only works with the native app installed, as I have learnt from my trials to get the facebook module working.
Edit: Using PHAssetChangeRequest from the iOS Photos namespace does not work.
A collegue has pointed out to me about the possibility of saving then using a photo picker to get the PHAsset for the Local Identifier. But this is an extra step I do not want the users of the App to go through. Better to just remove Instagram support as I just can go through the generic share method as shown below. The disadvantage of this method is that the user has then to pick the medium to share over.
public async void ShareImage(byte[] imageByte)
{
string fileName = "xxx.png";
string path = Path.Combine(FileSystem.CacheDirectory, fileName);
File.WriteAllBytes(path, imageByte);
await Share.RequestAsync(
new ShareFileRequest()
{
File = new ShareFile(path),
Title = "xxx"
}
);
}
Edit 2
Tried a different way using UIDocumentInteractionController but it is showing nothing and not posting, it is not throwing any exceptions to give me any clues as to what I'm doing wrong.
public bool ShareImage(byte[] imageByte)
{
bool result = false;
string fileName = "xxx.igo";
string path = Path.Combine(FileSystem.CacheDirectory, fileName);
File.WriteAllBytes(path, imageByte);
//string caption = "xxx";
string uti = "com.instagram.exclusivegram";
UIImageView view = new UIImageView();
//UIDocumentInteractionController controller = UIDocumentInteractionController.FromUrl(NSUrl.FromString(path));
UIDocumentInteractionController controller = new UIDocumentInteractionController
{
//controller.Url = NSUrl.FromString(path);
Url = NSUrl.FromFilename(path),
Uti = uti
};
//CoreGraphics.CGRect viewDimensions = new CoreGraphics.CGRect(0, 0, 200, 100);
_ = controller.PresentOpenInMenu(CoreGraphics.CGRect.Empty, view, true);
//_ = controller.PresentOpenInMenu(viewDimensions, view, true);
return result;
}
Edit 3
Using
UIView view = new UIImageView();
if (UIApplication.SharedApplication.KeyWindow.RootViewController is UIViewController uiController && uiController.View != null)
{
view = uiController.View;
}
I was able to get the possible share options to show. I was logged in to Instagram using the native App, but the post did not show.
Change
Url = NSUrl.FromFilename(path)
to
Url = new NSUrl(path,false)
The second way is pointing to the correct file path not the file name .
Change
controller.PresentOpenInMenu(CoreGraphics.CGRect.Empty, view, true);
to
controller.PresentOptionsMenu(UIScreen.MainScreen.Bounds, (UIApplication.SharedApplication.Delegate as AppDelegate).Window, true);
Show UIDocumentInteractionController inside current Window and set the proper frame.

System.Net.WebException on YoutubeExtractor when downloading a video

Environment
Windows 8.1
Visual Studio 2017 Community
C#
WPF application
Issue
YoutubeExtractor throws System.Net.WebException when downloading a video.
I got YoutubeExtractor by Nuget and it doesn't work. The VideoInfo object isn't null. I tried several videos on Youtube and the same exceptions popped up. I googled the issue and it didn't give me much help.
Here's the code.
var videos = DownloadUrlResolver.GetDownloadUrls(#"https://www.youtube.com/watch?v=M1wLtAXDgqg");
VideoInfo video = videos
.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
if (video.RequiresDecryption)
DownloadUrlResolver.DecryptDownloadUrl(video);
var videoDownloader = new VideoDownloader(video, System.IO.Path.Combine("D:", video.Title + video.VideoExtension));
videoDownloader.DownloadProgressChanged += (sender_, args) => Console.WriteLine(args.ProgressPercentage);
videoDownloader.Execute(); // I got the exception here.
How can I solve this issue? Thanks.
EDIT : 2017/10/26 13:42 GMT
Alexey 'Tyrrrz' Golub's answer helped so much! I corrected his original code and here it is.
using YoutubeExplode;
using YoutubeExplode.Models.MediaStreams;
var client = new YoutubeClient();
var video = await client.GetVideoAsync("bHzHlSLhtmM");
// double equal signs after s.VideoQuality instead of one
var streamInfo = video.MuxedStreamInfos.First(s => s.Container == Container.Mp4 && s.VideoQuality == VideoQuality.Medium360);
// "D:\\" instead of "D:"
var pathWithoutExtension = System.IO.Path.Combine("D:\\", video.Title);
// streamInfo.Container.GetFileExtension() instead of video.VideoExtension (video doesn't have the property)
var path = System.IO.Path.ChangeExtension(pathWithoutExtension, streamInfo.Container.GetFileExtension());
// new Progress<double>() instead of new Progress()
await client.DownloadMediaStreamAsync(streamInfo, path, new Progress<double>(d => Console.WriteLine(d.ToString("p2"))));

How to get the latest videos from YouTube watch history

I want to get the latest videos from YouTube watch history. I am using the following code, but the video size is always different and very rarely is equal to 100. How can I resolve this problem?
YouTubeRequestSettings ytSettings = new YouTubeRequestSettings(AppKey, DevKey, currentLogin, currentPassword);
ytSettings.PageSize = 10;
ytSettings.AutoPaging = true;
YouTubeRequest ytRequest = new YouTubeRequest(ytSettings);
string uri = "https://gdata.youtube.com/feeds/api/users/default/watch_history?v=2";
Feed<Video> videos = ytRequest.Get<Video>(new Uri(uri));
List<string> vids = new List<string>();
foreach (Video vid in videos.Entries)
{
if (vids.Count < 100)
{
vids.Add(vid.VideoId.ToString());
}
else
{
break;
}
}
I'm pasting the link so that someone might find it useful for their knowledge
http://www.codeproject.com/Articles/143669/Manage-YouTube-using-C-and-Youtube-API
Update:
Hi I got the links from google developers . There are four methods defined there for .NET . so we've to dig ourselves about recent uploads . As I can't see any recent videos headings for .NET
https://developers.google.com/youtube/v3/code_samples/dotnet
https://github.com/youtube/api-samples/tree/master/dotnet

WMPLib: player.mediaCollection.getAll().count is always 0

I am attempting to write code that reads each item from the user's Windows Media Player library. This code works for the majority of users, but for some users, getAll() will return an empty list when they clearly have hundreds or thousands of items in their Windows Media Player library.
var player = new WindowsMediaPlayer();
var collection = player.mediaCollection;
var list = collection.getAll();
int total = list.count;
I am referencing the WMPLib namespace by adding a COM reference to wmp.dll. My application ships with Interop.WMPLib.dll. How would some users' machines be configured in such a way that they run Windows Media Player with many songs in their library, but WMPLib fails to function correctly? Furthermore, what workarounds exist to reliably read the user's Windows Media Player library in all cases?
Try this snippet and see if it works for you.
public List<MusicEntry> GetMusicLibrary()
{
List<MusicEntry> entries;
IWMPPlaylist mediaList = null;
IWMPMedia mediaItem;
try
{
// get the full audio media list
mediaList = media.getByAttribute("MediaType", "Audio");
entries = new List<MusicEntry>(mediaList.count);
for (int i = 0; i < mediaList.count; i++)
{
mediaItem = mediaList.get_Item(i);
// create the new entry and populate its properties
entry = new MusicEntry()
{
Title = GetTitle(mediaItem),
Album = GetAlbum(mediaItem),
Artist = GetArtist(mediaItem),
TrackNumber = GetTrackNumber(mediaItem),
Rating = GetRating(mediaItem),
FileType = GetFileType(mediaItem)
};
entries.Add(entry);
}
}
finally
{
// make sure we clean up as this is COM
if (mediaList != null)
{
mediaList.clear();
}
}
return entries;
}
For more information refer to this excellent article on Code Project.
http://www.codeproject.com/Articles/36338/Export-Windows-Media-Player-Music-Metadata-to-XML

Video is still downloaded after releasing an AVPlayer instance

I have problems with my video player that uses the AV Foundation API and plays a clip via HTTP progressive download. Even when the AVPlayer is released, I'm still downloading the video clip (observed via an HTTP Traffic sniffer).
My player is initialized like that:
m_player = new AVPlayer();
m_playerLayer = new AVPlayerLayer();
m_playerLayer.Player = m_player;
Then, when I have the URL of the video:
m_url = new NSUrl (...);
m_asset = new AVAsset(m_url);
m_asset.AddObserver(this, new NSString ("playable"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, AVPlayerAssetObservationContext);
When I'am notified that the asset is playable, I'm creating an AVPlayerItem:
m_playerItem = new AVPlayerItem(m_asset);
if (m_player.CurrentItem != m_playerItem)
{
m_player.ReplaceCurrentItemWithPlayerItem (m_playerItem);
}
My video is playing without any problems. Then, when I press a back button, I have a mechanism that call a Destroy() method. Here I tried a lot of things to be sure that my player is well released:
if(m_player != null)
{
m_player.Pause();
m_player.Dispose();
m_player = null;
}
if(m_playerLayer != null)
{
m_playerLayer.Dispose();
m_playerLayer = null;
}
if(m_playerItem != null)
{
m_playerItem.Dispose();
m_playerItem = null;
}
if(m_asset != null)
{
m_asset.CancelLoading();
m_asset.RemoveObserver(this, new NSString("playable"));
m_asset.Dispose();
m_asset = null;
}
if(m_url != null)
{
m_url.Dispose();
m_url = null;
}
I tested my app with a debugger and for sure, I'am falling into this code. My objects seems to be well released, but for sure the application is still downloading the video url. Am I doing something wrong in the init / release code?
Thank in advance for your help!
The workaround I found is to add this line in the Destroy() code
m_player.ReplaceCurrentItemWithPlayerItem(new AVPlayerItem());
The video download is then interrupted.

Categories