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."
Related
I have the following code:
static int rnd_nmb()
{
Random rnda = new Random();
int skw1 = rnda.Next(1, 11);
return skw1;
}
private void function1()
{
rnd_nmb1();
MessageBox.Show(Convert.ToString(skw1));
}
I want to reuse the variable skw1 to show it on a Message Box, but it says:
"the name 'skw1' does not exist in the current context.".
I don't know what the problem is. Btw. it's a Windows Forms App and i'm using Visual Studio 2019.
I added the 'return' statement and thought it would work, but it doesn't.
there is no need to reuse the local variable, since you wrote a method named rnd_nmb which returns your desired value. Catch the returned value and use it:
private void function1()
{
int returnValue = rnd_nmb();
MessageBox.Show(returnValue.ToString);
}
I don't know what the problem is
One problem is the scope. The variable skw1 exists only withing the scope of the method in which it is declared. The scope is limited by { and }
Second problem is that you need to use the correct names when you try to call a method. You declared rnd_nmb but then you try to use rnd_nmb1
Third hint is that methods with a return value are exactly designed for the user to not care what happens inside of them. You use them and catch the result. It is like a toaster, you put bread in it and you catch the toasted stuff that come out in the end. You don't try to pull out the heating coil and use it on the bread, .... hopefully not... ;)
In my C# project I have a dependency on a 3rd party library. Now I want to write an automated acceptance test for my project. However to invoke the test I need an instance of a class from the 3rd party library. Using reflection I managed to set the values as I needed them apart from one.
Here is the relevant class that I am having the issue with:
public class SystemResults
{
// There must be something like this. However I cannot see it as it is private.
private List<Positions> xyz = new List<Positions>();
public IList<Positions> Positions
{
get
{
return xyz;
}
// This property does not have a set method
}
}
Here is what I have tried so far:
private void InitSystemResults(Type trueSysResType, SystemResults sysRes)
{
List<Position> positions = ImporterTools.GetPositions(PositionsCsv);
trueSysResType.GetProperty("Positions").SetValue(sysRes, positions); // ==> Here I get an exception
}
When I invoke the SetValue() method the following exception is thrown.
System.ArgumentException : Property set method not found.
From this information I figured out, that the class must look as I described above.
Now I would like to proceed with this some how. Has anybody an idea how I can achieve that when I access sysRes.Positions my positions are returned by the get method? Or is there a way to change the get method?
You can use BindingFlags.NonPublic,
FieldInfo[] fields = typeof(SystemResults).GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance).ToArray(); // gets xyz and the other private fields
List<int> testResults = new List<int>() { 1,23,4,5,6,7}; // list of integer to set
SystemResults sysres = new SystemResults(); // instance of object
fields[0].SetValue(sysres, testResults); // I know that fields[0] is xyz (you need to find it first),
// sets list of int to object
Hope helps,
{get;} only properties can have a backing field but Positions may be returning something completely different (not a value of a backing field, but maybe a result of a function).
Your code could accept ISystemResults which you can mock and in real code you could have a class SystemResultsFacade which internally calls the 3rd party code.
I'm trying to add custom coloring for only certain keywords in my Visual Studio editor for C# code. I want to be able to color any type that implements IDisposable as a different color. Ideally I'd like to create a simple list of classes/interfaces that derive from IDisposable in some sort of configuration that I can edit. (Although if you said there was a method/plugin that would automatically find all disposable types and color them independently that would be the Holy Grail).
I've done a ton of research and it looks like an "editor classifier" extension might do the trick. However I created one that merely tries to color the word "Stream" and although it does hit my code that attempts to highlight that word, it does not end up highlighted in the editor.
I have added my VS extension to Github here
This really seems like this should be fairly straightforward but I have gone down many alleys on this one only to find dead-ends. Is there a simpler way to do this, or is my extension broken?
Update
Very strange. I just ran my extension again and although it does not highlight the text in the editor it highlights all instances of "Stream" in the popup text when you hover over a type/variable! Is there any way to get it to apply to the editor?
Depending on wether you are using Jetbrains Resharper or not you may write a plugin for that. That way you are able not only to add visual notification of IDisposable on a variable but also provide quickfixes if, and only if, it is not beeing called, which is what i am assuming you want to catch. Mind you that i can imagine that there's already a R# plugin for that. I know i've considered this too, but i was too lazy to write a plugin for that.
Don't get me wrong btw - If you're not using r# yet you should consider trying it out.
Among others you'd be working with this: API-QuickFix
There are also ways to define custom keywords, as resharper does, given by a custom markup and apply quickfixes to that.
PS: No i don't work at jetbrains. it's just that good :)
UPDATE:
potential VS Extension fix?
check this one out: MSDN Link Highlighting Text
I tried opening your github project but couldn't so i thought i'll just check msdn instead. it seems you are deriving from the wrong class to fulfill your needs?
MSDN keyword "Editors - Extending the Editor - Walkthrough: Highlighting Text"
I know SO wants code on the site, but msdn links going down is rather unlikely and with the given information the content can be found easily enough :)
I'm a bit late to the party, but hey, why not throw my 2 cents in.
As you've explained in your question, your project has two basic parts:
Finding the classes that implement IDisposable
Highlighting them
The first is by far the hardest, though not impossible. A word-list based approach is probably the simplest, though it should be possible with Roslyn to figure out on the fly which classes inherit IDisposible.
You could also always resort to loading the project's compiled .exe/.dll in the background after a build and figuring out what the types are there, but you'd still have to write some magic glue code to figure out what short class names in the code referred to what actual full-name classes in the assembly.
The second part, highlighting, is quite easy once you know how to do it (it helps that I've spent the last several months working full-time on extending VS). Of course, with Visual Studio, nothing is as simple as it looks (despite the efforts of Microsoft to try to make it user-friendly). So, I've built a sample extension that highlights just classes named "Stream" within C# files to get you started.
The relevant code is below, and the full project source is on GitHub). It starts with a classification-tagger provider:
[Export(typeof(ITaggerProvider))]
[ContentType("CSharp")]
[TagType(typeof(ClassificationTag))]
[Name("HighlightDisposableTagger")]
public class HighlightDisposableTaggerProvider : ITaggerProvider
{
[Import]
private IClassificationTypeRegistryService _classificationRegistry = null;
[Import]
private IClassifierAggregatorService _classifierAggregator = null;
private bool _reentrant;
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag
{
if (_reentrant)
return null;
try {
_reentrant = true;
var classifier = _classifierAggregator.GetClassifier(buffer);
return new HighlightDisposableTagger(buffer, _classificationRegistry, classifier) as ITagger<T>;
}
finally {
_reentrant = false;
}
}
}
Then the tagger itself:
public class HighlightDisposableTagger : ITagger<ClassificationTag>
{
private const string DisposableFormatName = "HighlightDisposableFormat";
[Export]
[Name(DisposableFormatName)]
public static ClassificationTypeDefinition DisposableFormatType = null;
[Export(typeof(EditorFormatDefinition))]
[Name(DisposableFormatName)]
[ClassificationType(ClassificationTypeNames = DisposableFormatName)]
[UserVisible(true)]
public class DisposableFormatDefinition : ClassificationFormatDefinition
{
public DisposableFormatDefinition()
{
DisplayName = "Disposable Format";
ForegroundColor = Color.FromRgb(0xFF, 0x00, 0x00);
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged = delegate { };
private ITextBuffer _subjectBuffer;
private ClassificationTag _tag;
private IClassifier _classifier;
private bool _reentrant;
public HighlightDisposableTagger(ITextBuffer subjectBuffer, IClassificationTypeRegistryService typeService, IClassifier classifier)
{
_subjectBuffer = subjectBuffer;
var classificationType = typeService.GetClassificationType(DisposableFormatName);
_tag = new ClassificationTag(classificationType);
_classifier = classifier;
}
public IEnumerable<ITagSpan<ClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
if (_reentrant) {
return Enumerable.Empty<ITagSpan<ClassificationTag>>();
}
var tags = new List<ITagSpan<ClassificationTag>>();
try {
_reentrant = true;
foreach (var span in spans) {
if (span.IsEmpty)
continue;
foreach (var token in _classifier.GetClassificationSpans(span)) {
if (token.ClassificationType.IsOfType(/*PredefinedClassificationTypeNames.Identifier*/ "User Types")) {
// TODO: Somehow figure out if this refers to a class which implements IDisposable
if (token.Span.GetText() == "Stream") {
tags.Add(new TagSpan<ClassificationTag>(token.Span, _tag));
}
}
}
}
return tags;
}
finally {
_reentrant = false;
}
}
}
I've only tested this on VS2010, but it should work for VS2013 too (the only thing that might be different is the class classification name, but that's easy to discover with a well-placed breakpoint). I've never written an extension for VS2012, so I can't comment on that, but I know it's quite close to VS2013 in most respects.
So, one possible solution(I believe this one works):
1) Create your own content type which inherits from csharp.
2) Create new TextViewCreationListener which will swap out all "csharp" content types with your own one, thus potentially "disarming" all the other classifiers.
3) Register your classifier to handle your own content type.
Here is some of the code:
[Export(typeof(IVsTextViewCreationListener))]
[ContentType("csharp")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
class TextViewCreationListener : IVsTextViewCreationListener {
internal readonly IVsEditorAdaptersFactoryService _adaptersFactory;
[Import] internal IContentTypeRegistryService ContentTypeRegistryService = null;
[ImportingConstructor]
public TextViewCreationListener(IVsEditorAdaptersFactoryService adaptersFactory) {
_adaptersFactory = adaptersFactory;
}
#region IVsTextViewCreationListener Members
public void VsTextViewCreated(VisualStudio.TextManager.Interop.IVsTextView textViewAdapter) {
var textView = _adaptersFactory.GetWpfTextView(textViewAdapter);
var myContent = ContentTypeRegistryService.GetContentType(MyContentType);
if(myContent == null)
{
ContentTypeRegistryService.AddContentType(MyContentType, new[] {"csharp"});
myContent = ContentTypeRegistryService.GetContentType(MyContentType);
}
// some kind of check if the content type is not already MyContentType.
textView.TextBuffer.ChangeContentType(myContent, null);
}
#endregion
}
And now, just modify your IClassifierProvider to register with your own content type, as such: [ContentType(MyContentType)]
Iin your own IClassifier, you can basically do your own calculation and once you think you can't handle the stuff, you could pass the control to other classifiers.
If you use MEF and import IClassifierAggregatorService, you can get a "MASTER-classifier" which will run all the logic for you. I haven't implemented it yet, but I've suggestes something similiar in the past, and it seemed to work. Alternatively you could maybe use [ImportMany] with List<IClassifier> and filter out the csharp ones?!
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...
I have a MVC Web Application using the following approach:
public class MyController : Controller
{
public FooRepository fooRepository = new FooRepository();
public BarRepository barRepository = new BarRepository();
public ActionResult UpdateItems(int id, int range1, int range2)
{
Foo foo = fooRepository.GetItem(id);
List<Bar> bars = barRepository.GetItemsByRange(range1, range2);
// Some validation rules here...
DoSomeWork(foo, bars);
// Show confirmation / error message
}
private void DoSomeWork(Foo foo, List<Bar> bars)
{
foreach(int i = 0; i < bars.Count; i++)
{
bars[i].Prop1 = foo.Prop1; // This field is updated
bars[i].Owner = "someuser"; // This one too
bars[i].Status = BarStatus.SomeStatus; // This isn't...
}
foo.Status = FooStatus.SomeStatus; // Ok
// Calls DataContext.SubmitChanges()
fooRepository.SubmitChanges();
barRepository.SubmitChanges();
}
}
However, in some "random" cases (I see no pattern), one of the fields doesn't get updated, as noted in the comments.
It seems like LINQ isn't recognizing the field's update, so it gets excluded from the generated query.
Can anyone tell me if I'm missing something here, what could be causing it and/or how can I solve it?
Note: I don't get any Exception and can't verify this case in a development scenario.
From my experience if the error is random and you can't reproduce in development than the problem is user error.
Programming would be really hard if the .net framework or the CLR just randomly decided to do things differently.
You probably have an implicit/explicit bind exclusion floating around somewhere
[Bind(Exclude="...,Status,...")]
Just guessing of course
If Linq thinks that the Status is already BarStatus.SomeStatus, then it won't update it.
What can happen is that you find a record with the status set to this value, and then some other routine changes it, and then, if you are using your same DataContext, you will get the old value from the cached copy and hence Linq thinks that it does not need to update it.