|
Quote: I'm going to concerned with just two things. Any exceptions thrown by the Command and the data returned.
I understand and agree with what you say. But, I look for more. When something does go wrong in production, I'd like the debug log to have captured the runtime values of what I was using in the SqlConnection and SqlCommand object. With those, I can quickly tell if there was something wrong with the values (e.g. did someone diddle with a config file that had connection info?). Or maybe some of my query parameter values were unexpected. In any case, by having captured them in a catch block, I spend 5 minutes on solving a problem, instead of an hour or more guessing at what might have caused it. I could embed a try-catch within the using statement (not sure if the instantiation portion of the using statement would get "caught" in the catch block, though), but then if I have the try-catch, why not just add finally and do away with the redundancy of the using statement?
If the values seem OK, with the try-catch-finally, I can step through all the code, which is limited with the using statement.
I understand if these things are not valuable to you. But they are to me after many years of running into the odd issues that could have been solved by a couple more lines of code. Every developer has to pick and chose what they consider valuable to them, as well as to a customer.
|
|
|
|
|
Again, if you want that flexibility, don't us a using .
I don't have a need for the "what if" situation you posted, so I could easily just go with a using and not worry about it crashing under circumstances that were unexpected.
If I need to consider that the values are critical and need to be checked out in the future, I can always wrap it some logging code, or implement the using my self.
You're answering your own question.
|
|
|
|
|
I have to agree with Richard - using is cleaner, clearer, and easier to use.
And ... it makes the scope of the variable very, very obvious which a try...finally block doesn't - when you use the try...finally version, the scope of the variable is the block which contains the try...finally code (or it wouldn't be available for Dispose in the finally block) so you could write code to use a variable after it's content is Disposed:
SqlCommand cmd = new SqlCommand(sql, con);
try
{
...
}
finally
{
if (cmd != null) cmd.Dispose();
}
cmd.ExecuteNonQuery();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
...
}
cmd.ExecuteNonQuery();
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Quote: And ... it makes the scope of the variable very, very obvious which a try...finally block doesn't
Looks pretty obvious to me.
First, I would make the declaration statement as:
SqlCommand cmd = null;
since I would want the instantiation within the try block.
Your second example would be caught in the IDE, before you even tried to compile.
I agree that Quote: using is cleaner, clearer, and easier to use.
But easier does not always lead to better, more reliable, or less buggy. For the small amount of extra effort to use try-catch-finally, it seems to me to be worth the effort. I've run into objects created via the using statement that left me with odd behavior that could not be stepped through in a using statement. But once I did away with the using statement, and used try-catch-finally, I found the problem and corrected it within minutes. So to avoid these unnecessary, but rare issues, I don't take shortcuts like the using statement. I realize the responsibility is 100% on me to cleanup the objects I create, and I am OK with that.
Thanks, though, for taking the time to explain why you use it.
|
|
|
|
|
Quote: Your second example would be caught in the IDE, before you even tried to compile.
Precisely - you do realise that VS does a partial compilation while you type I assume - so it's caught before run time, which is always better from reliability and maintainability POV.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Quote: you do realise that VS does a partial compilation while you type I assume
Of course. Even the VB IDE did that back in the days before .NET. I was referring to when you would compile the project, not what the IDE was doing in the background, which is why the UI can tell you there is a problem.
|
|
|
|
|
MSBassSinger wrote: But easier does not always lead to better, more reliable, or less buggy. For the small amount of extra effort to use try-catch-finally, it seems to me to be worth the effort. I've run into objects created via the using statement that left me with odd behavior that could not be stepped through in a using statement. But once I did away with the using statement, and used try-catch-finally, I found the problem and corrected it within minutes. So to avoid these unnecessary, but rare issues, I don't take shortcuts like the using statement. I realize the responsibility is 100% on me to cleanup the objects I create, and I am OK with that.
Then don't use a using . It's your preference.
You seem to be looking for someone to refute your case for avoiding using . That's not going to happen.
|
|
|
|
|
The folks who responded so far have given some good insight as to why they use the using statement. I appreciate that they took the time to engage in a conversation about the topic. I understand those who do use it a bit better now.
I want to make it clear that although I would rarely choose to use it, that is my choice in the environments and contexts that I work in. I am in no place to judge someone else's choice, and I do not intend to imply that by this thread.
|
|
|
|
|
I tend to agree; though I'm drawn to using "using" because it makes me think harder when I have streams consuming streams that consume other streams (serializing, deserializing, encrypting, decrypting, compressing, uncompressing, xml versus binary, ...); using streaming "components" / iterators.
"Finally", is so ... "final".
(Also, "some" use try ... catch (nothing) as a crutch for sloppy thinking / coding).
At least, "using" is a useful thought experiment.
The Master said, 'Am I indeed possessed of knowledge? I am not knowing. But if a mean person, who appears quite empty-like, ask anything of me, I set it forth from one end to the other, and exhaust it.'
― Confucian Analects
modified 31-Jul-19 10:39am.
|
|
|
|
|
capture the screenshot of desktop using C#
|
|
|
|
|
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...
A very quick search using your question as the search term gave over 300,000 hits, including SO, MSDN, YouTube, CP, and a pile of other sites: capture the screenshot of desktop using C# - Google Search[^]
In future, please try to do at least basic research yourself, and not waste your time or ours.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I came of think of this, I wrote an application quite a while ago that did the same thing using .NET framework, I think I used System.Drawing to capture the graphics from the screen—maybe something else, please see there.
Here is the complete sample of this project, Windows Saving a screenshot using C# sample in C# for Visual Studio 2013
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Hello everyone,
I am actually trying to create or generate automatically struct using the class "TypeBuilder".
I have already found a solution to create an "enum".
Here is the Code that I found as example on the microsoft-page:
using System.Reflection;
using System.Reflection.Emit;
namespace IoddParser
{
class test{
public void CreateEnum()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
AssemblyName aName = new AssemblyName("TempAssembly");
AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(
aName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));
eb.DefineLiteral("Low", 0);
eb.DefineLiteral("High", 1);
Type finished = eb.CreateType();
ab.Save(aName.Name + ".dll");
foreach(object o in Enum.GetValues(finished) )
{
Console.WriteLine("{0}.{1} = {2}", finished, o, ((int) o));
}
}
How can I do the same procedure to get a struct (NOT A CLASS )
Thank you.
|
|
|
|
|
|
Because of the constraints that make using instances of run-time defined Types difficult, I'd recommend you look at an alternative like System.Dynamic ExpandoObject.
You create a Struct on-the-fly: any instance of it is going to be boxed, and right there you may have lost the potential benefits of using a Struct.
The few cases I've seen that needed to cook up some run-time bag of mixed Types could all be handled using System.Dynamic (or, even the now deprecated 'ArrayList).
Rick Strahl has done some very interesting work with ExpandoObject that I think could be relevant to your concerns: [^].
Describe your use case in detail, maybe you'll get more specific feedback.
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
modified 1-Aug-19 14:45pm.
|
|
|
|
|
BillWoodruff wrote: or, even the now deprecated ArrayList
I'm not sure you'd ever need to use ArrayList , when you could just use List<object> instead.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Amen ! Wish I could say I was thinking of those doomed to use .NET pre-Linq, but I wasn't
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
|
The problem is that when the code runs in the design view, the current directory is the Visual Studio application directory, not your project's directory. The file C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\google.png doesn't exist, so the Bitmap constructor throws an exception.
You can use the DesignMode property[^] to test whether your control is in design mode. You should probably also check that the file hasn't been deleted:
Image img;
public tab()
{
InitializeComponent();
if (!DesignMode && File.Exists("google.png"))
{
img = new Bitmap("google.png");
}
}
private void tab_Paint(object sender, PaintEventArgs e)
{
if (img != null)
{
e.Graphics.DrawImage(img, rect);
}
} You should be able to adapt the code from this SO answer[^] to resolve the image path at design time, if you need to see the image in the designer:
private string ResolveImagePath()
{
string path = "google.png";
if (DesignMode)
{
var typeResolver = (ITypeResolutionService)GetService(typeof(ITypeResolutionService));
if (typeResolver != null)
{
AssemblyName name = System.Reflection.Assembly.GetExecutingAssembly().GetName();
string basePath = typeResolver.GetPathOfAssembly(name);
path = Path.Combine(basePath, path);
}
}
return path;
}
public tab()
{
InitializeComponent();
string imagePath = ResolveImagePath();
if (File.Exists(imagePath))
{
img = new Bitmap(imagePath);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
___The bug is thrown at the initialization of the image. As you can see in the code below:
public tab()
{
InitializeComponent();
}
Image img = new Bitmap(@"google.png");
Rectangle rect = new Rectangle(5, 5, 22, 22);
private void tab_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, rect);
}
___ NEXT, i initialize it in the constructor, following your helping code like this:
public partial class tab : UserControl
{
public tab()
{
InitializeComponent();
if (!DesignMode && File.Exists("google.png"))
{
img = new Bitmap("google.png");
}
}
Image img;
Rectangle rect = new Rectangle(5, 5, 22, 22);
private void tab_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, rect);
}
but another Error appear:
https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/281c49f0-e874-4b83-bff6-9bc6b8526d42/ddctlq3-8c112b8d-5685-4a43-a96e-21046443ef9a.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzI4MWM0OWYwLWU4NzQtNGI4My1iZmY2LTliYzZiODUyNmQ0MlwvZGRjdGxxMy04YzExMmI4ZC01Njg1LTRhNDMtYTk2ZS0yMTA0NjQ0M2VmOWEuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.1fkgpeEVDKRy30I70lftNt0WfbpoFl8LACty1N_fzsc[^]
Now what?
_ Your '!DesignMode' solution, is really nice and i didnt know it at all !
Awesome so far.
|
|
|
|
|
_Q12_ wrote: another Error appear
You missed the update to the tab_Paint event handler:
private void tab_Paint(object sender, PaintEventArgs e)
{
if (img != null)
{
e.Graphics.DrawImage(img, rect);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you for all your help - you really inspired me.
It was a very very old problem and now you 'confirmed' it to me. Thats why im so thankful. And pointing that was more a design issue and not a compile issue, cemented it for me.
|
|
|
|
|
Are you sure the root is correct?
What i did: I created a new alb.jpg file into (your specified folder root):
"c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
and the code now checks if in 'DesignMode', then load the default alb.jpg image.
Else, is runtime and load the normal image.
here is my code:
public tab()
{
InitializeComponent();
string alb = @"c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\alb.jpg";
if (DesignMode==true)
{
img = new Bitmap(alb);
}
else
{
img = new Bitmap("google.png");
}
}
Image img;
Rectangle rect = new Rectangle(5, 5, 22, 22);
private void tab_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, rect);
}
string mytext;
public string tab_Text
{
get { return mytext; }
set
{
label1.Text = mytext = value;
}
}
I get the same error as the first time, not finding the png file.
|
|
|
|
|
I find another solution but all thanks to your support, so many many thanks - it really helped me !!!
control code:
public tab()
{
InitializeComponent();
}
Image img;
Rectangle rect = new Rectangle(3, 3, 22, 22);
private void tab_Paint(object sender, PaintEventArgs e)
{
if (img!=null)
{
e.Graphics.DrawImage(img, rect);
}
else
{
e.Graphics.FillRectangle(new SolidBrush(Color.Black), rect);
}
}
public Image tab_Image
{
get { return img; }
set
{
img = value;
}
}
and in design mode i set the property for image. And the image is seen in the design mode this way with no apparent errors. I will see in time how good solution is this one.
.
|
|
|
|
|
On top of what Richard said, for custom controls where you have images that don't change and are a mandatory part of your control, you should probably move the images to Resources instead of leaving them in files. You can then load the image from your controls Resource and you won't have any problems with managing files on the drive.
Load image from resources area of project in C# - Stack Overflow[^]
|
|
|
|
|