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... ;)
Related
In my application, different canvases are stored as "pages", the contents of each canvas is stored as "cells".
Now when I want to load all cells that occupy / make up one canvas, I retrieve them like this:
public Task<List<Cell>> GetCellsAsync(string uPageGUID)
{
return database.QueryAsync<Cell>("SELECT * FROM cells WHERE cellpageguid = ?", uPageGUID);
}
This works great.
Now I would like to find out the "pageguid" of the page that has the value "pageisstartpage" set to true.
Therefore I'm trying the following:
public Task<string>GetStartPageGUID()
{
nPages<List<Page>>=database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);
return nPages.First.GUID;
}
The compiler tells me:
nPages doesn't exist in the current context.
I don't see where I made a mistake.
nPages doesn't exist in the current context....I don't see where I made a mistake.
The first thing to mention is that the declaration of the List<Page> seems backwards.
nPages<List<Page>>=database....
The type has to be written first followed by the variable name.
List<Page> nPagesTask = database...
Another interpretation could be that you have a generic type variable nPages in which you want to specify the generic type. So the compiler looks whether this variable has already been declared. And apparently it cannot find any.
The second thing If you have an async method that returns a Task<string> you could do the following:
public async Task<string>GetStartPageGUID()
{
Task<List<Page>> nPagesTask = database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);
List<Page> npages = await nPagesTask;
return nPages.First().GUID;
}
Here is the source of the QueryAsync method. this is the signature:
public Task<List<T>> QueryAsync<T> (string query, params object[] args)
so it returns a Task<List<T>>. Since your method specifies a different return type the usual pattern is to await it in a async method as described in the MSDN example and then return the type that you specified in you method.
You have to declare nPages correctly:
List<Page> nPages = database.QueryAsync<Page>("SELECT * FROM pages WHERE pageisstartpage=?", true);
I have a class in my program of which I want only one copy. I don't want to use the Singleton pattern though for a couple of reasons (* see below). I know that I'll only have one copy of the class because I'll be the only one calling its constructor.
In my class's constructor, I want to check that only one copy of the class will exist and throw an exception if more than one exists. Is the code below a good pattern to use for this case?
public class MySingletonAlternative : IDisposable
{
private static int _count = 0;
public MySingletonAlternative()
{
int newValue = System.Threading.Interlocked.Increment(ref _count);
if (newValue > 1)
{
throw new NotImplementedException();
}
}
public void Dispose()
{
int newValue = System.Threading.Interlocked.Decrement(ref _count);
if (newValue < 0)
{
throw new ObjectDisposedException("MySingletonAlternative");
}
}
}
* Why I don't want to use a Singleton:
I want to be able to control when the class is created. In the traditional C# Singleton pattern, construction happens non-deterministically.
I want to avoid global variables.
When I'm debugging my code and an exception is raised in the Singleton's private constructor, Visual Studio highlights the exception, but it highlights the wrong line of code, usually in a different file.
I don't want to create this object lazily (using Lazy<T>). One instance of this class will exist for the life of my application. I gain nothing by constructing it lazily.
Use a IoC Container like an UnityContainer. It will erase all of your points you've mentioned why you don't want to use a Singleton (in the means of global variables or static). You will be able to fully controll the creation of your lifetime-instance and inject it into all classes that will need to use this.
Can you use dependency injection and then have the di container manage the lifetime of the class you want to create? an example is with Unity and the ContainerControlledLifetimeManager
http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec34
DON'T USE THIS CODE BELOW IN REAL APPLICATIONS! It's just for demo purposes.
I guess it's not a good way, but it looks like that your approach will work just fine. I am not aware of edge cases though.
Just created a little test app to create 1 million instances in a for loop and count
the exceptions it raises.
In this case it should be: 1 instance successfully created and 999.000 exceptions raised.
I ran the test app a couple of times and it always returned 999.000.
Depending on your machine this code could take some time to finish,
cause it throws 999.000 exceptions.
public static volatile int _global_Exception_count = 0;
static async Task Main(string[] args)
{
_global_Exception_count = 0;
var list = Enumerable.Range(1, 1000000).ToList();
var tlist = list.Select(async item =>
{
MySingletonAlternative current = null;
try
{
current = new MySingletonAlternative();
}
catch (Exception ex) { System.Threading.Interlocked.Increment(ref _global_Exception_count); }
return await Task.FromResult(0);
});
await Task.WhenAll(tlist);
Console.WriteLine(_global_Exception_count);
}// end main
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."
I am new to developing in .NET and C#, but have been a long-time developer, working with C, C++, Java, PHP, etc.
I have an MVC3 extension class for my data models that refers to the database. It is set as "private static" in the class, but I think that it is not keeping up with database changes. In other words, when I change data in the controllers, those changes aren't "noticed" in the db because it is static. Currently, I am creating and disposing of the variable for each use, to compensate.
My questions are:
Am I correct that a static db variable could behave that way?
Is it necessary to dispose of the dynamic variable in the static class, or will garbage collection still take care of it automatically?
Here is a relevant snippet of the class:
namespace PBA.Models {
using System;
using System.Text.RegularExpressions;
using PBA.Models;
using PBA.Controllers;
public static class Extensions {
private static PbaDbEntities db = null;
public static PbaDbEntities GetDb() {
// TODO: find out about static memory/disposal, etc.
//
if (db != null) {
db.Dispose();
}
db = new PbaDbEntities();
return db;
}
public static string GetCheckpointState(this Activity activity, long memberProjectId) {
GetDb(); // TODO: Do I need to do this each time, or will a one-time setting work?
string state = CheckpointController.CHECKPOINT_STATUS_NOT_STARTED;
try {
var sub = db.ActivitySubmissions.
Where(s => s.activityId == activity.activityId).
Where(s => s.memberProjectId == memberProjectId).
OrderByDescending(s => s.submitted).
First();
if (sub != null) {
state = sub.checkpointStatusId;
}
}
catch (Exception e) {
// omitted for brevity
}
return state;
}
}
}
Your code will fail horribly in production.
DataContexts are not thread-safe; you must not share a context between requests.
Never put mutable objects in static fields in multi-threaded applications.
Ignoring exceptions that way is a terrible idea, if you don't want to handle exceptions just don't try/catch, or catch & rethrow. Think about it like this, after you've buried the exception, your program is in an invalid state, b/c something you have no control over error'd out. Now, b/c you've buried the exception, your program can continue to operate but it's in a bad state.
If your code makes it to production, 3.5 yrs from now some jr. programmer is going to get involved in some middle of the night firestorm because all of a sudden the website is broken, even though it used to work. It will be completely impossible to track down where the exception is happening so, this poor guy is going to spend 48 straight hours adding logging code all over the place to track down the problem. He will find that some DBA somewhere decided to rename the column MemberProjectId to MemberProjectIdentifier, which caused your linq to blow up.
Think of the children, handle exceptions, don't bury them.
btw - yes, i have been that guy that has to figure out these types of mistakes.
It seems like you need to read about mvc3 and entity framework before writing coding and asking in here for help on something that's coded full of bad practices.
Answering your questions:
1- no
2- makes no sense as the answer to 1
Do it right, here are some useful documentation: http://msdn.microsoft.com/en-us/library/ie/gg416514(v=vs.98).aspx
EDIT: Adding some explicit fix
You could access your dbcontext from an static class, something like this:
var context = DbProvider.CurrentDb;
The idea is to access your db from here always: from your extension methods and from your controller actions.
Then, the implementation of the DbProvider.CurrentDb will be something like this:
public static classDbProvider {
public static void Initialize(){
HttpContext.Current.ApplicationInstance.BeginRequest += CreateDb;
HttpConetxt.Current.ApplicationInstance.EndRequest += DisposeDb;
}
private static void CreateDb(object sender, EventArgs e) {
HttpContext.Items.Add("CurrentDb", new PbaDbEntities(););
}
private static void DisposeDb(object sender, EventArgs e)
{
Current.Dispose();
HttpContext.Items.Remove("CurrentDb");
}
public static PbaDbEntities CurrentDb{
get {
return (PbaDbEntities)HttpContext.Current.Items["CurrentDb"];
}
}
}
As you can see, it will create a new Db per each request and it will be available ONLY in that request. In that way, your db will be disposed at the end of each request. This pattern is called Open-Session-in-View.
Finally, you need to initialize the DbProvider calling the method
Initialize() in your Global.asax file, in the event Application_start.
Hope it helps.
I don't have any idea of the context here-- if db is simply a connection-like object or not, but it appears you are throwing away and recreating whatever it is unnecessarily.
Best to create a property (for whatever your doing) so to be consistent.
private static Thing _thing;
private static Thing thing{
get{
if(_thing==null){
_thing=new Thing();
}
return _thing;
}
}
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.