"Use of unassigned local variable" error with an Interface - c#

I'm having trouble with some syntax. I'm not really familiar with interfaces so please excuse my ignorance.
VS2010 is giving me an error at... application.Name = System.AppDomain.CurrentDomain.FriendlyName;
public static void AddApplication(string applicationName = null, string processImageFileName = null)
{
INetFwAuthorizedApplications applications;
INetFwAuthorizedApplication application;
if(applicationName == null)
{
application.Name = System.AppDomain.CurrentDomain.FriendlyName;/*set the name of the application */
}
else
{
application.Name = applicationName;/*set the name of the application */
}
if (processImageFileName == null)
{
application.ProcessImageFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; /* set this property to the location of the executable file of the application*/
}
else
{
application.ProcessImageFileName = processImageFileName; /* set this property to the location of the executable file of the application*/
}
application.Enabled = true; //enable it
/*now add this application to AuthorizedApplications collection */
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
applications = (INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications;
applications.Add(application);
}
I can make that error go away by setting application to null but that causes a run-time null reference error.
Edit:
Here's where I'm adapting the code from. I hope it gives more context
http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

You never initialize
application
before using it here:
application.Name = System.AppDomain.CurrentDomain.FriendlyName;
The variable application is defined as:
INetFwAuthorizedApplication application
You need to assign an instance of a class that implements the interface INetFwAuthorizedApplication.
Somewhere there must be one (or probably more) classes in your project that look something like this:
public class SomeClass : INetFwAuthorizedApplication
{
// ...
}
public class AnotherClass : INetFwAuthorizedApplication
{
// ...
}
You need to determine what class you should use (SomeClass, AnotherClass) then assign an appropriate object, e.g. like this:
INetFwAuthorizedApplication application = new SomeClass();

Interfaces are used to describe what an object does, not what it is specifically. To put into "real world" terms, an interface might be like:
ISmallerThanABreadbox with a FitIntoBreadbox() method. I can't ask you to give me "the smaller than a breadbox" ... as that doesn't make any sense. I can only ask you to give me something that "IS smaller than a breadbox". You have to come up with your own object that makes sense to have the interface on it. An apple is smaller than a breadbox, so if you have a breadbox that only holds items smaller than it, an apple is a good candidate for the ISmallerThanABreadbox interface.
Another example is IGraspable with a Hold() method and FitsInPocket bool property. You can ask to be given something that IS graspable that may or may not fit in your pocket, but you can't ask for "the graspable".
Hope that helps...

Related

What is syntax for creating a class in C# that would be equal to a Module in VB.net

I do almost all of my programming in VB.net (all flavors). I am now been assigned a task to make a new routine in an existing C# application. What I want to be able to do is pass a string variable to a class where I can figure out device type of a symbol handheld and figure out where an executable resides on device.
I am trying to keep the class to contain changes we make going forward in one place.
so a brief description is on a screen there will be a button. on that button click I want pass the text of the button to a (what would be a module in VB) a class and depending on text being passed and device type call a separate executable that lives on the device.
Everything I have tried so far has thrown errors.
On my button click i have
String Reponse = clsCallAction("Activity");
but that gets a message that clsCallAction is a type but is used like a variable.
here is the smaple of clsCallaction
internal static partial class clsCallAction
{
public static object GetPath(object lAppName)
{
string resp = "";
if (lAppName.Equals("Activity"))
{
resp = #"\application\activity.exe";
}
return resp;
}
}
If I put new in front of the clsCallAction("Activity") on button click I get a
cannot create instance of the static class 'clsCalACtion'
appreciate any pointers. very new at C#
It would look something like this:
public static class CallAction
{
public static object GetPath(object lAppName)
{
string resp = "";
if (lAppName.Equals("Activity"))
{
resp = #"\application\activity.exe";
}
return resp;
}
}
And would be used like this:
String Reponse = CallAction.GetPath("Activity");
Don't prefix classes with cls
Avoid using object if possible - it just makes everything harder work than it needs to be.. Kinda like calling everything "thing" - ("Put the thing in the thing and open the thing" is harder to understand than "put the key in the lock and open the door")

Implementing "Intellisense" for IronPython

In my C# application I have a text editor that allows the user to enter IronPython scripts. I have implemented a set of C# classes that are made available to the python environment.
I would now like to implement an "intellisense" type of system where the user enters a variable name then a dot and it prompts the user for a list of available methods and properties.
For example here is an IronPython script:
foo = MyClass()
foo.
At this point the cursor is just after the dot. MyClass example in C#:
public class MyClass {
public void Func1() ...
public void Func2() ...
}
Now I would like to give the user a pop up list showing Func1(), Func2(), etc.
What I need to do is take the variable name "foo" and get the class MyClass.
Note that I can't execute the IronPython code to do this because it performs actions in the user interface.
This is how far I have been able to get:
ScriptSource Source = engine.CreateScriptSourceFromString(pycode, SourceCodeKind.File);
SourceUnit su = HostingHelpers.GetSourceUnit(Source);
Microsoft.Scripting.Runtime.CompilerContext Ctxt = new Microsoft.Scripting.Runtime.CompilerContext(su, new IronPython.Compiler.PythonCompilerOptions(), ErrorSink.Null);
IronPython.Compiler.Parser Parser = IronPython.Compiler.Parser.CreateParser(Ctxt, new IronPython.PythonOptions());
IronPython.Compiler.Ast.PythonAst ast = Parser.ParseFile(false);
if (ast.Body is IronPython.Compiler.Ast.SuiteStatement)
{
IronPython.Compiler.Ast.SuiteStatement ss = ast.Body as IronPython.Compiler.Ast.SuiteStatement;
foreach (IronPython.Compiler.Ast.Statement s in ss.Statements)
{
if (s is IronPython.Compiler.Ast.ExpressionStatement)
{
IronPython.Compiler.Ast.ExpressionStatement es = s as IronPython.Compiler.Ast.ExpressionStatement;
}
}
}
I can see that the last line of the script foo. is an ExpressionStatement and I can drill down from there to get the NameExpression of 'foo' but I can't see how to get the type of the variable.
Is there a better way to do this? Is it even possible?
Thanks!

Asp.Net Core class not passing data

In asp.net core 2.1 Identity I am using a class to move the login name from ExternalLogin.cshtml.cs and Login.cshtml to save them to another table via a class AddUserToStudentTable.
EDIT - I have got the terminology of DTO wrong, but consider it just a class that pushes data around. I just used the wrong naming convention.
The class is
public class StudentNameDTO : IStudentNameDTO
{
public string StudentGoogleNameLogin { get; set; } = string.Empty;
public bool IsExternal { get; set; } = false;
}
The Startup is using AddSingleton but I have also tried AddTransient, with no difference.
services.AddSingleton<IStudentNameDTO, StudentNameDTO>();
And I am using the usual Constructor injection automatically done with wonderful VS 2017
Yet when passing data I always get an error of
evaluation of method () calls into native method system System.Environment.FailFast().
and it all crashes down with
NullReferenceException: Object reference not set to an instance of an object.
ASPNZBat.Business.AddUserToStudentTable.AddUserToStudent(string Email) in AddUserToStudentTable.cs + if (_studentNameDTO.IsExternal == true) ASPNZBat.Areas.Identity.Pages.Account.ExternalLoginModel.OnGetCallbackAsync(string returnUrl, string remoteError) in ExternalLogin.cshtml.cs + _addUserToStudentTable.AddUserToStudent(Email);
I have tried using AddTransient and AddScope as well in the startup, but no difference. Having worked on it for hours I am starting to doubt my ability to program....
Note that when there is data passing through it works OK. But when there is no data - null - instead of working with it it just crashes. I even wrapped it in a boolean to see if I could catch the output with that but it crashed at the boolean as well.
Data going in
if (info.Principal.Identity.Name != null)
{
_studentNameDTO.IsExternal = true;
_studentNameDTO.StudentGoogleNameLogin = info.Principal.Identity.Name;
string Email = info.Principal.FindFirstValue(ClaimTypes.Email);
_addUserToStudentTable.AddUserToStudent(Email);
}
Data coming out
string StudentName = string.Empty;
if (_studentNameDTO.IsExternal == true)
{
StudentName = _studentNameDTO.StudentGoogleNameLogin;
}
There is something about passing null data that it doesn't like and I don't understand.
Here is the github acc for it https://github.com/Netchicken/ASPNZBatV2/tree/master/ASPNZBat
It looks like you've got a case of Over-Dependency Injection.
Aside: You almost certainly don't want to be using AddSingleton here, a singleton is something that you want your application to have no more than one instance of during its execution. In this instance that would mean that if you had two users logging (or whatever the process is here) in at the same time they would both share the same instance of StudentNameDTO.
Based on the code in AddUserToStudentTable.cs the reason you're seeing a NullReferenceException is that there's nothing here that assigns to _studentNameDTO prior to it being used. It's not being injected anywhere, nor is it being passed into the class anywhere, it's declared private so isn't accessible from outside the class and is only read from on lines 36 and 38.
That said, not everything in your code needs, or should, be instantiated via Dependency Injection. Your StudentNameDTO isn't something the class depends on, it's something it consumes / modifies. From a cursory look at your code, it looks like the place that obtains all the data that's stored into StudentNameDTO is in ExternalLoginModel.OnGetCallbackAsync so this is where you should var studentNameDto = new StudentNameDTO() before calling AddUserToStudent and passing the instance of StudentNameDTO into the method, e.g. (line 97 onwards):
if (info.Principal.Identity.Name != null)
{
var studentNameDto = new StudentNameDTO
{
IsExternal = true,
_studentNameDTO.StudentGoogleNameLogin = info.Principal.Identity.Name
};
string Email = info.Principal.FindFirstValue(ClaimTypes.Email);
_addUserToStudentTable.AddUserToStudent(studentNameDto, Email);
}

Object oriented programming in c# object definition

I have an object which I have defined , the class which I define my object from that has a variable. The type of this variable is the same as this class, see below:
public class _car
{
public _car()
{
}
_car BMW = null;
}
.
.
.
Pay attention the last line is global definition of an object machine.
My question is if in a method which is not located in _car class does something like this:
public another_Class
{
public another_class()
{
}
public _car machine = new _car();
public int this_Methode()
{
if (Machine.BMW == null){
Machine.BMW = new _car();
return 1;
}
return 0;
}
public void main_Methode()
{
int i=this_Methode();
i+=this_Methode();
//We run main_method in somewhere in our program now you say i is 0 or 1 or2 ?
}
}
think in this way //We run main_method now you tell me i's value? is 0 or 1 or 2?
To respond after your edits:
It's not clear where Machine.BMW is coming from. But if it is available at runtime, then it will be populated by the following method. So the first time it runs, it will return 1 to I.
public int this_Methode()
{
if (Machine.BMW == null){
Machine.BMW = new _car();
return 1;
}
return 0;
}
int i=this_Methode(); //i = 1 as new car was created.
i+=this_Methode(); Unless there is some other code running, this_Methode() will return zero as the car was already created.
you tell me i's value? Is 0 or 1 or 2? It will be 1 based on what you have shown in the code. But if there was other cod that affected Machine.BMW and set it to null, then it would be 2.
I like to create a test project in Visual Studio to try these kinds of things out. There is a free version called Visual Studio Express that you can use. Just create a Console app and try it out. This will help answer these questions quickly as you can try it and see if it works as expected. I do this all the time when something isn't working the way I think it should.
Greg
It looks like you are trying to learn more about C# and classes. Let me give you a few things that may help you out. This is not a direct answer to your question, as more info is needed to properly answer it. But a few pointers in general may help you out and let you clarify the issue:
In your class, the property _car is not initialized with an instance of a BMW, so it will be null when new instances are created.
You then have the line public _car machine = new _car()
This line is most likely inside of a class, as you can't have it just in a C# file on it's own. If this came from a Console.App, it's probably inside the Main Program so it run when you start it, and then it would be available to the rest of the app at runtime.
In another_class, you have a method which check to see if if BMW is null, and if not, it creates a new car. BMW will always be null here, as it has not been created before.
So even though you have the "global" variable, the "another_class" has no direct reference to it, so it's not going to see it. So I think the answer to your question is that it is going to always be null, not "live."

Using a string variable to set a 'Class = new <string of Class()>'

I have a three polymorphed classes. Based on user input the class should be set to that user's input. So the child class is decided by a user, and should make for 'class = new inputClass'. The snippet of code looks like:
public void characterGeneration(string classSelected)
{
foreach (string classInList in classes.ClassList)
{
if (classSelected == classInList)
{
PlayerOneStats = new Mage();
}
}
PlayerOneStats.generateStats();
}
Where it says PlayerOneStats = new Mage();, I want the Mage() to be the user input.
I've looked at Activator, Assembly, using Type, trying to cast over to the parent of GenerateStats, but nothing works. I've found many people saying it works, and one link that says it doesn't work. Can somebody please clear this up for me? Thank you very much!
Are you sure Activator doesn't work? Activator.CreateInstace("assembly-name", "type-name") seems like exactly what you want. What doesn't work?
What is the base class of Mage (and the other classes a user can select)? You should be able to do this:
public void characterGeneration(string classSelected)
{
foreach (string classInList in classes.ClassList)
{
if (classSelected == classInList)
{
PlayerOneStats = (GenerateStats)Assembly.GetExecutingAssembly().CreateInstance("YourNamespace." + classSelected);
break;
}
}
PlayerOneStats.generateStats();
}
Make sure that you include the namespace the type you want is contained in and this should work for you:
string classSelected = "testCode.Mage";
var player = Activator.CreateInstance(Type.GetType(classSelected));
Since Activator.CreateInstance() returns an object you will have to cast - in your case it would make sense to cast to an interface that all your player classes implement:
var player = (IPlayerCharacter) Activator.CreateInstance(Type.GetType(classSelected));

Categories