c# Console Application referenced DLL variable remains null - c#

I have read through many posts on this type of situation and I can't figure out the solution or what I am doing wrong.
I have a code that references a DLL. It is added as a reference in Visual Studio and it is copied locally along with the target exe file. It runs for me, but when I deploy it to another computer it causes a NullReference exception at the below line of code (see comment):
Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object.
at CheckUpdate.Program.checkUpdate() in Program.cs:line 28
at CheckUpdate.Program.Main(String[] args) in Program.cs:line 22
Here is my code, see comments where the error is reported on the stack trace:
using System;
using System.Collections.Generic;
using System.Text;
using Com.Idiominc.Webservices.Client;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace CheckUpdate
{
class Program
{
private static WSContext _UpdateWScontext { get; set; }
private static string wsUrl = "https://www.myWorldServer.com/ws";
private static string[] myArgs;
static int Main(string[] args)
{
myArgs=args;
if (myArgs.GetUpperBound(0) != 1) return 9;
return checkUpdate();
}
public static int checkUpdate()
{
string testStr = "password1";
while (_UpdateWScontext == null && testStr != "")
{
try
{
_UpdateWScontext = new WSContext("user", testStr, wsUrl + "/services");
}
catch
{
if (_UpdateWScontext == null)
{
if (testStr == "password1") testStr = "password2";
else if (testStr == "password2") testStr = "password3";
else testStr = "";
}
}
}
if (_UpdateWScontext.token == string.Empty) return 0;
string currentversion = myArgs[0];
string latestver = getLatestVersion();
if (latestver == null)
{
return 0;
}
else if (!currentversion.Equals(latestver))
{
if (getLatestDownload()) return 1;
else return 0;
}
else
{
_UpdateWScontext.logout(_UpdateWScontext.token);
return 2;
}
}
}
}
The DLL (WSWebServices.dll) is copied locally along with the executable. It runs on my own station, but when I port it to another station, it causes the exception.
Any advice or clue would be appreciated, thanks.
Edit:
Based on comments the NullReference exception was on the line
if (_UpdateWScontext.token == string.Empty) return 0;
I have now modified this to
if (_UpdateWScontext == null || _UpdateWScontext.token == string.Empty) return 0;
With this no more NullReference Exception, however the exit code now is always 0, meaning the variable is still null.
Any suggestion as to why the connection is not working to the URL? It does work from the browser on the same computer.
Update - solved
I traced the error by outputting the Exception stack trace to the console on the station where the app was not working, and it turned out that the WSWebServices.dll is referencing the Microsoft.Web.Services2.dll (part of the WSE package) and for some reason this was missing from the installation on the misbehaving station.
I added it as a reference and made sure that the dll is copied to the application folder and it now works as intended. Documented here for others in the same mystery why the WorldServer web services would not work.

Within while loop, firstly you try with Password1, you get exception on creating WSContext, then in catch block you set testStr to Password2. With Password2 you again get an exception, and this time in catch block you set testStr to an empty string, and you leave out of while loop without creation of _UpdateWScontext.
I think you null ref exception exactly at this point of code if (_UpdateWScontext.token == string.Empty) return 0;.
You should log exception details in the catch block within the while loop, it can give clue about the error.

Related

Weird error 'System.ExecutionEngineException' occurred in mscorlib.dll

here is the error I am getting :
System.ExecutionEngineException was unhandled
HResult=-2146233082
Message=Exception of type 'System.ExecutionEngineException' was thrown.
InnerException:
code Update:
here is my code
void WriteGraph(int[] vData)
{
string tempWrite = "";
try
{
for (int y = 0; y < vData.Length;)
{
for (int i = 0; i < 20; i++)
{
tempWrite = tempWrite + vData[i] + ",";
y++;
}
File.AppendAllText(name2, tempWrite);
}
File.AppendAllText(name2, Environment.NewLine);
}
catch ( Exception e)
{
AppendTextBox(e.Message.ToString());
}
}
it fails at tempWrite = tempWrite + vData[i] + ",".
not that is in a loop so it does write some values to the file.
I open the file in Excel and it goes from A to LW
before it died ...
the question is why ?
here is the loop :
void PlotSpectrum(int []vData)
{
ArrayList listDataSource = new ArrayList();
// Populate the list with records.
for (int i = 0; i < vData.Length; i++)
{
WriteGraph(Convert.ToString(vData[i]));
listDataSource.Add(new Graph_Class(i, vData[i]));
}
// Bind the chart to the list.
ChartControl myChart = chartControl1;
myChart.DataSource = listDataSource;
// Create a series, and add it to the chart.
Series series1 = new Series("Spectrum", ViewType.Line);
myChart.Series.Add(series1);
// Adjust the series data members.
series1.ArgumentDataMember = "X";
series1.ValueDataMembers.AddRange(new string[] { "Y" });
// Access the view-type-specific options of the series.
((LineSeriesView)series1.View).ColorEach = true;
series1.LegendTextPattern = "{A}";
try
{
//myChart.Update();
// myChart.Refresh();
}catch(Exception err)
{
AppendTextBox(err.Message.ToString());
print("Error in Graph: ", DateTime.Now.ToString(), err.Message.ToString());
}
}
The same thing is happening for me, but it only throws this exception when a yarn rebuild finishes (front-end is React). I am using IIS Express to run locally. I wonder if it doesn't like that the files are changing while the app is running.
This seems to fix it:
Go to Tools, Options, Projects and Solutions, Web Projects; and check "Use the 64 bit version of IIS Express for web sites and projects".
In my case this happened in Service Fabric startup before it has a chance to begin running. The exception shows up in the Event Viewer rather than VS.
This problem happens because something failed before throw ExecutionEngineException.
I faced this issue (typing Japanese characters in TextBox on WPF app), I solved activating Common Language Runtime Exceptions in Exceptions Settings in VS
and checking the values of each runtime exception(before get crash) and I found a null value in one of the variables in a previous method but the crash was thrown many seconds after that.
You can find a deep explanation here: Why this code throws System.ExecutionEngineException

C# throw exception to caller

I have a function that needs to throw an exception, but I wanted it to throw that exception to the line where I called that function:
static int retrieveInt()
{
int a = getInt();
if(a == -1)
throw new Exception("Number not found"); //The runtime error is pointing to this line
return a;
}
static void Main(string[] args)
{
int a = retrieveInt(); //The runtime error would be happening here
}
After 2 hours searching I found the answer to my question. To do what I wanted it is needed to user [System.Diagnostics.DebuggerStepThrough] before the function:
[System.Diagnostics.DebuggerStepThrough]
static int retrieveInt()
{
int a = getInt();
if(a == -1)
throw new Exception("Number not found"); //The runtime error will not be here
return a;
}
static void Main(string[] args)
{
int a = retrieveInt(); //The runtime error happens now here
}
The described behaviour is not strictly possible, but working around to the desired effect is.
The issue you're running into is that in Visual Studio, execution pauses and we see exceptions from the most available location with debug info. For framework methods, this means the method call, even though the exception is being thrown a couple of calls deeper. Since the exception is coming from the same project you're debugging, you'll always have debug info for the actual throw line, and thus you'll always reach that line.
The workaround here is to utilize the Call Stack window in VS, which will include a couple lines down the method call which triggered the error, and double-clicking on this will bring you where you want to be, including all local variables at the time of the call. This is analogous to the framework exception behaviour, because if you look at the stack trace, several frames are marked as "external" because they don't have debug info.
EDIT: To add some info about the behaviour of try and catch, catch will respond to any exception not already caught - thus, even if the exception is thrown several calls deeper, if it's not handled by the time the call stack unwinds into your try block, it'll hit the appropriate catch block (if there is one).
How about this ?
public static int NewInt
{
get
{
throw new Exception("Number not found");
}
}
static void Main(string[] args)
{
int a = NewInt;
}

Cryptoki dll causing application to crash

I'm using cryptoki in a C# app. The problem I have is the following:
I initialize cryptoki using the following code:
public static bool InitializeCryptoki(string criptokilib)
{
if (cryptoki != null)
throw new PdfSignException(PdfSignExceptionCode.PDF_EXCEPTION_NOT_FINALIZED);
try
{
cryptoki = new Cryptoki(criptokilib);
if (cryptoki.Initialize() == 0)
{
isInitialized = true;
return true;
}
return false;
}
catch (CryptokiException ex)
{
Log.Log(log, LogState.ERROR, UserId, "Initialize", null, ex.Message);
return false;
}
}
criptokilib value is equal to "eTPKCS11.dll".
After cryptoki is initialized, I check if at least one card reader exists using the following code:
public static bool HasCardReaders
{
get
{
if (cryptoki == null)
throw new PdfSignException(PdfSignExceptionCode.PDF_EXCEPTION_NOT_INITIALIZED);
return cryptoki.Slots.Count != 0;
}
}
When running the app in debug mode from the compiler (VS 2012), an error message is displayed (no app crash) saying that no card reader has been detected.
When running the app outside the compiler (VS 2012) - by double clicking the exe in debug folder, my application crashes. Looking at the log files, sometimes the app crashes while initializing cryptoki, and sometimes the app crashes while checking if at least one card reader exists.
In debug mode, I discovered that cryptoki.Slots[i].Token throws error n. 224 - this error means that no token is present. Can this error cause my app to crash? Do you have any idea how to overcame this issue?
Thank you very much,
Gica G.
if (cryptoki != null)
This looks wrong. That should read:
if (cryptoki == null)
It seems that upgrading to the last NCryptoki.dll resolves the issue.
However I still didn't understood why that error was causing my app to crash.

How to do proper exception handling and return codes for Console Application

I have a simple C# console application that talks to a webservice. I am not sure if the way I am handling expections and returning error codes are proper. Would like to have comments on good pratice to do this. (I am using CommandLine.dll for option parsing)
class Program
{
static int Main(string[] args) {
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options)) {
try {
var client = new MyWebService();
var response = client.MyFunction(new MyRequest() { Param1 = options.param1, Param2 = options.Param2 });
if (response.ErrorCode != 0) {
Console.WriteLine("Error code= " + response.ErrorCode);
}
else {
File.WriteAllText(options.OutputFile, response.File);
return 0;
}
}
catch (Exception exp) {
Console.WriteLine(exp.Message);
return 1;
}
}
return 1;
}
}
You should use the Console.Error.* to write errors. And I'll say that this:
if (response.ErrorCode != 0) {
Console.Error.WriteLine("Error code= " + response.ErrorCode);
return 1;
} else {
File.WriteAllText(options.OutputFile, response.File);
}
plus a final
return 0;
after the catch would be better, so that if you have multi-stage operations to do, it's easier to code (fall-through == ok, error == fast abort)
with multi-stage I mean:
call ws1
check for non-Exception errors of ws1, if errors abort
call ws2
check for non-Exception errors of ws2, if errors abort
call ws3
check for non-Exception errors of ws3, if errors abort
return success
In the cmd prompt, to save errors:
myprogram 2>err.txt
to redirect output + error:
myprogram > err.txt 2>&1
(the last one was taken from https://stackoverflow.com/a/1420981/613130)
Last thing: if the parsing of the arguments goes wrong, you should output an error.
You should refactor the MyWebService class and the MyFunction to throw exceptions if an error occurs. Instead of returning error codes. That gives you full flexibility in terms of who at which level can handle the errors and it makes the code much more readable.

Compiling error Nullreference

I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.

Categories