Sunday, May 1, 2011

How does GC and IDispose work in C#?

I remember i was loading in images by streaming it from the net straight into a bitmap. close the stream, return the bitmap and held it in an image control.

I excepted when i did = loadPicture() the first bitmap would be freed like a smart pointer would do in C++. But it didnt and i consumed a lot of ram until i called dispose. So my question is.

How does the GC and Dispose able objects work in C#? and why isnt it implemented like a smart_ptr?

From stackoverflow
  • The GC kicks in when the runtime feels it is necessary.

    The basic rule is: when you use an Disposable type (IDispose), then you (as the programmer) should release the resources used by that type as soon as possible, by calling Dispose when you do not longer need to use that type. For instance, when you read a file, you close that file as soon as you've done reading it. (Calling close will also call dispose in this case).

  • References are not smart pointers. Letting a reference-variable go out of scope, replacing it with another value, and/or setting it with null all do exactly nothing.

    This is simply part of the CLI /GC design...

    Gargage Collection (GC) will run when needed, and should clean up the managed memory used, and (if a finalizer is provided) any unmanaged resources too. But for deterministic cleanup: that is the entire purpose of IDisposable. It is your job to Dispose() such objects when you have finished with them - either via using, or by handing it to something else which assumes this responsibility (common, for example, with streams/readers etc).

    using (StreamReader reader = new StreamReader(myfile)))
    {
       ...
    }
    
    Dead account : +1. Im sure this question has been asked already :)
    acidzombie24 : Are you saying i don't 'need' to dispose of anything?
    Anton Tykhyy : Only in the sense that even if you don't, resources will eventually be freed (if they implement IDisposable correctly, that is). In practice, this is merely a safety net. You want to release unmanaged resources as soon as possible.
    Lucero : "...all do exactly nothing" is not the full truth. By setting references to null, you might allow the memory to be released earlier because the reference is no longer seen as "live" reference in the system when the GC runs.
    Mudu : As far as I know, finalizers are not guaranteed to be called. Usually they are, but there's no garanty. See http://tinyurl.com/cr4uo2 (MSDN: Object.Finalize Method) under "Remarks" for details.
    Marc Gravell : @Lucero - I mean as an *active* operation; the runtime is indeed to do more clever things. @Mudu - indeed.
    Marc Gravell : @acidzombe24 - choosing not to Dispose() things would be risky - you can run out of unmanaged resources without really using much managed memory, so GC wouldn't kick in. Early versions of VS suffered from this, IIRC. You should always try to release (Dispose()) such objects ASAP once you are finished with them.
    configurator : @Lucero: If the variable is not referenced after the point where you set it to null, it's a no-op, because once you have reached the point where a variable is not referenced any more, the JIT knows and it is the same as leaving scope. Setting it to null is also JIT-optimized away.
  • smart_ptr are reference counted. While this allows for deterministic release of their resources when they are no longer referenced by any code, they do have their problems of their own: assigning references always requires the counter to be updated, circular references fail to be released automatically causing memory leaks, the memory manager is invoked more often.

    The GC in .NET is a sweeping collector. It starts at any time when it feels that memory should be released (usually triggered by some memory usage condition, but not deterministic) and starts by building a list of all live references in the system (including the ones in CPU registers, nested references etc.). This works since we are in a managed environment where you cannot do pointer arithmetic etc. - the system can track all references. After the list of live references has been built, it basically releases all memory not known to be used anymore. Of course, this is just the basic sketch, for efficiency and management of unmanaged resources there is more to it like object generations, finalizers, etc., but that is not important for the basic understanding of how it works.

    The IDisposable interface is used to implement the disposable pattern, which helps when you are working with objects that should be disposed in a deterministic way. The pattern is so that Dispose() is called explicitly when the object is no longer needed, therefore releasing unmanaged resources or closing handles etc., but not releasing its memory. This will be done by the GC later on, but it does not matter that this happens later, because the deterministic release of resources has already been performed.

  • You must call Dispose explicity on any object implementing IDisposable, otherwise your unmanaged resources will not be disposed. If you don't want to call it explicity, then you must override the Finalize method to call the Dispose method - that is why you will see this frequently:

     class MyClass : IDisposable
     {
        ...
    
        ~MyClass()
        { 
           this.Dispose(false);
        }
    
        public void Dispose()
        {
           this.Dispose(true);
           GC.SuppressFinalize(this);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            { /* dispose managed stuff also */ }
    
            /* but dispose unmanaged stuff always */
        }
     }
    

How to correctly calculate the height of a table

How do you calculate the height of a flexgrid table in VB6 so that it only contains the number of filled rows.

Currently

myFlexGrid.Height = (myFlexGrid.CellHeight * myFlexGrid.Rows) ' paraphrased from code

comes out at about 3 pixels short per line. Adding in the magic number is a bit hackish and would like to accomplish this without having to resort to that.

Update: To complicate matters it also needs to handle multiline cells.

From stackoverflow
  • You need to go

    Me.MSFlexGrid1.Height = (Me.MSFlexGrid1.CellHeight) * (Me.MSFlexGrid1.Rows + Me.MSFlexGrid1.FixedRows) + 30

    The 30 is to make it two pixels longer to show the black border running around the flexgrid.

    Also disabling the vertical scrollbar helps as well.

    graham.reeds : Actually the 30 is not correct from what I can find: If a user is running in 120dpi mode then 12 twips is equal to 1 pixel. But this adding of a semi-arbitary number is what I am trying to avoid.
    graham.reeds : I've also just found it needs to handle multiline cells.
    RS Conley : Unless the control explicitly supports an autoheight function or exposes the values of the height of every UI element you will not be able to avoid using magic numbers. This is because controls are designed as black boxes. It looks like your logic is going to get complex here I suggest wrapping the flexgrid inside of a control class and add the autoheight function in there so the code in your main routines remains clean.
  • RS Coneley is close, but here is the correct way that accounts for all DPI settings:

    Me.MSFlexGrid1.Height = Me.MSFlexGrid1.CellHeight _
                          * (Me.MSFlexGrid1.Rows + Me.MSFlexGrid1.FixedRows) _
                          + (Screen.TwipsPerPixelY * 2)
    
  • This is the final code I came up with

        For i = 0 To fgrComments.Rows - 1
            'Set MSFlexGrid to appropriate Cell
            myFlexGrid.Row = i
    
            'Set textbox to match the selected cell
            txtSizer.Width = myFlexGrid.ColWidth(2)
            txtSizer.Font = myFlexGrid.Font
            txtSizer.Text = myFlexGrid.Text
    
            'Call API to determine how many lines of text are in text box
            lLinesOfText = SendMessage(txtSizer.hwnd, EM_GETLINECOUNT, 0&, 0&)
    
            ' Update the running values
            lTotalNumberOfRows = lTotalNumberOfRows + lLinesOfText
            lCurrentHeight = lCurrentHeight + myFlexGrid.CellHeight
        Next i
    
        ' resize the grid
        Dim iSpacers As Integer
        iSpacers = Screen.TwipsPerPixelY * lTotalNumberOfRows
        myFlexGrid.Height = lCurrentHeight + iSpacers
    

    You will need to Declare the SendMessage (see here to see how) and the value of EM_GETLINECOUNT, but you should be able to do that yourself:-)

    It doesn't remove the magic numbers but it does rationalise them which is close enough for me.

studying nhibernate critieria queries

Is there any other site for studying critieria queries like http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/querycriteria.html

From stackoverflow

Best way to write a custom gauge control in WPF?

I need to write a gauge control in WPF for a project at work. By gauge control, I mean something akin to a traditional car speedometer: a circular face with numbers and ticks around the circumference, and a needle pointing to the current value. Although I could get my employer to purchase a third-party control, or even find a free one somewhere, I’d still like to write it myself, for curiosity’s sake more than anything else.

My first thought was to ‘skin’ an existing control using a template, something like a ProgressBar for example as it has Minimum, Maximum and Value properties. However, I don’t think this will offer me the flexibility that I need.

I’d like to animate the needle that points to the current value, so that when the gauge’s value changes the needle moves from the old value to the new value. I figured the easiest way to do this would be to have some kind of shape or geometry representing the needle, and then apply a RotateTransform of the relevant number of degrees to get the needle to point to the correct value. The animation’s To property would be set to the ‘value degrees’ property via binding.

It seems to me that there are three basic approaches I could take:

Use one custom FrameworkElement to represent the entire gauge
I could derive from FrameworkElement, override its OnRender method, then use the DrawingContext to draw both the gauge face and the needle. This would mean that I could no longer animate the needle directly using a RotateTransform, but would instead have to redraw the entire gauge every time the value changes. This seems inefficient to me, as the gauge face represents the bulk of the drawing code but would change very rarely. However, this approach is the most lightweight in terms of the number of elements used.

Use two custom FrameworkElements, one for the face and one for the needle
I’m currently leaning towards this approach. One element would represent the face, the other the needle. This would allow me to target the needle element with the RotateTransform. The gauge control would then consist of three elements: the face, the needle, and a Panel container to hold both of them (ie. Canvas, Grid, whatever). So three elements instead of one, hence not as lightweight as the first approach.

Use DrawingVisuals to draw the face and needle
I’ve also read about the DrawingVisual class, but I’m a bit confused as to why anyone would use this as opposed to deriving from FrameworkElement and overriding OnRender, given that DrawingVisual must be hosted in a custom FrameworkElement anyway. It would seem that this approach doesn’t offer any advantages over the second approach, and would require more code, but maybe I’m missing something.

Any thoughts or advice regarding which approach people think is best and why would be most welcome!

From stackoverflow
  • Personally I'd recommend making a CustomControl using the second approach. Unless you are going to be showing more than 1000 of the gauges in view at the same time you aren't going to notice the extra element in your visual tree and I think you'll find it's much easier to make and maintain.

    Steve Rands : This is the best approach given my criteria I think. I wasn't able to write the control in this way for a number of reasons (mainly my lack of experience with WPF to date) so in the end I actually went with approach #1.
  • You could just style a slider control and feed values into it. You should be able to make a slider look like any kind of gauge you need.

    Steve Rands : While this would work in some circumstances it wasn't an approach I could use given my requirements (which maybe I should have clarified in the question). The scale of the gauge needed to be variable (ie. min/max range and number of divisions would change), plus I needed other properties to represent coloured ranges on the gauge and so on. I don't believe I could have achieved this by just styling an exisiting control; I couldn't see a way of representing something like that in markup.

msbuild community task and Svn commit

Hi all,

I'm currently using the tigris open source project MSBuild Community Task and I have some trouble with the SvnCommit Task. I don't really know how to use the Targets attribute I have this line in my project :

<SvnCommit Username="myName" Password="myPsswd" LocalPath="$(myPath)" ToolPath="$(SvnPath)" Targets="myFile.zip"/>

and I have an error : "c:\blabla" - which is a part of $(myPath) - is not a working copy; svn : Can't open file 'c:\blabla.svn\Entries"

If someone has some ideas, they are welcome !

maybe sould I use the RepositoryPath attribute ?

From stackoverflow
  • ok I have found my problem and it's so silly that I really apologize for the noise on this site. by the way if it can help someone who encounters same pb...

    so the problem was my "Target" attribute ! I had to use a ItemGroup : so I add the following lines in my project

    <ItemGroup>
      <ToCommit Include="$(myPath)/myFile.zip" />
    </ItemGroup>
    

    and changed the task :

    <SvnCommit Username="myName" Password="myPsswd" LocalPath="$(myPath)" ToolPath="$(SvnPath)" Targets="@(ToCommit)"/>
    

Is there a way to configure email account on iPhone from code?

Hi,

I'm quite new in iPhone development. I'm interested to configure email account on iPhone from code. Is it possible? Is there any API in SDK to implement this?

Thank in advance for your answers.

Regards, M. Wolniewicz

From stackoverflow
  • Unfortunately, you cannot configure eMail accounts on an unjailbroken iPhone from code.

Passing arguments to the Class Constructor

How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?

<?php

/*
./index.php
*/

function Object($object)
{
    static $instance = array();

    if (is_file('./' . $object . '.php') === true)
    {
     $class = basename($object);

     if (array_key_exists($class, $instance) === false)
     {
      if (class_exists($class, false) === false)
      {
       require('./' . $object . '.php');
      }

      /*
      How can I pass custom arguments, using the
      func_get_args() function to the class constructor?

      $instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
      */

      $instance[$class] = new $class();
     }

     return $instance[$class];
    }

    return false;
}

/*
How do I make this work?
*/

Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);

/*
./libraries/DB.php
*/

class DB
{
    public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
    {
     // do stuff here
    }
}

?>
From stackoverflow
  • Instead of your class taking separated parameters I'd have it take an array.

    class DB
    {
        public function __construct(array $params)
        {
            // do stuff here
        }
    }
    

    That way you can pass the direct result of the func_get_args into your constructor. The only problem now is being able to figure out the array key / values.

    If anyone else has any ideas I'd also be delighted to know :)

    Alix Axel : I got the same idea as well but I was curious to know if something like I described could be done.
  • I haven't tried this, but call_user_func_array sounds like you want.

    $thing = call_user_func_array(array($classname, '__construct'), $args);
    

    Have a look in the PHP Documentation.

    Alix Axel : Doesn't work. =\ call_user_func_array(array(new $classname(), '__construct'), $args); This works but then I would be calling the constructor twice.
    staticsan : Try it without new $classname().
    Alix Axel : Fatal error: Non-static method test::__construct() cannot be called statically
    staticsan : Okay, I've got no more ideas. Thanks for being willing to try.
  • $klass = new ReflectionClass($classname);
    $thing = $klass->newInstanceArgs($args);
    

    Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place?

    Alix Axel : I admit this function may seem a bit nonsense but I use it for small stuff where a framework may be too bloated. And since it acts as an "autoloader", object constructor and singleton container it does the job perfectly.
    Alix Axel : BTW, that Reflection class is really handy, is there any crash course available on the new features of PHP 5.3? I checked the PHP manual but is it me or it is lacking a lot of documentation?
    troelskn : It's not you: The documentation is rather sparse on that. You'll have to do with http://www.php.net/oop5.reflection. Also, it has been around since 5.1 (or is it 5.0?), so it's not a new feature of 5.3

Should the WebInfo file be excluded from SVN

I have recently had a few issues when checking out a colleagues ASP.NET project, that causes the Project to get into a conflicted state because of the WEBINFO file being checked into SVN.

Does this file need to be in the repository or should we exclude it?

From stackoverflow

Simplest way to stop all java threads from disappearing into IO ?

I have a web-application that only requires the servlet-container to run. My login page and front page do not have any backend transactions, but all others do. What'd be the simplest way to guarantee that I don't send all my threads into some socket wait for a backend system (CXF-webservices) ? This is weblogic 10.3 but I'm really not that concerned about standards compliance.

I have an AOP aspect that already intercepts all backend traffic, so I figured I could increment/decrement an AtomicInteger and throw an exception when there's too few threads left, but that gives the problem of determining current thread pool size.

Any ideas ?

From stackoverflow
  • Okay, what's your use case? If everything except your login and front pages have backend transactions, and you run out of threads, what do you want the application to do? What observable behavior would you like?

    Sort of the usual thing would be to have some kind of "please stand by..." message; if so, create a thread that can set that up, and have it checking for progress. When there's no progress, show the "please stand by..." message.

    krosenvold : I'd simply like to have a few threads available to process requests for the front page. There may be messages on the front page like "the system is having trouble.."
  • How much control do you have? Could you configure weblogic to use the 8.1 thread pool model and then define different thread pools--one for the potentially long lived back end calls and one for processing requests to the front page?

    This would be configuration only and you'd not have to code anything, which seems good to me.

What does SnapsToDevicePixels in WPF mean in layman terms?

Anybody? Say I have a Window Class and I give SnapsToDevicePixels = true? what happens?

From stackoverflow
  • It will enable pixel snapping for every element in your window as this property is inherited by child UI elements. It won't have an effect on the appearance of the window itself, though (i. e. window frame or similar).

Get Published XBAP version in C#

I have an XBAP currently published on my local machine, which has an 'About' canvas build into the XMAL, of which I want to show the published version number, but I can only seem to get the assembly version number. Any suggestions?

From stackoverflow
  • I've seen somewhere saying to use:

    System.Deployment.ApplicationDeployment.CurrentVersion

    But when using System.Deployment there appears to be no System.Deployment.ApplicationDeployment available to be accessed!

    This may not be a solution but may point in the right sort of direction. If someone uses this already maybe they can shed some more light on the matter.

  • First make sure you add the following assembly to your project references: System.Deployment. Then you can access the current version like this:

    using System.Deployment.Application;
    
    ... 
    
    if (ApplicationDeployment.IsNetworkDeployed)
        VersionTextBlock.Text = 
           ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
    

    CurrentDeployment is null when you debug locally, so you can use IsNetworkDeployed to only retrieve the version info when you run from the published location.

  • With .NET 3.0 I'm using

    Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

Deserialize object into assembly that is now signed and versioned

I used to serialize a treeview with the BinaryFormatter (c#). The Assembly that did just that and which contains the all the serializable classes has now a strong name and is signed and also got a new version number (however, implementation didn't change).

When I try to deserialize the byte[] array, the line

(TreeViewData)binaryFormatter.Deserialize(memoryStream);

produces an ArgumentNullException. (Parametername: type)

I thought the versionnumber is the problem, so I implemented an own Binder. I overwrote the BindToType method and made sure that the version is corrected and the correct type is returned.

However, at the very moment, the program leaves the BindToType method, I still get the exception mentioned above.

How do I fix this?

From stackoverflow
  • You could try using a serialization surrogate, but without something we can reproduce it will be hard to give a decent answer.

    The fundamental problem, however, is that BinaryFormatter is simply very, very brittle when it comes to things like assemblies. Heck, it is brittle enough even within an assembly.

    It sounds like TreeViewData is tree based, so I wonder whether xml would have been a better (i.e. more version tolerant) option. If efficiency is a concern, there are custom binary formats (like protobuf-net) that offer high performance, version tolerant, portable binary serialization. If your data is already serialized... I wonder if it might be time to change track? Try using the old assembly to deserialize the data, and switch to a more robust serialization strategy.

  • You can use a SerializationBinder to solve this:

    private class WeakToStrongNameUpgradeBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            try 
            {
                //Get the name of the assembly, ignoring versions and public keys.
                string shortAssemblyName = assemblyName.Split(',')[0];
                var assembly = Assembly.Load(shortAssemblyName);
                var type = assembly.GetType(typeName);
                return type;
            }
            catch (Exception)
            {
                //Revert to default binding behaviour.
                return null;
            }
        }
    }
    

    Then

    var formatter = new BinaryFormatter();
    formatter.Binder = new WeakToStrongNameUpgradeBinder();
    

    Voila, your old serialized objects can be deserialized with this formatter. If the type have also changed you can use a SerializationSurrogate to deserialize the old types into your new types.

    As others have mentioned, doing your own serialization rather than relying on IFormatter is a good idea as you have much more control over versioning and serialized size.

    Rick Minerich : Oh thank you so much.
  • My recommendation is to never use the builtin serializes for your persistent storage. Always code your own if for no other reason someday in the future you will need to read and write your file formats from another language.

Why is TestComplete so slow ?

We are using TestComplete from AQTime to test the GUI at client with our Client/Server application. It is compiled with Delphi 2007. The source of client is about 1.4 millions sourcelines. The hardware is a Intel dualcore 2.13 Mhz, 2 GB RAM using Windows XP Pro.

I compile the application with all debug options and also link in TCOpenApp, tcOpenAppClasses, tcPublicInfo, tcDUnitSupport as described in documentation to make it an Open Application. The resulting exe-file is about 50 MB.

Now when running the testscript and it works, but running very very slow. The CPU is running at 100 % and it is a bit frustrating to change the testscript because of the slowness. I have turned off all desktop effects like rounded window corners. No desktop background.

Anyone else with the same experience or even an solution ?

From stackoverflow
  • Your problem probably lies in the fact you compiled with debug info and are using the tcXXX units, resulting in an enormous amount of objects being created.

    A transcript from AutomatedQA message boards

    Did you compile it in debug mode? We have an app that when compiled in Debug mode is slow when used with TC. This is because of the enormous # of objects in it. If we compile w/o debug but with the TC enabler(s), everything is fine.

    and this one might help to

    A couple of areas where you can increase speed.

    If you are just using record and playback, then look into replacing the .Keys("xxx") calls to .wText = "xxx". The Keys function will use the ms delay between keystrokes, while wText just forces the text overwrite internally.

    The second suggestion (which you likely have already looked at) is Tools->Default Project Properties->Project->Playback, setting the delays to 100 ms, 5 ms, and 5 ms to keep the pauses to a minimum.

    As for the object properties, yes, TC loads them all. You can force this with a process refresh on yor application, so that the data is forced into being available without a load delay when called. This might help with reducing the appearance of delay.


    Edit:

    • We also have been evaluating TestComplete and also encountered this performance problems. I would be very interested to know if and how you've finally solved them.
    • That said, I think it is a product with great potential and can really help you with organizing all of your unit, integration and GUI tests.
    Roland Bengtsson : Thanks for thew information! I will try to remove debug information and also change to other things you find. Great!

ASP.NET MVC Roles Authorization

I want to make the roles default for my controller class to "Administrators, Content Editors"

[Authorize(Roles = "Administrators, Content Editor")]

I've done this by adorning the controller with the attribute above. However, there is one action that I want to be available to all (namely "View"). How can I reset the Roles so that everyone (including completely unauthorized users) have access for this action.

Note: I know I could adorn every single action other action with the authorize attribute above but I don't want to have to do that all the time. I want all of the controllers actions to be unacessible by default so that if anyone adds an action they have to make a considered decision to make it available to the general public.

Cheers...

From stackoverflow
  • The only solution I can think of so far is to create and register another controller so that I have one for anonymous access, and one for authorized access but that's not quite as elegant as I would have liked.

  • You can place the Authorize attribute on the action methods. Not just at the class level.

    So, move the attribute from the controller class to just the action methods you want to secure.

    Owen Thomson : Hi Kieron, thanks for the response. As the Note part of my question stated I'm aware this is possible but I want the default for the controller actions to be unaccessible without having to adorn them with the authorize attribute.
  • So are you wanting something like http://stackoverflow.com/questions/780436?

    Owen Thomson : Yup - looks about right ... wish this was inbuilt to the std controllers but not a big effort to code for. Thanks for linking me up.

How to combining two files and creating a report with matched fields in COBOL

I have two files : first file contains jobname and start time which looks like below:

ZPUDA13V STARTED - TIME=00.13.30
ZPUDM00V STARTED - TIME=03.26.54
ZPUDM01V STARTED - TIME=03.26.54
ZPUDM02V STARTED - TIME=03.26.54
ZPUDM03V STARTED - TIME=03.26.56

and the second file contains jobname and Endtime which looks like below:

ZPUDA13V ENDED - TIME=00.13.37
ZPUDM00V ENDED - TIME=03.27.38
ZPUDM01V ENDED - TIME=03.27.34
ZPUDM02V ENDED - TIME=03.27.29
ZPUDM03V ENDED - TIME=03.27.27

Now I am trying to combine these two files to get the report like JOBNAME START TIME ENDTIME.I have used ICETOOL to get the report If I get JOBNAME START TIME ,ENDTIME is SPACES .If I get Endtime ,JOBNAME START TIME gets spaces. Please let me know how to code the outrec fields as I have coded with almost all possibilites to get the desired one.But still my output is not the same as I required

From stackoverflow
  • I have no idea what ICETOOL is (nor the inclination to even look it up in Google :-) but this is a classic COBOL data processing task.

    Based on your simple data input, the algorithm would be:

    for every record S in startfile:
        for every record E in endfile:
            if S.jobnname = E.jobname:
                ouput S.jobname S.time E.time
                next S
            endif
        endfor
    endfor
    

    However, you may need to take into account the fact that:

    • multiple jobs of the same name may run during the day (multiple entries in the file).
    • multiple jobs of the same name may run at the same time.

    You could get around the first problem by ensuring the E record was the one immediately following the S record (based on time). The second problem is a doozy.

    If you're running on z/OS (and you probably are, given the job names), have you considered using information from the SMF records to do this collection and analysis. I'm pretty certain SMF type 30 records hold everything you need.

    And assuming this is a mainframe question, here's a shameless plug for a book one of my friends at work has written, check out What On Earth is a Mainframe? by David Stephens (ISBN-13 = 978-1409225355).

  • Hi GustlyWind,

    Why not use easytreive to get the report that you wanted.

WPF access controls in a DataTemplate of a ListBox

I'm building a WPF order manager app and i've run into a situation i'm not sure how to deal with.

I want to re-bind the list of purchase orders requests for each order but i only want to do it if the the purchase order requests panel is visible in the app (they double click the order to show the list of purchase order requests). The problem i have is that the purchase order requests are a listbox inside each list item of the Order listbox and i can't find a way to traverse the controls in the list items (I can only iterate over the actual objects e.g. OrderInfo).

What i would like to do is

OrderListBox.FindName("PurchaseOrderListBox")

An example of the crm with 2 orders showing purchase order requests and 1 order not showing any alt text

The result i want to achieve alt text

From stackoverflow
  • I'm not sure I understand your problem....

    But it feels like you're trying to hack through the UI hierarchy to find something (ala WinForms) - this is like swimming against the tide in WPF. It'll make you tired real fast..

    Look around for articles on the ViewModel pattern. One of them that I read is one by Dan Crevier. The basic idea is to have a Model object for the UI - the UI (data)binds to properties exposed by the ViewModel. Now all your UI related logic could go into the ViewModel, which is notified via propertyChanged notifications of any change in session state. So if a field changes, the ViewModel gets notified. The ViewModel updates relevant properties and the UI refreshes accordingly.

    In this case ViewModel.OrderInfo.Find_PO_with_X(searchCriteria) will help you get to the right object. If found, you say ViewModel.ShowGreenLight = true and the UI control bound to this property will turn green.

    HTH

Windows Form with String Table

I have Normal Windows Form (WinForm) C# (.Net 3.5) application, this application has label with text and menus and etc... also this application display sometimes Message Boxes to the user, and write some information to files.

I would like that all information that the user can see (by GUI or by files) will be manage by (One, if it possible) String Table. My problem is that I can't find how to move all of my GUI controllers texts to a string table in the resources file.

Thanks

From stackoverflow
  • You can bind the Text property of the labels to either an application setting or string resource in the Forms Designer's properties window.

  • For forms and other GUIO components, set their Localizable property to true. This will automatically move texts to resource files.

    For sting literals in your code, the resource refactoring tool is your friend

Python base clase method call: unexpected behavior

Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below?

class A(dict):
    def __repr__(self):
        return 'repr(A)'
    def __str__(self):
        return dict.__str__(self)

class B(dict):
    def __str__(self):
        return dict.__str__(self)

print 'call: repr(A)  expect: repr(A)  get:', repr(A())   # works
print 'call: str(A)   expect: {}       get:', str(A())    # does not work
print 'call: str(B)   expect: {}       get:', str(B())    # works

Output:

call: repr(A)  expect: repr(A)  get: repr(A)
call: str(A)   expect: {}       get: repr(A)
call: str(B)   expect: {}       get: {}
From stackoverflow
  • str(A()) does call __str__, in turn calling dict.__str__().

    It is dict.__str__() that returns the value repr(A).

  • I have modified the code to clear things out:

    class A(dict):
       def __repr__(self):
          print "repr of A called",
          return 'repr(A)'
       def __str__(self):
          print "str of A called",
          return dict.__str__(self)
    
    class B(dict):
       def __str__(self):
          print "str of B called",
          return dict.__str__(self)
    

    And the output is:

    >>> print 'call: repr(A)  expect: repr(A)  get:', repr(A())
    call: repr(A)  expect: repr(A)  get: repr of A called repr(A)
    >>> print 'call: str(A)   expect: {}       get:', str(A())
    call: str(A)   expect: {}       get: str of A called repr of A called repr(A)
    >>> print 'call: str(B)   expect: {}       get:', str(B())
    call: str(B)   expect: {}       get: str of B called {}
    

    Meaning that str function calls the repr function automatically. And since it was redefined with class A, it returns the 'unexpected' value.

  • Hi,

    I have posted a workaround solution to it. Check it out ... you might find it useful: http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html

    P.S. Read the original post where I introduced the issue as well ... There problem is the unexpected behavior that catches you by surprise ...

matrix transforms on adjacent sprites causing subpixel gaps

I have three sprites, stacked on top of each other.

I modify their transform.matrix to give the appearance they are growing in unison.

However, small cracks sometimes appear between the tiles depending on the scaling factor.

cracks between sprites

I am wondering how to fix this.

I know that text objects in AS3 have options for sub-pixel rendering. Maybe a similiar setting exists for all of AS3? Other ideas?

Tactics which don't work: cacheAsBitmap.

package
{

import flash.display.Sprite;
import flash.geom.Matrix;
import flash.geom.Point;

import mx.core.UIComponent;

public class tmpa extends UIComponent
{

 private var _scale:Number;

 private var _s1:Sprite;
 private var _s2:Sprite;
 private var _s3:Sprite;

 private var _s1Pt:Point;
 private var _s2Pt:Point;
 private var _s3Pt:Point;

 private var _tileDim:int;


 public function tmpa( ):void
 {
  _scale = 1;
  _tileDim = 100;

  _s1 = new Sprite();
  _s2 = new Sprite();
  _s3 = new Sprite();

  paintSprite( _s1, _tileDim );
  paintSprite( _s2, _tileDim );
  paintSprite( _s3, _tileDim );

  _s1Pt = new Point( 100, _tileDim );
  _s1.x = _s1Pt.x;
  _s1.y = _s1Pt.y;
  _s2Pt = new Point( 100, _tileDim*2 );
  _s2.x = _s2Pt.x;
  _s2.y = _s2Pt.y;
  _s3Pt = new Point( 100, _tileDim*3 );
  _s3.x = _s3Pt.x;
  _s3.y = _s3Pt.y;

  addChild( _s1 );
  addChild( _s2 );
  addChild( _s3 );

  scale = 1.0394; //cracks
  //scale = 1.0306; // nocracks
 }

 private function paintSprite( s:Sprite, dim:int, color:int=0xFF0000 ):void
 { s.graphics.beginFill( color, .5 );
  s.graphics.drawRect( 0, 0, dim, dim );
  s.graphics.endFill( );
 }


 public function set scale( s:Number ):void
 { _scale = s;

  var scaleFromPt:Point = new Point( 20, 20 );
  updateSpriteMatrix( _s1, _s1.globalToLocal(scaleFromPt), _s1Pt );
  updateSpriteMatrix( _s2, _s2.globalToLocal(scaleFromPt), _s2Pt );
  updateSpriteMatrix( _s3, _s3.globalToLocal(scaleFromPt), _s3Pt );
 }

 public function get scale( ):Number
 { return _scale;
 }

 private function updateSpriteMatrix( t:Sprite, ctrPt:Point, regPt:Point ):void
 { var mx:Matrix = t.transform.matrix;
  mx.identity();
  mx.scale( _scale, _scale );
  mx.translate( ctrPt.x*(1-_scale), ctrPt.y*(1-_scale));
  mx.translate( regPt.x, regPt.y );
  t.transform.matrix = mx;
 }

}
}

And the mxml:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
   xmlns:a="*"
   width="100%" height="100%"
   paddingTop="0" paddingBottom="0" paddingLeft="0" paddingRight="0"
   backgroundColor="0x000000"
   backgroundGradientAlphas="undefined">
 <a:tmpa id="t" width="100%" height="100%" x="0" y="0" left="0" top="0"/>
</mx:Application>
From stackoverflow
  • The reason there are gaps is due to rounding errors. Flash can only position elements down to 1 twentieth of a pixel (a twip). You were setting the y positions at

    • 3.152000000000008
    • 7.092000000000018
    • 11.032000000000028

    respectively. Obviously this is much more precise than a twentieth so rounding occurs. Once rounding happens you are prone to errors.

    In my opinion you should be putting all the items inside some other container and then scaling the container. The way you only perform one transform but get the same result.

    However i understand there may be a need for this method in some situations. The way round this is to perform all the scale transforms first. Then perform the translations relative to the previous sprite. That way it's always going to be based on the previously rounded potion. Here's a quick example hacked out of your class. Obviously there are many ways to organise this but I've tried to stick toy the way you work for simplicity.

    package
    {
    
    import flash.display.Sprite;
    import flash.geom.Matrix;
    import flash.geom.Point;
    
    import mx.core.UIComponent;
    
    public class tmpa extends UIComponent
    {
    
            private var _scale:Number;
    
            private var _s1:Sprite;
            private var _s2:Sprite;
            private var _s3:Sprite;
    
            private var _s1Pt:Point;
            private var _s2Pt:Point;
            private var _s3Pt:Point;
    
            private var _tileDim:int;
    
    
            public function tmpa( ):void
            {
                    _scale = 1;
                    _tileDim = 100;
    
                    _s1 = new Sprite();
                    _s2 = new Sprite();
                    _s3 = new Sprite();
    
                    paintSprite( _s1, _tileDim );
                    paintSprite( _s2, _tileDim );
                    paintSprite( _s3, _tileDim );
    
                    _s1Pt = new Point( 100, _tileDim );
                    _s1.x = _s1Pt.x;
                    _s1.y = _s1Pt.y;
                    _s2Pt = new Point( 100, _tileDim*2 );
                    _s2.x = _s2Pt.x;
                    _s2.y = _s2Pt.y;
                    _s3Pt = new Point( 100, _tileDim*3 );
                    _s3.x = _s3Pt.x;
                    _s3.y = _s3Pt.y;
    
                    _s1.transform.matrix = new Matrix();
                    _s2.transform.matrix = new Matrix();
                    _s3.transform.matrix = new Matrix();
    
                    addChild( _s1 );
                    addChild( _s2 );
                    addChild( _s3 );
    
                    scale = 1.0394; //cracks
                    //scale = 1.0306; // nocracks
            }
    
            private function paintSprite( s:Sprite, dim:int, color:int=0xFF0000 ):void
            {       s.graphics.beginFill( color, .5 );
                    s.graphics.drawRect( 0, 0, dim, dim );
                    s.graphics.endFill( );
            }
    
            public function set scale( s:Number ):void
            {       _scale = s;
    
                    scaleSpriteMatrix( _s1 );
                    scaleSpriteMatrix( _s2 );
                    scaleSpriteMatrix( _s3 );
    
                    translateSprite(_s2, _s1);
                    translateSprite(_s3, _s2);
            }
    
            public function get scale( ):Number
            {       return _scale;
            }
    
            private function scaleSpriteMatrix( targetSprite:Sprite):void
            {       var mx:Matrix = targetSprite.transform.matrix;
                    mx.scale( _scale, _scale );
                    targetSprite.transform.matrix = mx;
            }
    
            private function translateSprite( targetSprite:Sprite, basedOnSprite:Sprite):void
            {       var mx:Matrix = targetSprite.transform.matrix;
                    mx.translate( basedOnSprite.x, basedOnSprite.y + basedOnSprite.height);
                    targetSprite.transform.matrix = mx;
            }
    
    }
    }
    

    Hope that helps

    James

    jedierikb : Using your example, scale = 1.9666 results in a crack (actually overlap) where s1.y=0, s2.y=196.65, s3.y=393.3. ( fix with s3.y += .1 ) Working in twips seems to be the "right way" to resolve this. Are there good pixel/twip conversion/measuring tools out there?

String input to flex lexer

I want to create a read-eval-print loop using flex/bison parser. Trouble is, the flex generated lexer wants input of type FILE* and i would like it to be char*. Is there anyway to do this?

One suggestion has been to create a pipe, feed it the string and open the file descriptor and send to the lexer. This is fairly simple but it feels convoluted and not very platform independent. Is there a better way?

From stackoverflow
  • See this section of Flex's manual for information on how to scan in-memory buffers, such as strings.

    Björn Skoglund : Oh man, I can't believe I missed that.
  • The following routines are available for setting up input buffers for scanning in-memory strings instead of files (as yy_create_buffer does):

    • YY_BUFFER_STATE yy_scan_string(const char *str): scans a NUL-terminated string`
    • YY_BUFFER_STATE yy_scan_bytes(const char *bytes, int len): scans len bytes (including possibly NULs) starting at location bytes

    Note that both of these functions create, return a corresponding YY_BUFFER_STATE handle (which you must delete with yy_delete_buffer() when done with it) so yylex() scan a copy of the string or bytes. This behavior may be desirable since yylex() modifies the contents of the buffer it is scanning).

    If you want avoid the copy (and yy_delete_buffer) using:

    • YY_BUFFER_STATE yy_scan_buffer(char *base, yy_size_t size)

    sample main:

    int main() {
        yy_scan_buffer("a test string");
        yylex();
    }
    
    Vasco Fernandes : this answer is a copy of the flex manual linked below, with some sentences cut and mangled. The actual text from the manual is much better.

Extension method library for actions on System.Drawing.Color

Has anyone written a nice extension method 'library' for System.Drawing.Color.

Would be nice to say :

 Color.Red.AdjustBrightness(.5)
 Color.Red.AdjustAlpha(.5)
 Color.Red.ToHSV()

or something like that.

Alpha is easy, but others become time consuming because you have to go off and fine all the right mathematical equations for HSV and HSB and all that fun stuff.

Hoping someone else had done the work already :-) Microsoft doesn't seem to want to do it for me.

From stackoverflow
  • CodeProject has some code for an HSBColor class. It doesn't include extension methods, but they would be very straightforward to write once you have the HSBColor class and its associated conversion code available.

playing(and controlling) mp3s in Python

First things first, I am a Python beginner, with a typical C++/Java background for object oriented stuff.

I was convinced to try Python for this current endeavor I am working on, and so far I like it. One issue I am having though is finding a good mp3 module.

I have tried TkSnack, which installed and ran fine with no errors(as long as my audio device wasn't busy) but it could never actually produce a sound, it just did nothing... I went online for help, and was disappointed with the amount of documentation.

So I decided to switch. I tried PyMad because it is in the standard repositories for Ubuntu as well. There was even less documentation on this, but I could make it play a sound. The only problem is that it requires a loop to constantly write/play the audio buffer. This makes it particularly hairy to handle playback control(in my opinion) cause I would have to run this in a separate thread or process, and somehow control the seek position for pause and such. This is a little too low level for why I am using Python. I liked the simplicity of TkSnack for its easy commands like "mysound.play()" or "mysound.pause()" rather than controlling a loop.

I also looked at pyMedia, which looks like it is the most up to date with documentation, but I can't get it to install on my machine. I get a "gcc exited with value 1" error or something like that when running the "python setup.py build" command.

So I am looking for any suggestions or help on one of these modules, or a completely different one, that is high level and easy to use for mp3s(and preferably other formats too) I am trying to have basic playback control(pause, stop, skip, seek) and I may also be streaming files too eventually(if I ever get there).

EDIT: I like the python bindings for Gstreamer, but is this a cross-platform solution?? I forgot to mention that as a requirement. But I always just associated GStreamer with Linux, would this work on other OSs?

EDIT: Wikipedia says yes.

From stackoverflow
  • Sorry I can't help you with PyMad or pyMedia, but I have other suggestions.

    Existing music players written in Python:

    All of the above use the Python bindings for the GStreamer multimedia framework. Docs for the bindings are scarce, but check here, here, here, and examples from the source distribution here.

    gnomed : I like the idea of communicating with GStreamer, since thats how most audio/video programs work in linux already. But would it still be applicable if I wanted to make it cross-platform?
  • I just had to deal with this, and from my research I think your best bets are pyglet and pygame. They're interface packages with built-in a/v support.

    gnomed : pyglet looks promising, I'm a little too busy for the next couple days to try implementing with it. But I will let you know if I do.

How to update page data after event handling?

On Page_Init I create a table of dynamically created controls based on a couple of database tables. One of the controls is an ImageButton for moving an list item up the list. What this event handler does is to update the SortOrder column in the database for the affected items.

Now the problem is that since the controls are created in the Page_Init event and the SortOrder is updated later on when the ImageButton command event is fired. What's the best procedure for updating the table with the correct SortOrder. If I recreate the table after the event has fired the ImageButton command event does not work any more.

  • Should I implement a method for updating the data in the table without recreating it?
  • Should I reload the page in code after the event has fired?

What's your preferred way for solving this problem?

From stackoverflow
  • You'll need something like this...

    • OnInit (IsPostBack = false)
      • Dynamically create ImageButton
      • Wireup ImageButton Event Handler
      • Load Table - Check for a sort-order in Session/Variable. If none; use the default

    Click the button

    • OnInit (IsPostBack = true / 1st Postback)

      • Dynamically re-create ImageButton
      • Wireup ImageButton Event Handler
      • Load Table - with default sort order
    • ImageButton_OnClick (Still the same 1st postback)

      • Reload Table - with specific sort order
      • Save this sort-order variable in Viewstate/Session variable

    Cause some other Postback

    • OnInit (IsPostBack = true / 2nd & Subsequent Postbacks)
      • Dynamically create ImageButton
      • Wireup ImageButton Event Handler
      • Load Table - Check for a sort-order in Session/Variable. If FOUND, use that.
    Cerebrus : Telepathy, I tells ya! +1
    Eoin Campbell : What is it they say about "Great Minds" ;-)
    Cerebrus : ummm... "Great minds vote for each other" ? ;-)
    Eoin Campbell : indeed they do :p
  • Page events such as Init and Load will always fire before the event handler that raised the postback. This is the basis of the Page lifecycle (For a visual representation by Peter Bromberg, see here). Most developers new to ASP.NET have a major problem understanding and appropriately handling this "quandary".

    The ideal way to do this is:

    a. Your Page_Init should call a procedure (let's call it BindData() for illustration) that handles the creation of the table based on database data. This method would be similar to a binding method that binds to the database data and renders UI elements on the basis of that binding. IOW, you should remove the table creation code from the Page_Init method and put it in a separate method so that it can be called when needed.

    Important note: This BindData() method also handles the attaching of the eventhandler for the dynamically created ImageButton control to the control. We'll call this ImageButton_Click. This is crucial for the control to the event to fire on subsequent postback.

    b. When your ImageButton_Click method executes, it calls the BindData() method to recreate the table and it's bindings but with new sort order rules.

    So, the order of execution on first load is:

    1. Page_Init
    2. BindData()

    The order of execution on subsequent loads (on postback) is:

    1. Page_Init
    2. BindData() - Eventhandler for ImageButton attached.
    3. ImageButton_Click
    4. BindData()
  • Firstly, you seem to be binding your data manually to UI controls. In Asp.Net there and many ways to avoid this using built-in data binding techniques. Many controls like the GridView allow automatic creation of Html tables from a given data source. There are many other options including Repeaters.

    However you do choose to bind your data, the technique is to rebind at some point every time through the page lifecycle.

    You need to...

    1. Bind you data on first page load with the default sort order
    2. Rebind the data in the image button’s event handler after the sort order has been changed.

    The code would look something like this...

    private void Page_Load (...)
    {
        if (!IsPostBack)
            //On First Load
            BindData(defaultSoortOrder);
        else
            BindData(currentSortOrder);            
    }
    
    private void ImageButton_Click (...)
    {
        currentSortOrder = newSortOrder;
        BindData(currentSortOrder);
    }
    

    If the Image button is clicked, you will end up calling BindData twice. But this is necessary since a page postback could be initiated from any control, you need to always ensure you bind the data when the page loads.