How do I handle the error not implemented Exception was unhandled in cppcodeprovider - winforms

This exception indicates on the line of the code
CodeDomProvider = cpp.CreateCompiler();
And he says
The method or operation is not implemented
enter image description here
my code is
CppCodeProvider cpp = new CppCodeProvider();
CodeDomProvider.IsDefinedLanguage("Cpp");
CodeDomProvider.CreateProvider("cpp");
ICodeCompiler IC = cpp.CreateCompiler();
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = IC.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}

In short, as I said in the comment, a Method or Operation Not Implemented exception normally occurs when you have a method that's been added, but no implementation has been placed in the method. This normally occurs when you generate a method using IntelliSense, and is the compilers way of telling you "Hey, you need to put something in here".
public void MyMethod()
{
throw new NotImplementedException();
}
Adding an implementation to the method or even commenting the throwing of the exception would resolve the issue here.
public void MyMethod()
{
//throw new NotImplementedException();
}
Having said that I know that the method throwing the issue isn't your code, that was more so you understand WHAT the error is telling you.
I think the way you're trying to do what you're doing may not be correct. After doing some research and looking at the MS Learn Page you'll notice that this is Obsolete and has been since .net Framework 2.0.
See a similar thread on SO about this topic: How to compile C++ Code using CppCodeProvider in C#

Related

LocationManager never gives Available status for GPS - Codenameone

I created a small app to test out the GPS features of codenameone, but found that it never give an Available status, only Temporarily Unavailable.
For my little test app, the relevant code is the following:
private void doRetrieveLocationAction() {
try {
Location location = LocationManager.getLocationManager().getCurrentLocation();
taLocationDisplay.setText(getGPSDetails() + "\n : " + location.toString());
} catch (Exception e) {
e.printStackTrace();
taLocationDisplay.setText("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage());
ToastBar.showErrorMessage("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage(), 5000);
}
}
private String getGPSDetails() {
StringBuilder sb = new StringBuilder();
sb.append("isEnabled: ").append(LocationManager.getLocationManager().isGPSEnabled());
sb.append("\nisGPSDetectionSupported: ").append(LocationManager.getLocationManager().isGPSDetectionSupported());
sb.append("\ngetStatus: ").append(LocationManager.getLocationManager().getStatus());
return sb.toString();
}
The status being Integer, is assigned the following values in the codenameone source code:
public static final int AVAILABLE = 0;
public static final int OUT_OF_SERVICE = 1;
public static final int TEMPORARILY_UNAVAILABLE = 2;
What I get when the GPS is off:
What I get Immediately after the GPS is turned on:
What I get after I waited a bit:
These results show that the Status never changes. When is the status supposed to change and how am I supposed to use that status? How do I know when the GPS can function or not?
This is being tested on Android
The GPS will be off by default unless you explicitly try to get "real" location by binding a listener to location events. So what you normally get is hybrid location and not GPS location.

Application Level Unhandled Exceptions Not Creating New File

I have a bit of code in my App.cs file to catch unhandled exceptions in the event of a crash. The problems is when I step through the code, it reads as if the file exists, but no new file is actually created. I am probably overlooking something simple but I could use a second (or more ;)) set of eyes on it. Here is my method.
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var contents =
string.Format(
"HResult: {1}{0}" + "HelpLink: {2}{0}" + "Message: {3}{0}" + "Source: {4}{0}"
+ "StackTrace: {5}{0}" + "{0}",
Environment.NewLine,
e.Exception.HResult,
e.Exception.HelpLink,
e.Exception.Message,
e.Exception.Source,
e.Exception.StackTrace);
if (!File.Exists("/Source/CrashLogs/Exceptions.txt"))
{
File.WriteAllText("/Source/CrashLogs/Exceptions.txt", contents);
}
else
{
File.AppendAllText("/Source/CrashLogs/Exceptions.txt", contents);
}
e.Handled = true;
}
I'll next expand this out so that the file name contains the current date, but I would just like to get it running first.
Thanks!!
is folder /Source/CrashLogs/ already exists?
handle also AppDomain.CurrentDomain.UnhandledException
more info here

how do i convert these c# winform codes to be compatible on c# wpf?

hi im working on a project that uses invoke and threads.. it is a simple remote desktop program with chat.. i got a sample here on the internet in c# winform, but i would like to convert it to wpf.. i have no problem in sending message to another client using the wpf program but it cannot receive ( or cannot read) the sent messages from the others.. i think it has something to do with the thread and the invoke method, i read that wpf does invoke differently and i did try the dispatcher.invoke, but it still doesnt do the trick
pls hellp
here's the code
wait = new Thread(new ThreadStart(waitForData));
wait.Start();
that snippet above is executed when a successful connection is made in tcpclient
private void waitForData()
{
try
{
NetworkStream read = tcpclnt.GetStream();
while (read.CanRead)
{
byte[] buffer = new byte[64];
read.Read(buffer, 0, buffer.Length);
s = new ASCIIEncoding().GetString(buffer);
System.Console.WriteLine("Recieved data:" + new ASCIIEncoding().GetString(buffer));
rcvMsg = new ASCIIEncoding().GetString(buffer) + "\n";
hasNewData = true;
bool f = false;
f = rcvMsg.Contains("##");
bool comand = false;
comand = rcvMsg.Contains("*+*-");
/*File receive*/
if (f)
{
string d = "##";
rcvMsg = rcvMsg.TrimStart(d.ToCharArray());
int lastLt = rcvMsg.LastIndexOf("|");
rcvMsg = rcvMsg.Substring(0, lastLt);
NetworkStream ns = tcpclnt.GetStream();
if (ns.CanWrite)
{
string dataS = "^^Y";
byte[] bf = new ASCIIEncoding().GetBytes(dataS);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
try
{
new Recieve_File().recieve_file(rcvMsg);
}
catch (Exception ec)
{
System.Console.WriteLine(ec.Message);
}
}
/*Command-shutdown/restart/logoff*/
else if (comand)
{
string com = "*+*-";
rcvMsg = rcvMsg.TrimStart(com.ToCharArray());
execute_command(rcvMsg);
}
else
{
this.Invoke(new setOutput(setOut));
Thread.Sleep(1000);
}
}
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
}
the snippet above is a code that listens if there is a message or command.. the line
this.invoke(new setoutput(setout)) is a code for appending text in the rtb
hope someone could help me thanks
You've posted a lot of code, but I'm assuming it's only the call to Control.Invoke which is causing the problem. In WPF, use Dispatcher.Invoke (or Dispatcher.BeginInvoke) instead, via the Dispatcher property on the relevant UI element.
I'd also strongly encourage you to:
Refactor your code into smaller methods
Stop catching just Exception except at the top level of any large operation (it should just be a fall-back; usually you catch specific exceptions)
Start following .NET naming conventions
Add a using directive for System so you can just write Console.WriteLine instead of System.Console.WriteLine everywhere
Use Encoding.ASCII instead of creating a new ASCIIEncoding each time you need one
Use a StreamReader to read character data from a stream, instead of reading it as binary data first and then encoding it
For either Stream or TextReader, don't ignore the return value from Read - it tells you how many bytes or characters have been read

WPF using and accessing an ObjectContext from the BackgroundWorker thread

I have a code like the following (I have stripped some code for readability)
private void RicercaArticoloStripped(object sender, DoWorkEventArgs e)
{
try
{
using (var context = new ControlloSchedeLocalEntities())
{
var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text);
if (prodotti.Count() > 0)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{
textBlockDescrizioneArticolo.Text = prodotti.FirstOrDefault().WADESC;
}));
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error:\n\n" + ex.Message + "\r\nStack: " + ex.ToString());
}
}
private void textBoxCodiceArticolo_KeyUpStripped(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(RicercaArticoloStripped);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RicercaArticoloWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
object[] parameters = new object[] { textBoxCodiceArticolo.Text, textBlockDescrizioneArticolo.Text };
worker.RunWorkerAsync(parameters);
}
}
So, as for my understanding of BackgroundWorker, when I instantiate the:
var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text);
I am doing it FROM the working thread, not the UI thread.
But I get an exception on the line immediately below, when I try to access the value:
if (prodotti.Count() > 0)
I get the (in)famous error:
"The calling thread cannot access this object because a different thread owns it"
Why?
As you already said you must use Dispatcher.BeginInvoke/Invoke to perform operations from the control's owner thread or you will get "The calling thread cannot access this object because a different thread owns it" exception. Thats why you got this exception;
And here is why you got this exception on the line below (when prodotti.Count() was called):
When you create prodotti variable it's just a IEnumerable<T> object. So he actually calculates only when you call for prodotti.Count() method and thats why you got exception on this line.
IEnumerable actually is generator, that means that he will produce new set of objects every time he used.
To test this you can calculate prodotti as shown bellow:
var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text).ToList();
In this case you will get exception immediately because .ToList() forces all calculations.
Check this article for generators and enumerators: http://www.codeproject.com/Articles/155462/IEnumerable-Lazy-and-Dangerous
Updated:
really, when you use IEnumerable with reference types you can get the same objects as previously. Read this answer for more: https://stackoverflow.com/a/14361094/1467309
The property Text of TextBox gets the value of the DependencyProperty Text, this can only be done from the UI-thread. You are accessing textBoxCodiceArticolo.Text from your Worker thread.

Large method causing silverlight application to go into "Not responding" state

I am working on an application that plays videos through the silverlight MediaElement object.
I have a large method which is responsible for the following
Opens a FileInfo item on the local file path of the video and strips the file name to get the first portion of the filename which we use as part of the license acquisition process
Sets the LicenseAcquirer on the MediaElement
Sets the Source property of the MediaElement
When this method is called, it actually causes the application to go into a "Not reponding" state for a couple of seconds. How do I avoid this? I have tried putting this all into a background worker but I have to invoke the UI thread for almost all of the calls and this didnt help it seemed to actually make things slower.
I have a busy box that shows while this all happens but that actually stops reporting progress in those seconds where the application is not responding. I understand why this is happening - a lot of work happening on the main UI thread, but how do I avoid this?
This is the code that is causing the trouble:
private void SetupMediaElement(String mediaElementType)
{
Messenger.Default.Send("Loading video...", "SetNowWatchingVideoBusyBoxText");
Messenger.Default.Send(true, "SetNowWatchingVideoBusyBox");
try
{
if (_mainMediaElement != null)
{
VideoItem vi = CurrentSession.NowPlayingVideoItem;
if (vi != null)
{
CurrentVideoItem = vi;
MustShowImage = true;
if (vi.ID != string.Empty)
{
String mediaId = String.Empty;
if (vi.LocalFilePath != DEMOVIDEOPATH)
{
if (vi.LocalFilePath != String.Empty)
{
var fi =
new FileInfo(vi.LocalFilePath);
if (fi.Exists)
{
mediaId = fi.Name.Substring(fi.Name.LastIndexOf('-') + 1,
(fi.Name.LastIndexOf('.') -
(fi.Name.LastIndexOf('-') + 1)));
}
}
else
{
Debug.WriteLine("localFilePath is empty");
}
Debug.WriteLine("MediaId = " + mediaId +
", SessionId = " +
CurrentSession.LoggedOnUser.SessionId +
",Ticket = " +
CurrentSession.LoggedOnUser.Ticket);
string licenseURL = GetLicenseURL(mediaId, CurrentSession.LoggedOnUser.SessionId,
CurrentSession.LoggedOnUser.Ticket);
if (licenseURL != string.Empty)
{
var la = new LicenseAcquirer
{
LicenseServerUriOverride
=
new Uri(
licenseURL)
};
la.AcquireLicenseCompleted += la_AcquireLicenseCompleted;
_mainMediaElement.LicenseAcquirer = la;
}
var fileInfo = new FileInfo(vi.LocalFilePath);
string playURL = #"file://" +
Path.Combine(CoreConfig.HOME_FULL_PATH, fileInfo.Name);
playURL = playURL.Replace("\\", #"/");
VideoURL = playURL;
}
else
{
VideoURL = vi.LocalFilePath;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
_totalDurationSet = false;
TotalTime = FormatTextHoursMinutesSecond(_mainMediaElement.NaturalDuration.TimeSpan);
SetSliderPosition();
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
VideoURL = DEMOVIDEOPATH;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
Thanks
EDIT:
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.
You should do some diagnostics to determine which line(s) are truely costing all that time, its unlikely that amount of time is spread evenly across the whole function.
Place that line (or lines) in a background thread (hopefully that line doesn't need to be on the UI thread).
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.

Resources