Jump to content
Xtreme .Net Talk

snarfblam

Leaders
  • Posts

    2156
  • Joined

  • Last visited

  • Days Won

    2

Everything posted by snarfblam

  1. Maybe you should post the whole try/catch block, because from what you've posted I can't see a possible cause.
  2. JoeMamma wasn't banned because he posted malicious code (in fact, he posted plenty of good code), he was banned because he had a malicious mouth.
  3. No, it is not useless. The property is poorly implemented and does not necessarily work as expected. You would think that DoEvents would make it work, but obviously that is not the case. But if you experiment then you'll see that if you put a DoEvents inside the loop and then, while the loop is running, click on another window and move the mouse back over the original form, the hourglass appears. The behavior might be because the GUI's click event is still being processed, preventing some sort of action necessary to change the cursor in UseWaitCursor's implementation. That still doesn't help you out much, of course, but a workaround might. Appearently if you disrupt the focus of the control for which an event is being processed (for example, by disabling and then immediately enabling the control) the wait cursor will appear as expected. Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Me.UseWaitCursor = True [b] Button1.Enabled = False Button1.Enabled = True[/b] System.Windows.Forms.Application.DoEvents() 'doesn't help. Dim h As Long = Now.Second Dim i As Long = Now.Millisecond Dim n As Long Dim m As Long For n = 1 To 100000 For m = 1 To 2000 Next Next Text = (Now.Second - h) * 1000 + Now.Millisecond - i Me.UseWaitCursor = False End Sub End Class The important difference between UseWaitCursor and setting the cursor to an hourglass is that UseWaitCursor is application-wide, where as the Cusor property is form- or control-specific.
  4. DllImport should definitely be there. Perhaps it is hidden because it is an advanced member? (Are you using VB?) What happens if you type it in manually and try to compile?
  5. Just so you know, you really don't need all those parentheses. TextBox2.AppendText(vbCrLf + "linetest1 ") TextBox2.AppendText(vbCrLf + "linetest2 " + speaker_status) Would be exactly the same as: TextBox2.AppendText(vbCrLf + ("linetest1 ")) TextBox2.AppendText(vbCrLf + ("linetest2 ") + (speaker_status)) You might want to consider using the & and &= operators for joining strings because it makes it clear that you want to concatenate, not add. Dim Result As Object Dim Value1 As Integer = 10 Dim Value2 As Integer = "11" Result = Value1 + Value2 ' 10 + "11" = 21? Or "1011"? Result = Value1 & Value2 ' 10 & "11" = "1011" because & can't add.
  6. (1) I've seen tutorials that use TypeConverters, so I don't really know if there is any real advantage to using stringConverters. (2) I'm nearly positive that the property grid doesn't come with this feature out of the box. You'll notice that no simple dropdowns in VS allow you to select multiple enum members. Those properties where you can select multiple enum members (for example, the anchor property of a control) use custom editors. It would be nice if there were built in support for something like an enum dropdown list with checkboxes.
  7. I have the same problem too. I highly doubt that it is a problem with your installation. It could be a graphics hardware compatability, but I doubt that too. Most likely, intentionally or not, they changed the behavior of the control.
  8. The DesignMode property of the Control class is meant to be testable to see if the control is in design mode, allowing the programmer to produce different behavior at design time than at runtime. Unfortunately, the behavior of this property is particularly unreliable. It certainly has frustrated me at times and I'm sure that it has frustrated others, so I did a quick google search and found a few work-arounds on a blog and another blog. Test the value of GetService(typeof(IDesignerHost)) for null within a component. A null value indicates that the component is not hosted in a designer. This method did not work for me consistently. Check System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime. A true value indicates design mode. I haven't tried this method. Check that the process hosting the component is devenv. This is a less solid option because it won't work properly in certain circumstances, for example within VS add-ins or #Develop. Add a public static field to a class (ideally the Program class) named DesignMode that is initialized to true. In your application's Main() set the field's value to false. Because your application's Main method is not run within the designer, DesignMode will return true in the designer and false outside the IDE. This method is my preferred method, but isn't available with an VB program that doesn't have a Main() method.
  9. If you do a test like that, be sure to run the test many times under different circumstances. The reason I say so is that there are many factors that cause a program's memory usage to fluctuate. Things such as the fact that the garbage collector in the CLR won't collect the same objects at the same times, and that memory allocation won't be exactly the same when the state of the rest of the computer's memory isn't exactly the same. You'll notice that the memory usage of a program with a single form will drop dramatically (by an order of magnitude) when the form is minimized, and suppose that you open the task manager to view memory usage of method A, then close method A and run method B, and this time unwittingly minimize the window to view the already-open task manager. It would certainly seem as though method B consumes one eighth of the memory as method A, which is obviously not the case. If the difference is pronounced in all circumstances, I would say the statistics speak for themselves, but generally things such as the order that the programs are run in or even slightly varying contexts under which a program is running can make a difference. Minimize those unforeseen variables. Besides all that, I can venture a guess about which of the two will consume more resources, but a guess is all I can offer. Using only button-buttons, each button will require more Windows resources: each needs their own window, their own device context, yadda yadda yadda, whereas each toolbar-button requires more managed resources. Based on the assumption that the windows resources would out-weight the managed resources, I would say that button-buttons would use more memory than toolbar-buttons. Again, that's just a guess.
  10. Interesting... at the moment the only solution I can think of is calculating the color resulting from the combination of the backcolor and semi-transparent forecolor yourself, i.e.: 'Calculate solid color resulting from an alpha blend Public Function SolidColorFromAlphaBlend(ForeColor As Color, BackColor As Color) As Color 'Strength of forecolor as a fraction between 0 and 1 Dim Alpha As Single = CType(ForeColor.A / 255, Single) 'Strength of backcolor Dim Omega As Single = 1-Alpha 'Determing the resulting R, G, and B colors based on the 'strength of the component colors, as derived from alpha component Byte NewR = CByte(Math.Min( 'Math.Min ensures no overflow resulting from roundoff error. ForeColor.R * Alpha + BackColor.R * Omega, 255) Byte NewG = CByte(Math.Min( ForeColor.G * Alpha + BackColor.G * Omega, 255) Byte NewB = CByte(Math.Min( ForeColor.B * Alpha + BackColor.B * Omega, 255) Return Color.FromARGB(255, NewR, NewG, NewB) End Function I haven't tested this, and it won't work on top of a background image, but this function would help if the text were on top of a solid background.
  11. Much, much easier on the eyes.
  12. Which version of C# are you using? If you are using version 2.0 then there is a very easy (and more type safe) solution for problem #1. You can use the generic dictionary class and create your own IEqualityComparer<String> class that compares strings with case insensitivity. // Class that compares two strings in a case-insensitive manner. class InsensitiveComparer:IEqualityComparer<string> { public bool Equals(string x, string y) { // To do the comparison we use a string.Equals overload that allows us to ignore case return string.Equals(x, y, StringComparison.InvariantCultureIgnoreCase); } // This method exists only because it is required for the interface. public int GetHashCode(string obj) { return obj.ToUpper().GetHashCode(); } } // This is a string-key and string-value dictionary that uses case-insensitive keys. class NiftyStringDictionarty : Dictionary<string, string> { public NiftyStringDictionarty() : base(new InsensitiveComparer()) { } } This, of course, doesn't really help with problem #2.
  13. Just out of curiousity, why GDI instead of GDI+?
  14. I think that your and malfunction's point of view comes from the fact that you program for a living (assuming that that is what malfunction does for a living). Yes, you might still enjoy your work, but even if you still program in your spare time, and even if you enjoy doing so, it takes the "hobby" part out of it. And when you get to that point, I think that's where you are going to lose interest in the details (which is probably what you concentrate on the most at work) and pay more attention to the "bigger picture." My point of view, concentrating on the details instead of a more advanced or unique conception, might seem inane and uninspired, but I'm not looking to build something new and exciting. I'm simply looking to explore logic and learn new things. Besides, I see as much beauty in the details as I do in the whole of something.
  15. I think a profiler is closest to what you are looking for. Microsoft offers their CLR Profiler for free, although there are others too. CLR Profiler For .Net 1.1 CLR Profiler For .Net 2.0
  16. VB Express has a feature I am not particularly fond of. It has two tabs in the intellisense. Make sure you are looking at the second tab, which lists all memebers as opposed to "commonly used members," which the first tab lists.
  17. To elaborate on the GC.Collect method, Cags is right on the money. The garbage collector is designed in a manner that is optimized for best performance when the GC is left to its own devices. For example, an important aspect of .Net garbage collection is the use of generations. Each time a garbage collection is performed objects are "aged" a generation. The majority of garbage collections only collect objects from the most recent generation, which means that if you force collections you are pre-maturely aging objects and actually delaying their collection.
  18. The implementation is part of the solution, and it is not necessarily busy work, but it can be where the most challenge and thinking is involved. You can sketch out a program and an object model in you head, but once you start coding you find that in order for object A to communicate with object B, or to get certain types of input from a user, or to make your UI consistent you must do alot of rethinking. That's what I like. Entertaining my brain with the pure logic in program code. More importantly, for me, programming is not my job, it is my hobby. I get enough exercise at work, and when I get home it is nice to sit down for a while... what a perfect time to program, no? Use my body at work and my mind at home. If you prefer vice-versa, that's certainly fine. I, personally, would never want to program for work, or do any computer work, period, to make a living, because that is my hobby and as much as it sounds nice to "have a job doing what you love," the fact is that that job turns what you love into a chore.
  19. The event is run before the item is actually checked (i.e. you click a checkbox, it raises an event to let you know that an item is going to be checked, and then it actually checks the item). If you look at the members of the ItemCheckEventArgs, e, you will see that this allows you to examine the old value (CurrentValue), the new value (NewValue), and the index of the item that was clicked. It doesn't really do much for you and it can be slightly counter-intuitive, but if you just keep in mind that the item that is being checked does not actually change until after the event is raised, you should be fine.
  20. ReDim is a misleading, overly-convenient feature. It is not a smart way to manage memory, unless used very carefully. Each time you perform a ReDim, with or without the Preserve option, a new array is created (Preserve specifies that all elements that can fit into the new array should be copied over). It isn't necessarily your only problem, but it certainly isn't helping. So, for example, if you have a somewhat large array of integers (say 1000), it will take up 4000 bytes. Every time the amount of data you need changes, you decide to save memory by ReDimming to a smaller or larger array so that you only hold as much memory as you need. You end up redimming to 900, then 800, then 1100, which is only 100 more integers than you started with, but if the garbage collector doesn't get a chance to make its rounds all those old arrays pile up, so you end up with three extra arrays floating around (the total of the four arrays would be 15200 bytes, compared to the original 4000 bytes). Besides that, each time you do a ReDim Preserve, all of the data needs to be copied. This is hardly an efficient way to run things. So, what do we do? For starters, when your need for memory decreases, don't create a new, smaller array unless you aren't going to need the extra space for a long time and the difference is huge. Also, try to predict how much memory you are going to need. If you know you will usually need around 1000 integers, maybe create an array of 1500 integers so you have some breathing room before you need to create a larger array. But of course, all this coding to be more memory efficient is a pain, which is why Microsoft already did it for you. If you are using VS 2003 there is the ArrayList class, though it is not very efficient with memory when used for structures or primitive types like Integer and Boolean. In VS 2005 we have the generic List class which maintains an array for you and manages the array's memory for you, and is used with array-like syntax. 'Create a list Dim MyInts As New List(Of Integer) 'Add some data MyInts.Add(1) MyInts.Add(2) MyInts.Add(3) 'Now we can examine that data as though we were using an array: Dim RetrievedValue As Integer = MyInts(2) ' Get value MyInts(0) = 4 ' Set value
  21. The next question, I would imagine, would be "What alternatives are there to a constructor?" so I'll offer a couple. Both alternatives are seen from time in the .Net framework, though the first is encountered more often. Neither example does something you can't do with a normal constructor, but they demonstrate alternatives that don't have the same restrictions and can be more straightforward in certain cases. One option is to have no public constructors and instead provide a static method that can be used to obtain instances. This allows you to apply logic before you call a constructor. Class ExampleClass ' Private constructor, only methods defined in this class can instantiate this class. Private Sub New (int v) Base.New(v) End Sub ' This is the function that must be called to get an instance of this class Public Sub GetInstance(numericValue As Integer) ' You can place logic here before creating the object, for example ' confirm that a value is positive before passing it on to the base ' constructor If numericValue < 0 Throw New ArgumentException("The value must be positive.") Return New ExampleClass(numericValue) End Sub End Class The other option is to use a creation-parameters class, where instead of passing a number of parameters to a constructor which needs to process the parameters before calling the base constructor, you create a creation-parameter object, assign values to it, process logic internally in the creation-parameter object, and then finally pass that object as the sole parameter to the constructor of the object you want to instantiate. 'We want to create an ExampleClass object. To do so, we must create a CreateParams 'object, assign data to it, and pass it to an ExampleClass constructor. Class CreateParams 'We can use properties now, instead of constructor parameters Dim _examplePropertyBackingField As Integer Public Property ExampleProperty As Integer Get Return _examplePropertyBackingField End Get Set ' Pre-process you creation parameters here, before we even invoke the ' ExampleClass constructor. If value < 0 Throw New ArgumentException ("Value must be positive.") _examplePropertyBackingField = value End Set End Property End Class Class ExampleClass { Public Sub New(cp As CreationParams) ' Now we don't need to do any processing here because it was already done in ' the CreationParams object. Base.New(cp.ExampleProperty) End Sub End Class Hope that helps.
  22. What happens when you throw an exception depends on where and when it is thrown. When you throw an exception .Net crawls up the calls stack, looking at each function from the one most recently called up to the first function called, until it finds an exception handler (Try block). There is always an exception handler somewhere. In debug mode at the top level is the "Exception Assistant". In release in winforms apps it is the "Unhandled Exception" window, and in consoles it simply outputs a message. The debugger can also intercept exceptions for you, which means that you will see the exception assistant even if there is a handler somewhere up the chain. If you don't catch your exceptions they will usually trigger one of the above error handlers. If there is a .Net function on the call stack (for example, if you call a .Net function which, in turn, calls one of your functions) that .Net function could have an exception handler, which means that it might eat the exception and do nothing, or it could throw a different exception in response. When you throw an exception it doesn't always reach the top level handler (for example, the "unhandled exception" window in a realease build), and you should never assume it will. In fact, ideally, in a well designed application, it never will. The whole idea behind an exception is that your program can catch the exceptions and react to them without the program grinding to a halt or showing the user some horrific, confusing "unhandled exception" window.
  23. I would have to say that the while(true) form of the loop is much more common, though neither of the two are generally used by a reasonably experienced programmer. It has the makings of spaghetti code, not to far from here: loopstart: // Same as while(true) { goto loopend; // Same as break; goto loopstart; // These two lines loopend: // are the same as } P.S. Cags, the reason for the image link that appeared in the C# code is the ; ) in for( ;; ) (hence the name wink.gif). All you needed were some spaces. Look: for(;;).
  24. After much effort and time, I've gotten the collection editor to properly work with a collection property (Items) on a control I've written. The only problem I am having now is that when I delete the control in the designer, the components that were assigned to the Items property are not being deleted with the control. For instance, if you create a TabControl and add multiple TabPage components to the TabPages property, then delete the TabControl, the TabPage components disappear with it. When I delete my control, the items are not deleted. They remain in the designer generated code and in the drop down list at the top of the property grid. Some declarations: // Collection Item Class Declaration [DesignTimeVisible(false), ToolboxItem(false)] public class CollectionItem:Component { } // Collection Class Declaration public class Collection:IList<CollectionItem>, IList { // The designer uses the non-generic IList implementation } // to manage the collection at design time. // Collection Property Declaration [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), // Treat property as collection Editor(typeof(CollectionEditor), typeof(System.Drawing.Design.UITypeEditor) )] // Edit with the generic collection editor public Collection Items { get { return items; } } If anyone has any tips or suggestions they would be appreciated.
×
×
  • Create New...