compile and execute lines of code from txt in C# [closed] - c#

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);
}

Related

Example of a singleton class with a dictionary of BitmapImages [closed]

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.

can storing data in a database sometimes lead to corrupted data? [closed]

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 a field that's stored in the database as a string. It's actually a comma-separated string of numbers that I convert to a list of longs. The lines of code that do the conversion look somewhat like this:
TheListOfLongs = (from string s in StringFromDB.Split(',')
select Convert.ToInt64(s)).ToList<long>();
The code that creates the database storage string looks like this:
return String.Join(",", TheListOfLongs.Select(x=> x.ToString()).ToArray());
This works fine but as you can see, if for some reason there's a problem with the string, the code in the first line of code breaks on Convert.ToInt64(s).
Now I know I can wrap all this around a try statement but my question is this: can storing and retrieving a string in the database corrupt the string (in which case I definitely need the try statement) or is this a one a trillion odd type of event?
I wouldn't worry about corrupt data per se. However, you definitely need to handle the more general case where you can't parse what should be numeric data.
Even in the most controlled situations it is good programming practice to provide conditions for when you can't process data as you're expecting to be able to. What that means to your application is something you'll need to decide. Wrapping the statement with a try..catch will prevent your application from choking, but may not be appropriate if the parsed list is critical later on.
Selecting from the DB shouldn't corrupt your string.
If the connection is dropped mid transfer or something like that then an exception is thrown.

I am looking to generate a list of Concrete nouns....with picture and associated sentence [closed]

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.

What algorithm can break text up into its component words? [closed]

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 was pleasantly surprised to find how easy it is to use iTextSharp to extract the text from a pdf file. By following this article, I was able to get a pdf file converted to text with this simple code:
string pdfFilename = dlg.FileName;
// Show just the file name, without the path
string pdfFileNameOnly = System.IO.Path.GetFileName(pdfFilename);
lblFunnyMammalsFile.Content = pdfFileNameOnly;
string textFilename = String.Format(#"C:\Scrooge\McDuckbilledPlatypus\{0}.txt", pdfFileNameOnly);
PDFParser pdfParser = new PDFParser();
if (!pdfParser.ExtractText(pdfFilename, textFilename))
{
MessageBox.Show("there was a boo-boo");
}
The problem is that the text file generated contains text like this (i.e. it has no spaces):
IwaspleasantlysurprisedtofindhoweasyitistouseiTextSharptoextractthetextfromatextfile.
Is there an algorithm "out there" that will take text like that and make a best guess as to where the word breaks (AKA "spaces") should go?
Though I agree with Gavin that there's an easy way to solve this problem in this case but the problem itself is an interesting one.
This would require a heuristic algorithm to solve. I will just explain in a bit on why I think so. But first, I'll explain my algorithm.
Store all the dictionary words in a Trie. Now take a sentence, and look up in the trie to get to a word. The trie tracks the end of the word. Once you find a word, add a space to it in your sentence. This will work for your sentence. But consider these two examples:
He gave me this book
He told me a parable
For the first example, the above algorithm works fine but for the second example, the algorithm outputs:
He told me a par able
In order to avoid this, we will need to consider a longest match but if we do that then the output for the first example becomes:
He gave met his book.
So we are stuck and hence add heuristics to the algorithm that will be able to judge that grammatically He gave met his book doesn't make sense.

Is .NET old code updated in new releases? [closed]

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.

Categories