In the top of form1 i did
WebBrowser webbrowser1;
Then in the constructor
webbrowser1 = new WebBrowser(); webbrowser1.Navigate("http://www.ims.gov.il/IMS/tazpiot/RainRadar.htm");
webbrowser1.DocumentCompleted += webbrowser1_DocumentCompleted;
Then in the DocumentCompleted event
void webbrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsoluteUri != webbrowser1.Url.AbsoluteUri)
{
return;
}
IHTMLDocument2 doc = (IHTMLDocument2)webbrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
foreach (IHTMLImgElement img in doc.images)
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
bmp.Save(#"E:\newimages\" + img.nameProp);
}
}
}
I'm getting on the hard disk 20 images saved.
But not the one i needed. The one i need to save from this page in the webBrowser is the image in this link: http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=
The radar it self image. I can make save as...
And i can use like i'm doing today WebClient...
But WebClient is not working all the time. So i'm trying to surf to the site and get the image of the radar from the webBrowser. But without success.
UPDATE
This is my webclient how i'm downloading the radar image today:
private void fileDownloadRadar()
{
if (Client.IsBusy == true)
{
Client.CancelAsync();
}
else
{
try
{
Client.DownloadFileAsync(myUri, Path.Combine(combinedTemp));
}
catch(Exception errors)
{
string errors2 = errors.ToString();
}
}
}
Client is WebClient
Now i'm going to the directory of where it was downloaded combinedTemp and i see that the downloaded file is 0kb empty.
The url in myUri is:
http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=
When i put this link in my chrome and surf to it i see the latest radar image but when i'm looking in my hard disk it's 0kb the downloaded file.
And i will add this is not happening now but some time ago some months ago i had another problem in some cases not all the time but in many times when i downloaded the image i had another error i even have open question about it one year ago : Why i'm getting exception: Too many automatic redirections were attempted on webclient?
So in general it's two problems but now the problem is that the downloaded file is 0kb.
This is the Client completed event:
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
try
{
client_Error_counter = client_Error_counter + 1;
if (client_Error_counter == 5)
{
Logger.Write("Tried to download radar image file " + client_Error_counter + " times without success");
Logger.Write("Error Tried to download radar image file : " + e.Error);
client_Error_counter = 0;
}
else
{
Client.DownloadFileAsync(myUri, Path.Combine(combinedTemp));
Logger.Write("Times tried to download radar image file: " + client_Error_counter);
Logger.Write("Error Tried to download radar image file : " + e.Error);
}
}
catch(Exception errors)
{
string myerr = errors.ToString();
}
}
And i see now i missed it that when it's getting to the DownloadFileCompleted event there is an error:
e.Error show: e.Error = {"Too many automatic redirections were attempted."}
StackTRace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
This is why i tried to use the WebBrowser. I can't find a way to solve this "Too many automatic redirections were attempted" problem.
That's why i see the file 0kb on my hard disk.
Another thing is today few hours ago it did download fine some radar images but now it's making this error again.
Related
So I'm creating a program that can go into google and search for the word that has
been saved into a variable. So my question is how I can do this, without having it go to a URL instead just going to Google and search "whatever" Here's the code.
private void button2_Click(object sender, EventArgs e)
{
if (Script.Text == Script.Text)
{
Console.AppendText("\n[1] Loading Websites of " + Script.Text + "...");
}
WebClient wc = new WebClient();
Process.Start(#"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "Scripts " + Script.Text);
}
This should solve your problem
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start("chrome.exe", url);
}
you can also change browser dynamically by adding a second params
You can also do this:
String stringToSearch = “stackoverflow”;
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + stringToSearch);
This assumes IE is the default browser on your machine. If Chrome or Firefox is the default browser, then code will fail.
This is a useful link:
http://www.seirer.net/blog/2014/6/10/solved-how-to-open-a-url-in-the-default-browser-in-csharp
Maybe you can put it in a try catch block and see if there is an exception. If there is an exception with starting IE, then open chrome.
So, I'm trying to implement closed captions support to my UWP video player (using MediaElement), I've followed this example to do so.
I'm getting an error when resolving it called "Error resolving track due to error NetworkError System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I do it like this: I open a file using filepicker and then get the SRT of the video that was picked. After that I show it. Unfortunately, nothing appears.
Here is my OpenButton function:
private async void BtnOpenMedia_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
filePicker.FileTypeFilter.Add(".mp4");
filePicker.FileTypeFilter.Add(".wmv");
filePicker.FileTypeFilter.Add(".mpg");
filePicker.FileTypeFilter.Add(".mpeg");
filePicker.FileTypeFilter.Add("*");
StorageFile storageFile = await filePicker.PickSingleFileAsync();
if (storageFile != null && mElement != null)
{
string strSource = Path.GetDirectoryName(storageFile.Path) + #"\" + storageFile.DisplayName + ".srt";
var mediaSource = MediaSource.CreateFromStorageFile(storageFile);
var ttsStream = TimedTextSource.CreateFromUri(new Uri(strSource));
ttsStream.Resolved += TtsStream_Resolved;
mediaSource.ExternalTimedTextSources.Add(ttsStream);
var mediaPlayback = new MediaPlaybackItem(mediaSource);
mElement.SetPlaybackSource(mediaPlayback);
}
}
Here is my resolve function:
private void TtsStream_Resolved(TimedTextSource sender, TimedTextSourceResolveResultEventArgs args)
{
if (args.Error != null)
{
var ignoreAwaitWarning = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
var msg = new MessageDialog("Error resolving track " + " due to error " + args.Error.ErrorCode + " " + args.Error.ExtendedError);
await msg.ShowAsync();
});
return;
}
}
P.S: Also, I don't know if this is duplicated or not, that's why I'm adding it in this but I've done my research and found nothing. How to preview frames of MediaElement ? For example like YouTube you can preview thumbnails in the slider, I don't know how to achieve that, thanks!
You used a FileOpenPicker to select the Video file, but use a Path to access the .srt file. The .srt file is also in the Video file's folder. I reproduced your problem here:
The error message is clear, you have no access to this file, this file indicates the .srt file, so the problem is where did you store this .srt file. Just have a test, seems TimedTextSource.CreateFromUri(Uri) | createFromUri(Uri) method does not support to access the files in the local machine, but you can use TimedTextSource.CreateFromStream(IRandomAccessStream) | createFromStream(IRandomAccessStream) method for example like this:
if (storageFile != null && mElement != null)
{
//string strSource = Path.GetDirectoryName(storageFile.Path) + #"\" + storageFile.DisplayName + ".srt";
var fileSource = await KnownFolders.VideosLibrary.GetFileAsync(storageFile.DisplayName + ".srt");
IRandomAccessStream strSource = await fileSource.OpenReadAsync();
var mediaSource = MediaSource.CreateFromStorageFile(storageFile);
//var ttsStream = TimedTextSource.CreateFromUri(new Uri(strSource));
var ttsStream = TimedTextSource.CreateFromStream(strSource);
ttsStream.Resolved += TtsStream_Resolved;
mediaSource.ExternalTimedTextSources.Add(ttsStream);
var mediaPlayback = new MediaPlaybackItem(mediaSource);
mediaPlayback.TimedMetadataTracksChanged += (sender1, args) =>
{
mediaPlayback.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
};
mElement.SetPlaybackSource(mediaPlayback);
}
When using this code, the .srt file and video file should in the Video lib and the capability "Videos Library" should be enabled in the manifest.
In an UWP app, you can only access the files in known folder like picture lib, music lib and video lib and doc lib or local folder of your app, if your video is not in these folders, you should also handle the exception when access is denied in this scenario.
How to preview frames of MediaElement ? For example like YouTube you can preview thumbnails in the slider.
For this question, I can't find any ready-made sample for you, but I think the scenario 4 of official Media editing sample can be a direction, it shows a overlay layer on MediaElement, maybe you can set the "baseVideoFile" and the "overlayVideoFile" with the same source. The problem is when and where to show this overlay layer, it's related to the transport control of MediaElement. This is for now just a mind, you can have a try.
I am working on an application that will download a .zip file from my server and extract it when the download is complete using DotNetZip 1.9
The application is downloading the zip file properly, but when it gets to the section to read the .zip file it throws the exception "Cannot read that as a zip file" (full exception at http://pastebin.com/NTrtMgR9).
What throws me off, is even tho it is throwing an exception, the file is still unzipped properly...
Here is my source:
private void btnDownload_Click(object sender, EventArgs e)
{
if (!Directory.Exists(HardCorpsPath))
{
//MessageBox.Show("Downloading HardCorps Mod Pack (Full)", "Downloading", MessageBoxButtons.OK, MessageBoxIcon.Information);
zipFileName = "HardCorps";
HCDownloadURL = String.Format("http://www.survivaloperations.net/client/hardcorps/{0}.zip", zipFileName);
HCZipPath = Path.Combine(Arma2OAPath, #"HardCorps.zip");
WebClient Download_Client = new WebClient();//Declaring the webclient as Download_Client
Download_Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);//the event handler
Download_Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);// " "
Download_Client.DownloadFileAsync(new Uri(HCDownloadURL.Trim().ToString()), HCZipPath);// " "
//extract
using (var zipFile = ZipFile.Read(HCZipPath))
{
zipFile.ExtractAll(Arma2OAPath, ExtractExistingFileAction.OverwriteSilently);
}
}
else
{
MessageBox.Show("Directory Validated!");
//Read users HardCorpsPath\version.txt and compare to server version.txt
//if server version > user version, download patch.zip where "patch" == the number version of the server's version.txt (ex: 1001.zip)
//On download complete, extract to HardCorpsPath and overwrite silently
}
}//close Download Button
and my ProgressChanged/Completed methods:
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
pbDownloader.Value = e.ProgressPercentage;//setting the progressbar value as downloadprogress
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
using (var zipFile = ZipFile.Read(String.Format(HCZipPath)))
{
zipFile.ExtractAll(Arma2OAPath, ExtractExistingFileAction.OverwriteSilently);
}
MessageBox.Show("Downloading Successful ", "Download_Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);//just a messagebox
pbDownloader.Value = (0);//resetting the progressbar
}
HCZipPath is a string variable (if that makes any difference)
In your btnDownload_Click method, you are trying to extract the file before it has been downloaded. You call Download_Client.DownloadFileAsync which starts the download, and you've correctly set up the handler for the DownloadFileCompleted event where you try to do the extraction (again). Take out the code below the DownloadFileAsync method call (to prevent the exception). You file is being extracted because you extract it in the Completed method (which is the correct way to do it).
I have an image in IsolatedStorage, and I would like to programmatically set it as the device lock screen background. My problem is that I cannot get the correct path required by LockScreen.SetImageUri. From referencing http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206968(v=vs.105).aspx it is evident that `"ms-appdata:///local/" is the required precursor for local images.
var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
I have created a folder in my applications IsolatedStorage called Pictures in which jpg images are saved from the CameraCaptureTask. I have tried several ways to access images within this folder via the above scheme but I always receive an ArgumentException on the next line
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
When debugging, however, I see that uri = "ms-appdata:///Local/Pictures/WP_20130812_001.jpg", how is this not correct?
My implementation is as follows
private void recent_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
capturedPicture = (sender as LongListSelector).SelectedItem as CapturedPicture;
if (capturedPicture != null)
{
//filename is the name of the image in the IsolatedStorage folder named Pictures
fileName = capturedPicture.FileName;
}
}
void setAsLockScreenMenuItem_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(fileName))
{
//PictureRepository.IsolatedStoragePath is a string = "Pictures"
//LockHelper("isostore:/" + PictureRepository.IsolatedStoragePath + "/" + fileName, false); //results in FileNotFoundException
LockHelper(PictureRepository.IsolatedStoragePath + "/" + fileName, false); //results in ArgumentException
}
else
{
MessageBoxResult result = MessageBox.Show("You must select an image to set it as your lock screen.", "Notice", MessageBoxButton.OK);
if (result == MessageBoxResult.OK)
{
return;
}
}
}
private async void LockHelper(string filePathOfTheImage, bool isAppResource)
{
try
{
var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication;
if (!isProvider)
{
// If you're not the provider, this call will prompt the user for permission.
// Calling RequestAccessAsync from a background agent is not allowed.
var op = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
// Only do further work if the access was granted.
isProvider = op == Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted;
}
if (isProvider)
{
// At this stage, the app is the active lock screen background provider.
// The following code example shows the new URI schema.
// ms-appdata points to the root of the local app data folder.
// ms-appx points to the Local app install folder, to reference resources bundled in the XAP package.
var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
// Set the lock screen background image.
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
// Get the URI of the lock screen background image.
var currentImage = Windows.Phone.System.UserProfile.LockScreen.GetImageUri();
System.Diagnostics.Debug.WriteLine("The new lock screen background image is set to {0}", currentImage.ToString());
}
else
{
MessageBox.Show("You said no, so I can't update your background.");
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
How might I modify LockScreen.SetImageUri to the proper expected uri?
For setting lock screen images from the app, you might want to declare your app as lock screen provider. You can do that by modifying the WMAppManifest.xml file by adding the following tag:
<Extensions>
<Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
</Extensions>
Check to see if you have this tag in your manifest file.
I hope this could help you to address your issue.
If your app is already installed, make sure that it is an background image provider. If not then go to settings -> lock screen -> background and select your application from the list.
On the programmatic side:
1. Declare the app’s intent in the application manifest file
Edit WMAppManifest.xml with the XML editor, make sure the following extension is present:
<Extensions> <Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" /> </Extensions>
2. Write code to change the background image
The following is an example of how you can write the code for setting the background.
private async void lockHelper(Uri backgroundImageUri, string backgroundAction)
{
try
{
//If you're not the provider, this call will prompt the user for permission.
//Calling RequestAccessAsync from a background agent is not allowed.
var op = await LockScreenManager.RequestAccessAsync();
//Check the status to make sure we were given permission.
bool isProvider = LockScreenManager.IsProvidedByCurrentApplication; if (isProvider)
{
//Do the update.
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(backgroundImageUri);
System.Diagnostics.Debug.WriteLine("New current image set to {0}", backgroundImageUri.ToString());
}
else { MessageBox.Show("You said no, so I can't update your background."); }
}
catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Regarding Uris, there are many options, but keep on mind:
To use an image that you shipped in your app, use ms-appx:///
Uri imageUri = new Uri("ms-appx:///background1.png", UriKind.RelativeOrAbsolute); LockScreen.SetImageUri(imageUri);
To use an image stored in the Local Folder, use ms-appdata:///local/shared/shellcontent
Must be in or below the /shared/shellcontent subfolder
Uri imageUri = new Uri("ms-appdata:///local/shared/shellcontent/background2.png", UriKind.RelativeOrAbsolute); LockScreen.SetImageUri(imageUri);
any one can help me with a c# code to grab frames from a video file,
I am working on a live streaming server on (Asp.Net & c#)..
so when a user uploads his files after live streaming, at the point I have to capture a video frame, so that it can be listed
in the format of a you-tube video list...
thanks
Take a look at AForge.NET - it is a mature set of libraries for processing images and video.
You should be try this it works nice:
private Capture capture = null;
private void btnStart_Click(object sender, System.EventArgs e)
{
try
{
if ( capture == null )
throw new ApplicationException( "Please select a video and/or audio device." );
if ( !capture.Cued )
capture.Filename = txtFilename.Text;
capture.Start();
btnCue.Enabled = false;
btnStart.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show( ex.Message + "\n\n" + ex.ToString() );
}
}