Quest: Using Resource in C# app...

  • Thread starter Thread starter bj7lewis
  • Start date Start date
B

bj7lewis

I am working on a project I want to add a few files as resource to
access(copy them to FS and use) at runtime.

So far in VS.NET IDE, I Add Files to the project and set its Build Action to
Embedded Resource...

Now where should look next...

Any help...
 
Does this help?

public static Image RetrieveResourceImage(Assembly assembly, string
resourceName)
{
Image image = null;
try {
using (Stream stream = RetrieveResourceStream(assembly, resourceName)) {
if (stream != null) {
image = Image.FromStream(stream);
}

stream.Close();
}
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(string.Format("RetrieveResourceImage({0})
Exception> {1}", resourceName, ex.Message));
throw;
}

return image;
}

Frisky
 
public static Image RetrieveResourceImage(Assembly assembly, string
[and]
using (Stream stream = RetrieveResourceStream(assembly, resourceName))
{
What is this?...

Image is drawing class or Image ctrl class and can't find
RetrieveResourceImage(...) on MSDN or whole MSN INET search...

Any more help...
 
Whoopsss.... :)

You might need this too...

public static Stream RetrieveResourceStream(string resourceName)
{
return RetrieveResourceStream(Assembly.GetEntryAssembly(), resourceName);
}

public static Stream RetrieveResourceStream(Assembly assembly, string
resourceName)
{
try {
return assembly.GetManifestResourceStream(resourceName);
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(string.Format("RetrieveResourceStream({0})
Exception> {1}", resourceName, ex.Message));
return null;
}
}

Basically, you are calling assembly.GetManifestResourceStream(). (There are
other versions.)

Bonus:
The biggest problem most people have is with the resource names. (I don't
think it is documented very well.) For that, use this snippet of code to
iterate all the names of all the resources in your assembly.

Hope this helps...

public static void DebugIterateResources(Assembly assembly) {
string[] resources = assembly.GetManifestResourceNames();
System.Diagnostics.Debug.WriteLine("Resources for assembly: " +
assembly.GetName());
int index = 0;
foreach (string resource in resources) {
System.Diagnostics.Debug.WriteLine("Resource " + index + ": " +
resource);
index++;
}
}


Frisky

bj7lewis said:
public static Image RetrieveResourceImage(Assembly assembly, string [and]
using (Stream stream = RetrieveResourceStream(assembly,
resourceName))
{
What is this?...

Image is drawing class or Image ctrl class and can't find
RetrieveResourceImage(...) on MSDN or whole MSN INET search...

Any more help...
 
Whoopsss.... :)
Thanks that help and I will try it out...
Sorry, I guess Image was meant to be a image(pic) obj to represent a picture
resource in the exe...
 
Frisky said:
Whoopsss.... :)

You might need this too...

public static Stream RetrieveResourceStream(string resourceName)
{
return RetrieveResourceStream(Assembly.GetEntryAssembly(), resourceName);
}

public static Stream RetrieveResourceStream(Assembly assembly, string
resourceName)
{
try {
return assembly.GetManifestResourceStream(resourceName);
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(string.Format("RetrieveResourceStream({0})
Exception> {1}", resourceName, ex.Message));
return null;
}
}

Why return null rather than throwing the exception? Exceptions should
usually be used rather than special return values to indicate things
going wrong - as it is, at each level you're going to have to check for
nullity, which makes the purpose of the code less clear. You're also
losing the stack trace when you're logging the exception, so if you
have several calls to this, it could be hard to see which one of them
went wrong.
 
Jon,

This is an exert of a complete utility class I have for managing resources.
I only yanked out part to give some hints on where to start.

The utility class supports both. That is there is an equivalent function to
throw, and to receive a null value.

Exceptions depends on their intent. Are you expecting them, or you expecting
not to get them? Exceptions have a high overhead. So, for efficiency sake,
if you are expecting execute an operation 1000 times, and expect 500
failures, and you are not concerned with the failures, then checking for
null is much more efficiect. If you are expecting to load 1000 images, and
they better all be there, I would go with the expception. Which is why I
have both forms in my library.

To get a relation as to how heavy, if you were to right an application that
simply calls a method that thows, and catch that 10000 times, how long would
it take? (On my machine, just over 20 seconds.) If you now right an
application that calls a method that makes a mathmatical calculation, and
then returns null, it checks the result and then either way performs another
mathmatical calculation. On my machine that takes 0.0006953 seconds for
10000. To me, there is no contest. Use Exceptions judiciously.

As far as the stack trace goes, you will still get a trace from a point of
failure that would point you to the culprit. But, this is a good point.
Another reason why I offer both methods.
 
Frisky said:
This is an exert of a complete utility class I have for managing resources.
I only yanked out part to give some hints on where to start.

The utility class supports both. That is there is an equivalent function to
throw, and to receive a null value.

Exceptions depends on their intent. Are you expecting them, or you expecting
not to get them? Exceptions have a high overhead. So, for efficiency sake,
if you are expecting execute an operation 1000 times, and expect 500
failures, and you are not concerned with the failures, then checking for
null is much more efficiect.

True - but in my experience when you're asking for resources, you
really want to know if they're not there - it's almost certainly a
major problem. How often in real life do you ask for a resource which
isn't present? Aren't you specifically asking for resources with hard
coded constant names which you've put in there yourself? That's almost
always the situation in my experience.

To get a relation as to how heavy, if you were to right an application that
simply calls a method that thows, and catch that 10000 times, how long would
it take? (On my machine, just over 20 seconds.)

That seems unlikely to me. My laptop can throw nearly 100,000
exceptions in 1 second in release mode. When debugging things are very
different, but performance while running in a debugger isn't that
important IMO.

Try the following program:
using System;

public class Test
{
static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 1000000; i++)
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

On my box, the result is 11.14 seconds - about 89,000 exceptions per
second. That means that in the rare case where you want to catch
exceptions from resource loading and keep going (rather than reporting
an error - the usual case where only one exception will be
thrown/caught) it would take about 5ms. Just how often are you
expecting to do that within the lifetime of the app?
If you now right an
application that calls a method that makes a mathmatical calculation, and
then returns null, it checks the result and then either way performs another
mathmatical calculation. On my machine that takes 0.0006953 seconds for
10000. To me, there is no contest. Use Exceptions judiciously.

You're vastly overestimating the cost of exceptions, IMO. Besides, I'd
far rather have a program which gave an exception at the first point of
failure than one which carried on with bad data because someone forgot
to check a return value - something which is very easy to do.

(If it's really taking 0.0006953 seconds to check for nullity 10,000
times, either you've got a slow machine or you're measuring things
oddly... on my box it takes 0.00004687 seconds (measured over
100,000,000 and scaled) - it seems unlikely that your machine is a
tenth the speed of my laptop.)
As far as the stack trace goes, you will still get a trace from a point of
failure that would point you to the culprit. But, this is a good point.
Another reason why I offer both methods.

No, you wouldn't get a trace from the real point of failure. You'd get
a trace from the first place where the null reference was used. That
could be much further down the line - especially if you pass the
reference to methods which *can* legally take null values, but you
don't want to pass null in this particular situation.

I *must* get round to writing up the true cost of exceptions as an
article some time - there's such a myth around how slow they are...
 
Intellectuals solve problems; geniuses prevent them. ~ Albert Einstein
Jon Skeet said:
True - but in my experience when you're asking for resources, you
really want to know if they're not there - it's almost certainly a
major problem. How often in real life do you ask for a resource which
isn't present? Aren't you specifically asking for resources with hard
coded constant names which you've put in there yourself? That's almost
always the situation in my experience.

You are correct. This is the general scenario. But then I had to write a
utility that iterates through external resource files based on information
in a database. (I did not create that monster. I guess they though resource
files were a clever way to store things. :)

Anyway, the application gathers up the resources which do exist. Many had
been removed by a "spring cleaning" process. The original application took
some time to run. A simple change to my resource utility, to have it check
for null instead of throw, made the application run in a couple of seconds.
That seems unlikely to me. My laptop can throw nearly 100,000
exceptions in 1 second in release mode. When debugging things are very
different, but performance while running in a debugger isn't that
important IMO.

Try the following program:
using System;

public class Test
{
static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 1000000; i++)
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

On my box, the result is 11.14 seconds - about 89,000 exceptions per
second. That means that in the rare case where you want to catch
exceptions from resource loading and keep going (rather than reporting
an error - the usual case where only one exception will be
thrown/caught) it would take about 5ms. Just how often are you
expecting to do that within the lifetime of the app?

Again, refer above to the application for this was written. But the fact
remains, it took seconds. The null checks with mathmatical callculations was
less than 1 ms. for the same number. That is to the order of 10,000 times
faster. This holds up in both realease and in debug. Although you are
correct that in release mode you can throw a lot more them. :)

IMO: I don't want to sitting around all day way on the debugger. I had just
assume write the code once, and have it work in either arena as efficiently
as possible while maintaining minimal complexity.
You're vastly overestimating the cost of exceptions, IMO. Besides, I'd
far rather have a program which gave an exception at the first point of
failure than one which carried on with bad data because someone forgot
to check a return value - something which is very easy to do.

(If it's really taking 0.0006953 seconds to check for nullity 10,000
times, either you've got a slow machine or you're measuring things
oddly... on my box it takes 0.00004687 seconds (measured over
100,000,000 and scaled) - it seems unlikely that your machine is a
tenth the speed of my laptop.)

First, I noticed that you were using DateTime in your profiling code. This
is not an accurate timer at the ms level you are timing. For seconds it
works fine. You have to use the windows high resolution counters or
performance monitors. Mine is not the fastest in the world. I have not
purchased a new machine in a little over a year. But that's ok, it works
just fine for me.

As indicated though, I was not just checking for null. (Not a fair test.)
So, I added a mathemetical computation to the mix. This was done in the
procedure and on success or failure of the null check. This was not included
in the exception test. It already has enough against it.

None the less, this just ups the factor by which you can save time.
No, you wouldn't get a trace from the real point of failure. You'd get
a trace from the first place where the null reference was used. That
could be much further down the line - especially if you pass the
reference to methods which *can* legally take null values, but you
don't want to pass null in this particular situation.

I *must* get round to writing up the true cost of exceptions as an
article some time - there's such a myth around how slow they are...

And, if I was checking for null, I would know exaclty who gave me the
invalid value. To me, that is point of failure. If I don't want to check for
null, how about at least an assert?

I really don't want to spend my life worrying about exceptions and stack
traces over something that I can easily handle another way.

I remember a system from years ago that we wrote in C++. One of the project
goals was to make all errors exceptions. That ended up being the wrong
choice. What a nightmare. The code jumped all over the place. Because of the
exceptions and exception handling the code became complex and tedious to
debug. A year later we re-wrote the system. During the rte-write we
judiciously removed exceptions. We ended up with a much higher performance
system, that was much more maintainable and easier to understand.
[/QUOTE]
 
Frisky said:
You are correct. This is the general scenario. But then I had to write a
utility that iterates through external resource files based on information
in a database. (I did not create that monster. I guess they though resource
files were a clever way to store things. :)

I'd say that's the exception (no pun intended) rather than the rule
though.
Anyway, the application gathers up the resources which do exist. Many had
been removed by a "spring cleaning" process. The original application took
some time to run. A simple change to my resource utility, to have it check
for null instead of throw, made the application run in a couple of seconds.

So in this one odd situation, it's the better solution - but I wouldn't
suggest using it normally.
Again, refer above to the application for this was written.

That's not the app you were giving advice for though :)
But the fact remains, it took seconds. The null checks with
mathmatical callculations was less than 1 ms. for the same number.
That is to the order of 10,000 times faster. This holds up in both
realease and in debug. Although you are correct that in release mode
you can throw a lot more them. :)

And the point is that in practice you *don't* actually throw a lot more
of them. As I said above, if your app is *actually* throwing that many
exceptions, it suggests deeper problems where you shouldn't be using
exceptions. The reason for not using exceptions in that case isn't
because of performance - it's because you're clearly not handling an
exception case, you're handling a common one.
IMO: I don't want to sitting around all day way on the debugger. I had just
assume write the code once, and have it work in either arena as efficiently
as possible while maintaining minimal complexity.

When was the last time you actually had code which threw several
thousand exceptions (in a relatively short space of time) either in the
debugger or out of it? I suggest that if you get into that situation
often, you have more drastic worries than waiting for the debugger.
First, I noticed that you were using DateTime in your profiling code. This
is not an accurate timer at the ms level you are timing. For seconds it
works fine.

And that's the kind of precision I was working at - nearly half a
second for the 100,000,000 cycles, which is enough to give an order-of-
magnitude figure, which is what we're interested in here. Any test
which *actually* relies on timing so small that the high precision
timer is required is probably going to be influenced too heavily by
JITting etc to be much use.
You have to use the windows high resolution counters or
performance monitors. Mine is not the fastest in the world. I have not
purchased a new machine in a little over a year. But that's ok, it works
just fine for me.

As indicated though, I was not just checking for null. (Not a fair test.)
So, I added a mathemetical computation to the mix. This was done in the
procedure and on success or failure of the null check. This was not included
in the exception test. It already has enough against it.

None the less, this just ups the factor by which you can save time.

Only if you don't also rerun the exception test - and in release mode
this time.
And, if I was checking for null, I would know exaclty who gave me the
invalid value. To me, that is point of failure. If I don't want to check for
null, how about at least an assert?

You know exactly what gives you the exception when you look at the
stack trace.
I really don't want to spend my life worrying about exceptions and stack
traces over something that I can easily handle another way.

Whereas I *certainly* don't want to spend my life checking return
values over something (error handling) that I can easily handle another
way - using exceptions.
I remember a system from years ago that we wrote in C++. One of the project
goals was to make all errors exceptions. That ended up being the wrong
choice. What a nightmare. The code jumped all over the place. Because of the
exceptions and exception handling the code became complex and tedious to
debug. A year later we re-wrote the system. During the rte-write we
judiciously removed exceptions. We ended up with a much higher performance
system, that was much more maintainable and easier to understand.

That doesn't prove that exceptions are a bad thing, just that they can
be abused like anything else. That story could easily have been the
other way round, couldn't it?
 
At this point, I think we have beaten this horse to death.

However, we have not yet achieved the maximum number of posts, the maximuim
depth on a post, or maximum number of bytes in a reply either. So, nntp on
dude ... :)

Intellectuals solve problems; geniuses prevent them. ~ Albert Einstein
Jon Skeet said:
I'd say that's the exception (no pun intended) rather than the rule
though.

It does not make it any less viable a tactic. For resources though, I am
with you. That was purely based on need. As explained.
So in this one odd situation, it's the better solution - but I wouldn't
suggest using it normally.

Funny, but I just use the methods that throw when I need that, and the
methods that return null when I need that. Neither is better than the other.
They just have different uses.
That's not the app you were giving advice for though :)

Actually, I was not giving advice on an application. The questions was,
(para-phrased) files have been added to the project, but I don't know how to
access them. My code suficed this answer and showed some quasi
implementation. And with the message "does this help?" I think it answers
the question fine. (Other than my mistake of grabbing only part of the code
out of a huge utility class in an attempt to be quick.)
And the point is that in practice you *don't* actually throw a lot more
of them. As I said above, if your app is *actually* throwing that many
exceptions, it suggests deeper problems where you shouldn't be using
exceptions. The reason for not using exceptions in that case isn't
because of performance - it's because you're clearly not handling an
exception case, you're handling a common one.

Depends on the application. If we are sticking to the resource theme, most
applications would not have had as much code as we've written to this
newsgroup in them. :) Much less have a need to worry over the triviality of
whether to throw versus check for null. Which kind of makes this post
senseless at some level. The reality is, for resources, either method in an
application like the "generic" one you describe would not matter because, if
there is an issue, you are going to get it during development. Once you have
it working, its a "who cares".

But, that does not change the fact that one or a thousand, throwing is much
much slower, and uses more resources than checking for null.
When was the last time you actually had code which threw several
thousand exceptions (in a relatively short space of time) either in the
debugger or out of it? I suggest that if you get into that situation
often, you have more drastic worries than waiting for the debugger.

Uh, today. I ran your sample. And mine a couple of days before that. :)

Actually, I don't have that problem, because I use them where I need to, and
use checks where I need to.
And that's the kind of precision I was working at - nearly half a
second for the 100,000,000 cycles, which is enough to give an order-of-
magnitude figure, which is what we're interested in here. Any test
which *actually* relies on timing so small that the high precision
timer is required is probably going to be influenced too heavily by
JITting etc to be much use.

You did run your test twice didn't you? So that it had already been JITed. I
don't know where you get 100,000,000 throws = a half a second. Mine, in
release mode was over 1 and 1/2 seconds for 100,000. And while my box ain't
the latest, its plenty fast. It is a simple statement. Exceptions are
slower. Use them wisely.
Only if you don't also rerun the exception test - and in release mode
this time.

Release or debug, exceptions are still slower. Dramtically slower.
You know exactly what gives you the exception when you look at the
stack trace.

I know exactly what gave me null when I ask for it. I know exactly what
asserted when I asserted it. A stack trace is not something I want to resort
to unless there is a real problem at hand. When my application throws an
exception, I don't normally go look at the stack trace. I look at where the
debugger was when it threw.
Whereas I *certainly* don't want to spend my life checking return
values over something (error handling) that I can easily handle another
way - using exceptions.

To each his own. Such is life.
That doesn't prove that exceptions are a bad thing, just that they can
be abused like anything else. That story could easily have been the
other way round, couldn't it?

Ah, my point comes through. Use them judiciously I say.

And yes, I am sure you could say it could go the other. That is why I use
both.

And that is why I recommend the right one for the right use. (But we will
probably never get consensus on the "right use" or the "right one". :)
 
Frisky said:
At this point, I think we have beaten this horse to death.

Perhaps. It looks like I'm not going to persuade you that exceptions
really *aren't* a performance problem in reasonable real world apps,
and you're not going to persuade me that they are...
However, we have not yet achieved the maximum number of posts, the maximuim
depth on a post, or maximum number of bytes in a reply either. So, nntp on
dude ... :)

Well, this set of posts will be the last for the night from me - it's
already past midnight here, and I'm sure my little boy will be getting
me up in about 6 hours...
It does not make it any less viable a tactic. For resources though, I am
with you. That was purely based on need. As explained.

After prodding though - it was still the solution you suggested to the
OP :)
Funny, but I just use the methods that throw when I need that, and the
methods that return null when I need that. Neither is better than the other.
They just have different uses.

That's because you dislike exceptions though - when using exceptions is
the normal, idiomatic way of showing a very unexpected situation (such
as a resource being missing), they look very different.
Actually, I was not giving advice on an application. The questions was,
(para-phrased) files have been added to the project, but I don't know how to
access them. My code suficed this answer and showed some quasi
implementation. And with the message "does this help?" I think it answers
the question fine. (Other than my mistake of grabbing only part of the code
out of a huge utility class in an attempt to be quick.)

In my experience, people tend to use code they're presented with,
whether it's actually suitable or not, unfortunately.
Depends on the application. If we are sticking to the resource theme, most
applications would not have had as much code as we've written to this
newsgroup in them. :) Much less have a need to worry over the triviality of
whether to throw versus check for null. Which kind of makes this post
senseless at some level. The reality is, for resources, either method in an
application like the "generic" one you describe would not matter because, if
there is an issue, you are going to get it during development. Once you have
it working, its a "who cares".

Absolutely - and using exceptions, you end up with much more readable
code. In particular, you just need:

public static Image RetrieveResourceImage (Assembly assembly,
string resourceName)
{
Assembly entryAssembly = assembly.GetEntryAssembly();
using (Stream stream = entryAssembly.GetManifestResourceStream
(resourceName))
{
return Image.FromStream(stream);
}
}

No need for two extra methods which do nothing but unnecessary error
handling.

(Looking at that code now, it's not right - you're meant to keep the
stream open for the lifetime of the image, which doesn't happen in the
above; it doesn't happen in your code either though.)
But, that does not change the fact that one or a thousand, throwing is much
much slower, and uses more resources than checking for null.

Actually in this case it's not, because you're not stopping the
exception from being thrown in the first place - you're just catching
it and changing to a different error-handling solution. If higher up
the chain you decide to change back to using an exception, you've
actually just doubled the number of exceptions which need to be
thrown...

Regardless, if you're really worried about the ~0.01ms for the single
exception which is likely to halt processing of that request or
whatever anyway, I think using a platform like .NET is a bad idea
anyway. Do you avoid ever creating objects unless you absolutely have
to as well, whether or not it leads to less readable code?
Uh, today. I ran your sample. And mine a couple of days before that. :)
Touche.

Actually, I don't have that problem, because I use them where I need to, and
use checks where I need to.

So you haven't run into it as an actual problem, but you're adding lots
and lots of code doing error checking in order to avoid this supposed
problem?
You did run your test twice didn't you? So that it had already been JITed.

JITting happens every time you run the app, not just once (unless you
use Ngen).
I don't know where you get 100,000,000 throws = a half a second.

I never said that I did. I said I got 100,000,000 checks for nullity in
half a second - reread the post.
Mine, in release mode was over 1 and 1/2 seconds for 100,000. And
while my box ain't the latest, its plenty fast. It is a simple
statement. Exceptions are slower. Use them wisely.

"Premature optimization is the root of all evil (or at least most of
it) in programming." - Donald Knuth.

I'm throwing exceptions merrily and avoiding lots of return value
checking. I can hand-on-heart say that I've *never* found exceptions to
be a performance problem. It sounds like you haven't except in the very
strange situation you wrote about before. Now, doesn't avoiding
exceptions sound like premature optimisation?
Release or debug, exceptions are still slower. Dramtically slower.

Yup, but not nearly as bad as they look in debug. And they're
sufficiently fast that I just don't care, so long as my program doesn't
have the kind of problem that means I'm throwing tens of thousands of
them a minute - in which case I've got far bigger fish to fry.

Suppose my app *were* throwing 10,000 exceptions per minute, and let's
say my computer could only throw 50,000 exceptions per second (instead
of the 89,000 it can actually do.)

That still means that it would only be taking up about 0.3% of the
processor time *even in a situation where I would be very, very
concerned for other reasons*.

When looking for performance optimisations, I look for things which
will gain me an order of magnitude, or at the *very, very* least
increase performance by more than 1% (usually much more).

Out of interest, how many apps which use exceptions freely like I do
really suffer a *significant* performance problem due to it?
I know exactly what gave me null when I ask for it.

Only if you either check for null immediately. What if you forget, and
pass the parameter to a method which stashes it for a while, or perhaps
doesn't even throw an exception, but takes a different course?
I know exactly what asserted when I asserted it.

Do you have assertions turned on in the field? If so, that's costing
you performance *when things are working*. The ability to throw
exceptions is basically free when things are working. I'd rather have
code that performs slightly worse in the debugger but slightly better
in the field than vice versa.
A stack trace is not something I want to resort to unless there is a
real problem at hand. When my application throws an exception, I
don't normally go look at the stack trace. I look at where the
debugger was when it threw.

That's because you don't use exceptions as your preferred event
handling mechanism though. I'm quite prepared to see exceptions in the
diagnostic logs for real world apps,
To each his own. Such is life.

I've been having to read a load of C code that deals with errors in
what I view as the old-fashioned way. I then come back to me C# and
Java code and thank goodness for exceptions which can make life sane
again...
Ah, my point comes through. Use them judiciously I say.

And I've never said otherwise - but I view your avoidance of exceptions
on performance grounds as unjudicious, if there is such a word. It
seems to be based on a bogey-man which no-one ever really sees - the
app which *does* have performance problems due to over-use of
exceptions.
And yes, I am sure you could say it could go the other. That is why I use
both.

And that is why I recommend the right one for the right use. (But we will
probably never get consensus on the "right use" or the "right one". :)

We certainly won't if you keep arguing against their use due to
performance reasons.
 
Back
Top