It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I know this is a simple question, but I can't find an example anywhere. Please think of this as helping out a newbie. I need to create a singleton class so I can access a dictionary of BitmapImages across multiple files.
The dictionary is:
ConcurrentDictionary<string, BitmapImage> PlantImageDictionary;
Could someone please post an example of how to create/instantiate this?
Could someone please post an example of how such a dictionary would be called?
Thanks in advance.
If you're just going to be reading from the dictionary, you don't need ConcurrentDictionary. In fact, I wouldn't recommend exposing a Dictionary at all. Rather, I'd expose the minimum number of methods you need. If all you want is the ability to look something up by key, then supply just that method.
Here's a very simple singleton that will do what you're asking for.
public sealed class ImageCache
{
private static readonly Dictionary<string, Bitmap> Images;
static ImageCache()
{
Images = new Dictionary<string, Bitmap>();
// load XML file here and add images to dictionary
// You'll want to get the name of the file from an application setting.
}
public static bool TryGetImage(string key, out Bitmap bmp)
{
return Images.TryGetValue(key, out bmp);
}
}
You probably should spend some time studying the Singleton pattern and looking at alternatives. Whereas the above will do the job, it's not the best practice. One glaring problem, for example, is that it needs outside knowledge of the XML file's location, making it somewhat difficult to fit into a testing framework. There are better alternatives, but this should get you started.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am looking to generate programmaticaly a list of concrete nouns, an associated picture and if possible a sentence describing the proper noun.
I have tried various dictionary APIs - but the first part of the problem - getting a list of concrete nouns has caused me difficulty. Can anybody think of a good way of achieving this I would be very interested in hearing about it!
Please be aware I know what hashmaps are - and storing this data is not my problem - more sourcing the data is what I need help with - WHERE do I get a list of concrete nouns I can progrmmatically iterate over.
Cheers
NLTK has a part of speech tagger. You could run it on a piece of text and store all the nouns it identifies as your list.
If you want a list of all nouns, you might be in for a long hunt - you'd have to run through every dictionary, encyclopedia, atlas and baby names book in the English language. A more reasonable place to start would be this list of 2336 nouns of various kinds. They reckon it's short of a complete list by 50,000 or so - and my bet is that's an underestimate.
If you want to do in Java
You can use HashMap to store the data; where key can be proper noun and value an object which has other details
HashMap<String, ProperNounObj> obj = new HashMap<String, ProperNounObj>();
where ProperNounObj class has attributes like picutureUrl and description
List of proper noun can be generated by hashmap method obj.keySet(); this will return a set of all proper noun.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have on text s this lines:
myData = myData.Replace(".jpg", ">JPG<");
myData = myData.Replace(".gif", ">GIF<");
myData = myData.Replace(".png", ">PNG<");
myData = myData.Replace(".tif", ">TIF<");
and on my C# program i wont one by one, on a cicle for:
for (int l=0; w<listWithLines.Count;l++)
{
// MY LINE
// listWithLines[l]
}
If your intention is just to do string replacement (as in the example lines), and you are able to modify the text list, the best approach would be to provide just the replacement tokens in the list:
.jpg,>JPG<
.gif,>GIF<
.png,>PNG<
.tif,>TIF<
Then your C# code can be modified like this:
for (int l=0; w<listWithLines.Count;l++)
{
string[] strTokens = listWithLines[l].Split(',');
// MY LINE
myData = myData.Replace(strTokens[0], strTokens[1]);
}
I dont think you can do that, you can compile a block of code from an external source using CodeProviders etc but I dont think you can just drop it into a predefined scope like you seem to want to (the scope being within your for loop), unless you can load it as a block and pass it in to a method (which would do the loop) as an Action.
I'm not aware of an easy way to compile and run lines of code from a text file this way. But if you were to provide methods for myData objects to be serialized and deserialzed using XML you could read in lines from an external file to do something similar to this.
You could maybe do that but it's lot of work with things like Reflection.Emit. Pretty sure you'd have to an entire class as well
You could use IronPython or one of the other DLR implementations to do it, but would be a good bit of work as well
Turn it into an xml
<Replaces>
<Replace from=".jpg" to=">JPG<" />
<Replace from=".gif" to=">GIF<" />
</Replaces>
Then do something like
XmlDocument doc = new XmlDocument();
doc.Load("Replaces.xml")
foreach(XmlNode replaceNode in doc.DocumentElement.SelectNodes("Replaces/Replace"))
{
myData = myData.Replace(replaceNode.Attributes["from"].Value, replaceNode.Attributes["to"].Value);
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have created a form that gives a open file windows dialog. With this form I want to pass the filename I open to the main function in order to use the data in the file. I wish to know if I should code in the form.cs or the program.cs window!
It really depends what you are trying to achieve? If this is a simple throw-away program, either will do, whichever is easiest! If this is a program that you plan to develop for more than just a few hours and want to structure it correctly, the answer is neither!
Larger applications need to be structured in a way to support various concerns:
re-use - i.e. code can be used in different contexts. Code-behind in forms is not re-usable (unless you use static methods - yuck)
testable - code behind forms cannot be executed by unit tests
separation-of-concerns - you should try to separate out code that performs a single specific function into its own class, this will promote re-use and enable testing.
I would recommend learning about the Model-View-Presenter, or some other MVx pattern.
It is pretty unclear why you have a Form but ask for an OpenFileDialog to return the selection to the Main() method. I'm guessing you simply don't need that form. Just use the class directly in your Main method. Like this:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var dlg = new OpenFileDialog();
// Set dlg properties
//...
if (dlg.ShowDialog() == DialogResult.OK) {
// Do something with dlg.FileName
//...
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
How would you name an interface which provides 1 method inUse()?
I would actually reconsider the name 'inUse()' in the first place; A boolean value obviously has only two possible values, but you're actually adding the ability to get a state. I'd consider declaring an enum
public enum UsageState
{
Idle,
InUse
}
and name your interface IHasUsageState. This gives you the flexibility of adding things like Starting, Finishing, WaitingToBeUsed or other options depending on precisely what is is you're doing, for example if you have threading issues to deal with in the future.
Also, you eliminate the need for negative checks like if (!obj.InUse()) { } in favor of the more readable and intuitive if (obj.Usage == UsageState.Idle) { }, not to mention you may decide in the future that you might want it to specify WHY it's idle.
IUsageIndicator if you want to show that your object is currently in use or not.
IUsable if you want to show that your object can be used or not.
I would name it. IInUse. Looks good...
I would prefer to name it as IUsable keeping in mind the standard conventions that MS follows. (Eg: IEnumerable, IComparable etc)
I would prefer
InUsable. Sounds everlasting.
see here
I would name it. IUsable. Looks good...
This is what I would have done in Java
public interface Usable {
public boolean inUse();
}
It should start with Uppercase 'I', so the interface name becomes in your case IInUse.
Follow the C# coding standards over here.
How about IExclusiveUseObject?
are you looking for answers for both c# and java?
As a c-sharper, I prefix with "I" and most c# developers I talk to do also, probably because it's in the microsoft naming conventions.
However interestingly when search around for java naming conventions I see a mix of prefixed and no prefix.
So in c# perhaps something like:
public interface IUsable {
void InUse();
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I'm just asking this, because the same happened to me when trying to iterate over a DataRowCollection:
DataSet s;
...
foreach (var x in s.Tables[0].Rows)
{
//IntelliSense doesn't work here. It takes 'x' as an object.
}
I saw #Marc Gravell answer in Why is there no Intellisense with 'var' variables in 'foreach' statements in C#?, and now it's clear to me why this is happening.
I decided to take a look at the code of the DataRowCollection class, and GetEnumerator() is:
return this.list.GetEnumerator();
where list is a DataRowTree type that inherits the abstract class RBTree<K> (by the way, never knew there was an implementation of a Red-Black Tree in .NET before) which implements IEnumerable instead of IEnumerable<K>.
Is too hard to make RBTree<K> implement IEnumerable<K>? That would solve the main problem here.
I suppose it was developed like this in previous versions of .NET, but that doesn't really make sense anymore, does it?
My question is:
Is .NET old code updated in new releases? (for example, make DataRowCollection implement IEnumerable<DataRow> instead of IEnumerable)
Breaking changes, such as changing the class hierachy, is only implemented if there's a really good reason. In this case it's only for convinience.
An example of why it's a breaking change:
Let's say a project has these two methods.
public void Foo(object obj){
Console.WriteLine(obj.ToString();
}
public void Foo<T>(IEnumerable<T> obj){
throw new Exception();
}
now the change you want will make a program that has been recompiled but not changed throw an exception every time instead of printing to the console. It's not that it throws that's the problem but that the behaviour is different.
There's other ways such a change could break/alter a perfectly good program so the benefits (being able to write var in foreach loops) does not outweigh the cost (designing, implementing,testing,documenting), nor the potential costs of breaking customers work.