How to make an object exist in the current context? - c#

I fully understand why this is happening, but I don't know how to solve it as my attempts all didn't work.
I'm loading a file using MsgReader. I need to catch exceptions.
try
{
var message = MsgReader.Mime.Message.Load(fileInfo);
}
catch(IOException e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (message.Attachments != null) //if has attachments
{
//...
This obviously fails as the object is created within the try. How can I instantiate the object but without having it load the file?
I've tried this before the try:
var message = new MsgReader.Mime.Message;
Error:
Severity Code Description Project File Line Suppression State
Error CS1526 A new expression requires an argument list or (), [], or {} after type
I've also tried variations of this, but I can't find the type I need to specify.

As the error states, if you want to create a new object then you need parentheses to invoke the constructor:
var message = new MsgReader.Mime.Message();
However, in this case it looks like you don't actually want a new instance, but just to declare the variable:
MsgReader.Mime.Message message = null;
In this case the declaration just needs an explicit type specified because var won't be able to infer the type from just null.
Just be aware that if the code in the try fails then message will be null and can't be used/dereferenced.
(And, of course, remove the var keyword when assigning a value to the variable within the try block.)

Related

Need to Write Data from CAPL to C# code and read back to CAPL script

I am using CANoe tool for CAPL scripting.
And I have referred this link for help given by Vector: https://vector.com/portal/medien/cmc/application_notes/AN-IND-1-011_Using_CANoe_NET_API.pdf
Now I am facing issue at step or section: 2.7 Calling CAPL Functions.
There are no syntax errors, but I think, the code is not able to retrieve the function from the CAPL file as it is giving this error when I pass values to the function from C# code.
Error statement:
An exception of type
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll but was not handled in user code
Additional information: Cannot convert null to 'int' because it is a
non-nullable value type
If there is a handler for this exception, the program may be safely continued.
Can some one tell me what exactly the issue is?
Code:
public void Init()
{
CANoe.Application myApp;
myApp = new CANoe.Application();
CANoe.Measurement mymeasure;
mymeasure = (CANoe.Measurement)myApp.Measurement;
myApp.Open(#"D:\Planter CAPl\CANoeCAPLdll.cfg", true, true);
CANoe.OpenConfigurationResult ocresult = myApp.Configuration.OpenConfigurationResult;
if (ocresult.result == 0)
{
CANoe.CAPL CANoeCAPL = (CANoe.CAPL)myApp.CAPL;
CANoeCAPL.Compile(null);
CANoe.CAPLFunction mydata;
mydata = (CANoe.CAPLFunction)CANoeCAPL.GetFunction("Data");//CANoeCAPL.GetFunction("DataShare");
mymeasure.Start();
Thread.Sleep(2000);
int Result = (int)mydata.Call(10,20,30);// Exeception error is coming at this point*
if (mymeasure.Running)
{
mymeasure.Stop();
}
}
}
I think the error message is relatively self-explanatory, you're trying to convert a null value to an int type. Since int is a value type, it cannot be null, therefore, you get an exception.
In the line
int Result = (int)mydata.Call(10,20,30);
The value returned by mydata.Call(10,20,30) is null. You should check if that value is null and do something.
var myDataResult = mydata.Call(10,20,30);
if(myDataResult == null)
// do something
else
int result = (int)myDataResult;
As to why the call to the Call method returns null, you'll have to check the API you're using.

Roslyn Check If Field Declaration has been assigned to

I'm writing an app which converts keys to use resources from a RESX File. This code was working with local variables before:
public static void AnalyzeConstDeclaration(SyntaxNodeAnalysisContext context)
{
var fieldDeclaration = (FieldDeclarationSyntax)context.Node;
if (false == IsValidFieldDeclaration(context, fieldDeclaration))
{
return;
}
var firstVariable = fieldDeclaration.Declaration.Variables.FirstOrDefault();
var dataFlowAnalysis = context.SemanticModel.AnalyzeDataFlow(firstVariable);
var variableSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);
if (dataFlowAnalysis.WrittenOutside.Contains(variableSymbol))
{
return;
}
var firstSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), firstSymbol.Name));
}
However when I try to get the dataFlowAnalysis I receive an error:
Additional information: statementOrExpression is not a StatementSyntax or an ExpressionSyntax.
How can Ideally just need to see if anyone has written to this variable outside of the declaration.
DataFlow works by analyzing order of execution within a single method.
It doesn't make sense for class-level fields.
Instead, you should use a simple syntax visitor (or SymbolFinder) to search the entire class for assignments to the field.
You'll probably also want to check whether it's ever passed as a ref parameter.

Visual Studio Code Analysis - CA1804 thrown when variable is being used

I'm using VS2015 on Windows 7.
Code analysis rule CA1804 (http://msdn.microsoft.com/library/ms182278.aspx) states that I am not using a variable and to remove it. However, I am using this variable further down in my code. This is happening across the whole solution in hundreds of places. The code block looks like this:
[WebMethod]
public bool ValidateUser(string userName, string password)
{
string soapResult = String.Empty;
try
{
// code here
using (StreamReader rd = new StreamReader(responseStream))
{
soapResult = rd.ReadToEnd();
}
// code here
bool isValidated = true;
}
catch (Exception e)
{
// throw error
}
return isValidated;
}
I'm getting this error from Code Analysis:
Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.
Is there something I'm missing here? It's not within an if/else like some of the instances I'm getting this error. But I figured that if it's being used at all this error would not be thrown.
Thanks for any help.
Read the analysis message carefully, note the bit I have highlighted:
Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.
It is telling you that you only assign a value to it (you actually do that twice including the initialisation to string.Empty) but you never use the value. So it's effectively a waste of a variable.
What you should be doing is either using the value, for example:
soapResult = rd.ReadToEnd();
if(soapResult.Contains("something")
{
isValidated = true;
}
else
{
//Not needed but added it to better show how this works in context
isValidated = false;
}
Or remove it altogether and discard the result you get from the StreamReader:
rd.ReadToEnd();

How to call a callback with arguments C#

Here I am again with another question about C#.
So,here are some of the files i have in my project.
Configuration.cs
Settings1.cs
Bot.cs
Now, the problem is, in Settings1.cs I have made a callback (If that is what you call it in C#).
public void LoadText(Configuration.BotInfo config)
{
txtUsername.Text = config.Username;
txtPassword.Text = config.Password;
txtName.Text = config.DisplayName;
txtPrefix.Text = config.DisplayNamePrefix;
txtBackpack.Text = config.Backpack;
txtSell.Text = KeyUserHandler.SellPricePerKey.ToString();
txtBuy.Text = KeyUserHandler.BuyPricePerKey.ToString();
lblPrice.Text = value.ToString();
}
As you can see, it is getting the data from the Configuration.cs file. What I want to do, is that I wanna call this under the Settings1_Load callback.
So, when I type
LoadText();
It gives me the error that it cannot have 0 arguments.. But what argument can I use here? I am only kind of 'dimming' Configuration.BotInfo as config because if I use the full name everywhere, it gives me the non-static and static field error.
No, it is not getting data from Configuration.cs file, it is getting data from that argument which is named config and the type of argument is Configuration.BotInfo. Probably BotInfo is a class which is defined inside of your Configuration.cs file.You should pass a BotInfo instance to your function to make it work.
For example you can call your method like this:
// set your other properties
LoadText(new BotInfo { Username = "user2331", Password="1234", ... })

Try-catch creating new array in C# - where to initialize it?

If I'm reading a string from a config file, I'd use a similar approach to the below, in case the string isn't present in the file being read and an exception results. However, if I want to do the same for a string[] array, I can't just 'new it up' outside the try block because the size is not known.
I can't new it up in the try block itself. How should it be approached?
string[] logContent; // can't new it up here as don't know the size
try
{
logContent = File.ReadAllLines(aLogFile);
}
catch
{
throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
}
You could initialize it to a default value:
string[] logContent = null;
try
{
logContent = File.ReadAllLines(aLogFile);
}
catch
{
// Be careful with the error message here => there might be other reasons
// that the ReadAllLines threw an exception
throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
}
You can initialize it with null and then check against it.
By default it is null. You can leave it as is, if this is appropriate for your program, or initialize to any array according to your needs. Anyway, successful initialization inside of try block overrides this.
string[] logContent=null;
try
{
logContent = File.ReadAllLines(aLogFile);
}
catch
{
throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");
}

Categories

Resources