System.NotSupportedException while calling captureSource.Start() in wp8 - c#

System.NotSupportedException: Specified method is not supported
I'm getting this error sometimes while calling Start method of captureSource to record video on windows phone 8.
Below is my code :
if (captureSource.VideoCaptureDevice != null
&& captureSource.State == CaptureState.Started)
{
captureSource.Stop();
//UpdateUI(ButtonState.Recording, "Initializing...");
//Create Dir If Not Exist
if (!IsolatedStorageFile.GetUserStoreForApplication().DirectoryExists(FileLocation))
IsolatedStorageFile.GetUserStoreForApplication().CreateDirectory(FileLocation);
DateTime theDate = DateTime.Now;
isoVideoFileName = theDate.ToString("yyyyMMdd") + "_" + theDate.ToString("HHmmss") + "_" + "Video" + "." + GlobalDTO.VideoFormat;
// Connect the input and output of fileSink.
captureSource = new CaptureSource();
captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);
captureSource.CaptureImageCompleted += captureSource_CaptureImageCompleted;
fileSink.CaptureSource = captureSource;
fileSink.IsolatedStorageFileName = FileLocation + isoVideoFileName;
}
// Begin recording.
if (captureSource.VideoCaptureDevice != null
&& captureSource.State == CaptureState.Stopped)
{
videoRecorderBrush.SetSource(captureSource);
captureSource.Start();
captureSource.CaptureImageAsync();
}
// Set the button states and the message.
UpdateUI(ButtonState.Recording, "Recording...");

That feature may not be supported on all phones?
That maybe why you are getting that exception. you should catch the exception and handle it in an appropriate way to inform the user the functionality is not supported.

Related

Multiple AxWindowsMediaPlayer controls exception: System.Runtime.InteropServices.COMException' in AxInterop.WMPLib.dll

Developing a winforms C# 4.5 on Win10 that creates multiple AxWindowsMediaPlayer control objects dynamically on Form1 (the only form). Relative code segments look like this:
axWMPn[zi] = new AxWindowsMediaPlayer();
((ISupportInitialize)(axWMPn[zi])).BeginInit();
axWMPn[zi].Name = "Zone " + zi; //Zone name + index
axWMPn[zi].Tag = "Z" + zi; // "Z" + Zone index
axWMPn[zi].Location = loc;
axWMPn[zi].Size = sz;
Controls.Add(axWMPn[zi]);
((ISupportInitialize)(axWMPn[zi])).EndInit();
axWMPn[zi].uiMode = "none";
axWmpDisplayZones.Add(axWMPn[zi].Tag.ToString(), axWMPn[zi]);
axWMPn[zi].StatusChange += axWMPx_StatusChange;
axWMPn[zi].PlayStateChange += axWMPx_PlayStateChange;
I create 6 zones - 3 are assigned static JPEG images and the other 3 are used for video (*.avi and *.mov). The video files are assigned like this:
private void playVideo(string file)
{
int tc6 = 0;
axWMPn[0].URL = file;
axWMPn[4].URL = file;
axWMPn[5].URL = file;
axWMPn[6].URL = "C:/test/AmexDonut.mov";
}
This all works - playVideo is called from another process and the first time all videos run without errors; however when I call playVideo a second time I intermittently get a COMException error:
Exception thrown: 'System.Runtime.InteropServices.COMException' in AxInterop.WMPLib.dll -- Message: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)).
Notes:
1. If I just do 2 axWMPn[x].URL=file it always works no COMException; if I had a third axWMPn[x].URL=file it mostly works with a COMException once every few dozen calls to playVideo. Adding the 4th awWMPn[x].URL=file almost always causes the COMException but not every single time.
So I did following to see more about what was going on:
private void playVideo(string file)
{
int tc6 = 0;
try
{
axWMPn[0].URL = file;
}
catch (System.Runtime.InteropServices.COMException comEx)
{
Console.WriteLine("playVideo COMException 0: " + comEx.Source + " -- " + comEx.Message);
}
try
{
axWMPn[4].URL = file;
}
catch (System.Runtime.InteropServices.COMException comEx)
{
Console.WriteLine("playVideo COMException 4: " + comEx.Source + " -- " + comEx.Message);
}
try
{
axWMPn[5].URL = file;
}
catch (System.Runtime.InteropServices.COMException comEx)
{
Console.WriteLine("playVideo COMException 5: " + comEx.Source + " -- " + comEx.Message);
}
Again:
try
{
axWMPn[6].URL = "C:/test/AmexDonut.mov";
}
catch (System.Runtime.InteropServices.COMException comEx)
{
tc6++;
Console.WriteLine("playVideo COMException 6: try again count = " + tc6 + " - " + comEx.Source + " -- " + comEx.Message);
goto Again;
}
The COMException "busy" when it occurs always occurs in axWMPn[6].URL=file and putting the goto Again in works - tc6 will always just be 1. So merely trying one more time to assign axWMPn[6].URL=file always works. It never takes more than 1 additional try (tc6 never goes beyond 1).
I could leave it this way - I have run it dozens of times and it works just fine; but it sure seems like a bad hack. Does anybody have any thoughts or ideas?
Thanks for any input

OrientDB Query works sometimes and at other times throws FormatException

I'm having a problem with this query below. I'm connecting to OrientDB using the C# driver and running the query in my c# code. All this code is in a loop and the queries in the try block works for a number of iterations and afterwards fails throwing a FormatException. At the point it fails I copy out the query and run it in the orientDB web interface and it returns the expect records so I'm sure it's not the input. So I'm so confused as to why it succeeds sometimes and fails at other times even when the input string is correct. Has anyone encountered a similar problem? Someone please help.
string origin = route[i].Trim();
string destination = route[i + 1].Trim();
List<ODocument> document = new List<ODocument>();
try
{
document = database.Query("select from (traverse out_Connects from " + origin + ") where in = " + destination);
//document = database.Query("select from Connects where (out = " + origin + " and in = " + destination + ")");
}
catch (Exception e)
{
//document = database.Query("select from Connects where (out = " + origin + " and in = " + destination + ")");
}

Get Operational log EventLog fails

I get InvalidOperationException when I run this code:
static void Main(string[] args)
{
var aLog = new EventLog("Microsoft-Windows-Diagnostics-Performance/Operational");
EventLogEntry entry;
var entries = aLog.Entries;
var stack = new Stack<EventLogEntry>();
for (var i = 0; i < entries.Count; i++)
{
entry = entries[i];
stack.Push(entry);
}
entry = stack.Pop();// only display the last record
Console.WriteLine("[Index]\t" + entry.Index +
"\n[EventID]\t" + entry.InstanceId +
"\n[TimeWritten]\t" + entry.TimeWritten +
"\n[MachineName]\t" + entry.MachineName +
"\n[Source]\t" + entry.Source +
"\n[UserName]\t" + entry.UserName +
"\n[Message]\t" + entry.Message +
"\n---------------------------------------------------\n");
}
Exception says that:
Microsoft-Windows-Diagnostics-Performance/Operational doesn't exist on this computer
Why?
Updated
Since you are using EventLog class, the valid "categories" (for sure this is not the correct word to name it...) for your constructor must be Application, System or any other Log Name available under Windows Log tree, not under Applications And Services Log tree.
const string LogName = "Microsoft-Windows-Diagnostics-Performance/Operational";
var query = new EventLogQuery(LogName, PathType.LogName, "*[System/Level=2]");
using (var reader = new EventLogReader(query))
{
var currentEvent = reader.ReadEvent();
while (currentEvent != null)
{
// Do your stuff here...
// Read next event.
currentEvent = reader.ReadEvent();
}
}
This snippet code works for me.
Remember to run this under elevated privileges. If not, you'll receive an Unauthorized exception throw.
First Answer
Because you are initializing your EventLog class with a category that doesn't exists.
Typical valid categories would be Application, System, etc.
The single parameter constructor for EventLog refers to a log of the registry. [^]

Best practice error handling in Global asax

I have code below in global asax now, I want to store exception log in database, is this good practice? because if sql error happens there, I want to log it too. So I am thinking changing the code below to write text log instead email, then on sql error, write text log.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
string testEnvironment = ConfigurationSettings.AppSettings["isTestEnvironment"];
if (testEnvironment == "0")
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ex.InnerException is ViewStateException)
{
Response.Redirect(Request.Url.AbsoluteUri)
return
}
StringBuilder theBody = new StringBuilder();
theBody.Append("URL: " + Request.Url + "\n");
theBody.Append("Referer: " + Request.ServerVariables["HTTP_REFERER"] + "\n");
theBody.Append("IP: " + Request.ServerVariables["REMOTE_HOST"] + "\n");
theBody.Append("Error Message: " + ex.ToString() + "\n");
if (User.Identity.IsAuthenticated)
theBody.Append("User: " + User.Identity.Name + "\n");
else
theBody.Append("User is not logged in." + "\n");
theBody.Append("Form Values: " + "\n");
foreach (string s in Request.Form.AllKeys)
{
if (s != "__VIEWSTATE")
theBody.Append(s + ":" + Request.Form[s] + "\n");
}
theBody.Append("Session Values: " + "\n");
foreach (string s in Session.Keys)
theBody.Append(s + ":" + Session[s] + "\n");
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
email.IsBodyHtml = false;
email.From = new System.Net.Mail.MailAddress("errors#karpach.com", "ErrorManager");
email.To.Add(new System.Net.Mail.MailAddress("errornotification#karpach.com", "Developer"));
email.Subject = Request.Url.ToString().Split('/')[2] + " has ASP.NET error";
email.Body = theBody.ToString();
try
{
System.Net.Mail.SmtpClient emailProvider = new System.Net.Mail.SmtpClient();
emailProvider.Send(email);
}
catch (Exception anException)
{
}
finally
{
if (Request.Url.Segments[Request.Url.Segments.Length - 1].ToLower() != "error.aspx")
Response.Redirect("~/error.aspx?msg=4");
else
{
Response.Write(#"We encountered an internal error. We apologize for any inconvenience
but know that our staff gets emailed EVERY error that occurs so that we can solve it promptly.");
Response.End();
}
}
}
}
You could log it to the EventLog. System admins can setup monitoring to see when new events are added and be alerted to potential problems.
Here's an example from MSDN for the EventLog class:
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");

error: The query results cannot be enumerated more than once

Edit:
DataClassesDataContext dc = new DataClassesDataContext();
string _idCompany = Request["idCompany"];
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
string date = "";
string newsHtml = "<center>";
if(newes.GetEnumerator().MoveNext()){
foreach (var item in newes)//say Error .......................
{
// date = calendar.GetDayOfMonth(item.DateSend) + "/" + calendar.GetMonth(item.DateSend) + "/" + calendar.GetYear(item.DateSend).ToString();
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" onclick=\"$(\'#BodyNews\').text(\'" + HttpUtility.HtmlEncode(item.Body).Trim() + "\');$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + item.Title.ToString() + "</a> " + date + " </li>";
}
newsHtml += "</center>";
}
else
{
// var propertyCompany = dc.GetPropertyCompanyById(Int64.Parse(_idCompany));
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" );$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + "!به صفحه شخصی شرکت " + propertyCompany.FirstOrDefault().NameCompany + " خوش آمدید " + "</a> " + date + " </li>";
}
return newsHtml;
say error:The query results cannot be enumerated more than once
how check var is empty or null with out enumerated;
Why bother with the if at all?
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
//if (newes.GetEnumerator().MoveNext())//check is null or empty
var newesList = newes.ToList();
if (neweList.Count > 0)
{
...
}
You can always check the newesList.Count property afterward.
Not sure what's available as a member in newes, but if it's an object and depending on what dc.GetNewsCompany returns you could check for null
if (news == null) return;
or if it returns an empty collection/array, just check the count/length:
if (news.Count == 0) return;
if (news.Length == 0) return;
the error comes, because you are using .GetEnumerator() on newes and then using the newes again in a foreach Loop .. this causes the "double enumeration".
Generally avoid walking "such var"'s with a foreach, since the DataReader is locked the whole loop !. Means that you cannot use the same entitie in this loop.
Better .ToList() , you can the list.AsQuearable agian if you want to Linq on it
f.e. something like
var newes = dc.CompanyTable.Where(ln => ln.id.Equals(_idCompany));;
List<CompanyTable> newesList = newes.ToList();

Categories