Sunday, May 1, 2011

How to Invoke if the form is not active?

Till this moment I used this method to invoke:

    public string AddText
    {
        set
        {
            if (listView1.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    Textbox.text += value + "\n";
                });
            }
            else
            {
                Textbox.text += value + "\n";
            }
        }
    }

And here is the problem:

    var form = Form.ActiveForm as Form1;
    if (form != null)
        form.AddText = "Test";

I'm writing an analyzer which analyze packets. I can't put the form on focus all the time, because I have to do actions on the application. I'm writing this analyzer in order to get a packet so I can analyze it.

If I touch the application I want to analyze Form.ActiveForm returns null.

Is there a way I can invoke and set the textbox to add text even if the form is not on Top of everything?

From stackoverflow
  • You could possibly use a Unit of Work pattern for this with the OnActivation event of the form.

    Put the 'if active form' check in you AddText method. if the form is not active, put the text into a List for later.

    Then, handle the OnActivation event of the form, and if the list has values push them back thu AddText. Then when the form becomes activated (this happens when the form gets focus) the text will fill.

    Even if the OnActivation part doesn't work, this general patter should do the trick.

  • I think the root of the problem is the tight coupling between your packet analyzer and the main form. A packet analyzer should not have to know anything about the active form, or even that there is any form at all. It makes things hard to maintain because it only works under a very specific circumstance that's already untrue some of the time.

    You could turn the problem around, and raise an event from the class that is analyzing the packets. That gives you much better encapsulation because now the packet analyzer needs to know nothing about the rest of the application. You can either create your own event args or reuse one like System.Diagnostics.DataReceivedEventArgs for example. Then your form can sink the DataReceived event and call its own AddText to invoke back to the main thread, and it will work whether the form is visible or not.

    At least that will work but it is a blocking call so the packet analyzer thread will be stopped until the form fully handles the event and the marshalled call back to the main thread has returned. That would be okay if the paket rate isn't very high but usually you wouldn't want to stop a communication thread to wait for the main thread to update a textbox. Another approach would be to log the text using a StringBuilder inside the packet analyzer, and expose it (the accumulated text, not the StringBuilder) via a thread-safe public property. Or if you need to separate the invidual messages then you could add them to a List for example, and have the thread-safe property return an array of accumulated messages. Then your form could poll the analyzer for new logged data using a Timer at whatever rate is appropriate for your application, and only while the form is visible. It would not update quite as fast but the impact on the analyzer thread would be almost nil and it should run faster overall if it consolidates many messages inside the StringBuilder or List in between updates rather than concatenating on to the Text property with every single packet.

  • If the problem that you can't Invoke then your answer would be to use SynchronizationContext it's always available on the Application.Run thread. So do the following:

    In Form OnLoad save SynchronizationContext.Current to static field anywhere. After that you can easily use Post or Send methods for sync or async invokes in GUI Thread.

    Description here: http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx

    Nice article here: http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx

  • Split the problem into two parts. Log your text using Trace.TraceInformation() and implement a TraceListener that handles the display aspect.

    This way, you can redirect your log output to a file, or the Windows EventLog, or your UI, or whatever, simply with an entry in a config file. You don't have to pick just one. You can do all of the above if it helps.

    This is such a mundane and frequent problem that the MSDN sample for implementing a TraceListener is exactly what you need.

iphone app submission. creating screen shots.

When submitting screen grabs for an iphone app during the approval process, is it ok to submit screens that are different than what is represented on the app itself? for example, i wanted to submit a screen where i explain some of the features of the app but not necessarily a screen grab.

all the best.

From stackoverflow
  • People seem to do it fairly often - I've seen several cases where the "screen shots" were something else entirely. I think as long as you're not deliberately misleading, you'll be fine.

  • As Mark mentioned, this seems to be accepted fairly often, though personally I would not encourage it. When I see images like those in the screenshot collection I'm immediately suspicious. Your app should be simple enough that the screenshots show the user what is available. What your screenshots do not convey, you can explain in the text that you submit

    Brad Larson : Agreed. I don't recommend this, as it doesn't look very professional. Any features should be concisely described within your text listing. Walkthrough videos on your supporting website can help explain things that text and images can't convey.

Upgrading a J2EE application to Java 6

With the upcoming end of life (EOL) of Java 5.0. We need to upgrade our enterprise application to work with Java 6. The application can be deployed on both WebLogic, WebSphere & JBoss. (It's up to the customer's choice)

Does anyone have an experience with such an upgrade? What issues should we encounter? What pitfalls we should avoid?

From stackoverflow
  • Why, I would follow the JavaSE 6 Adoption Guide!

    http://java.sun.com/javase/6/webnotes/adoption/adoptionguide.html

    The upgrade usually is pretty straight forward...

    Tom Hawtin - tackline : Not much of a problem in this case.
    duffymo : I thought the enum keyword was introduced in Java 5. Shouldn't be an issue moving from 5 to 6.
    altCognito : Good point, sigh... What a day. Removed...
  • Your biggest problem will be with the WebSphere, WebLogic etc.

    Are they all certified to run on Java 6.

    I am surprised that Java 5 is EOL so quickly - in practice Sun will offer patches for years.

    Tom Hawtin - tackline : The new practice is not to offer *free* support for so many old versions. Support is available through Java for Business.
    Fortyrunner : Wow. Just looked at the Sun policies for EOL. They have been much more aggressive with 1.5 retirement than 1.4 was. Lucky we moved onto 1.6 nearly two years ago.
    duffymo : WebLogic 10.3 is the first version that ships with JDK 6. The earlier releases of 10.x ship with JDK 5.
  • One problem you may encounter is if you use JAXB 2.1. See this link for details.

  • At my last job, we had to do this; it was put off for a long time. When we got to doing it, it took no time at all in the grand scope of things. A few interfaces expanded to add new functionality, the enum keyword was used and promptly refactored, etc.; nothing major. We supported the same app-servers you do, and they all work just fine with Java6. The whole thing turned out to be something an intern could do.

    LiorH : Thanks, that's sound encouraging
    geowa4 : that's just my experience. your system might be different.
  • Can't do anything specific to WebLogic, WebSphere, or JBOSS. You have to include whatever special config each one needs in the distro at all times.

    The only way I find I can migrate between app servers without changes is to use Spring. I can move a WAR from Tomcat to WebLogic without issues, but only if I include the META-INF/context.xml for Tomcat and weblogic.xml for WebLogic.

Why don't I have to release these objects?

Here's an sample code, where only the "string" object is released.

NSString *nameOfFile = ... ;
NSError *error;
NSString *string = [[NSString alloc] initWithContentsOfFile:nameOfFile encoding:NSUTF8StringEncoding error:&error];
if (string == nil) {
    // handle error
}
[string release];

I understand why the error object is not released. This is, since the method here did not create that error object with an "new" or "alloc" method. Instead, this one is returned by reference, so the initWithContentsOfFile method is responsible for that memory. But what about the nameOfFile object? Why don't they release it? It's not returned by reference...?

From stackoverflow
  • similar to why you do not need to release error, you also do not need to release nameOfFile. In Objective-C if you declare a string as NSString *temp = @"Hello" it is treated as a string constant and it does not need to be released. The memory reference count is zero so it does not need to be released.

  • Assuming nameOfFile is a constant string, then it automatically has a retain count of 7fffffff (i.e. 2147483647, the highest possible retain count). Basically, string literals last for the duration of execution and are never deallocated, so you should never worry about releasing them.

    Remember, you only need to release an object if you have either retained it or explicitly allocated memory for it.

    See Apple's documentation for more information.

    paxdiablo : You need either two more 'f' characters in that hex value, or the decimal should be 2^23 - 1, not 2^31 - 1.
    htw : Thanks—I made a typo when typing that hex value out. Lost track of how many bytes I had written. Sorry about that—fixed.
    Ahruman : The string isn’t “automatically added to the release pool”. Constant string objects are never deallocated, and releasing or autoreleasing them has no effect. On the other hand, only one instance of the string (per source file) exists.
    htw : Yup, I checked the documentation again, and you are indeed correct. Fixed.

Differences between UNIX and Windows development

I've been programming in C and C++ in Linux for around 3 years, and recently have been interested in developing commercial software for businesses. Let's say I've found a niche where I think I could be successful, but that they only use Windows. I have no experience whatsoever with the Windows API, however. I have a few questions:

Should I learn .NET?

Do I need to learn C# in order to use .NET, or can I stick with C++?

What is the sentiment about compiling using GCC under Cygwin with the --no-cygwin option? I'm interested in portability, and I'm worried that if I start writing for VC++, I might get bound to Windows.

Where is a good place to do my essential reading?

What else can you tell me about transitioning from Linux to Windows programming?

From stackoverflow
  • You can use C++ for .NET development, but it'll be a somewhat modified version of C++ (C++/CLI). You might as well just learn C#, to be honest. (Personally I think C# is a beautiful language, but there we go.)

    There's much more to learn in terms of the framework itself than languages - even though the languages have been gaining features, the libraries have been growing even more quickly.

    All of this is still simpler (IMO) than learning the Win32 native API though.

    For essential reading, I'd recommend "C# 3.0 in a Nutshell" and "CLR via C#". (Links coming when I'm not overdue laying the table for dinner...)

    TheTXI : That damn family time interfering in Jon Skeet's important work!
    Lucas : Note that when Jon mentions C++/CLI he means for .NET Framework (managed) development, not native Windows API development.
    Jon Skeet : Thanks Lucas - updating the answer now to make that clearer...
  • Should I learn .Net?

    Depends on whether or not you feel this would be advantageous to the niche your are looking at. For instance, if your niche is a desktop application it's probably a good idea to get started because, IMHO, it's so much easier to develop a WinForms,WPF GUI than a C++ version,

    Do I need to learn C# in order to use .Net, or can I stick with C++?

    C# is not a requirement and using C++/CLI allows you to take advantage of .Net while still using C++. However, I tend ot only use C++/CLI for components which are heavily focused on interop between managed and native code. It is particularly good at that kind of development. If you switch to more mainstream applications I think you'll find that C# or VB.Net will suite you better. Most of the online samples are geared towards these languages. In particular a good portion of the tooling is heavily geared to these languages (WinForms and WPF designers to start).

    Worried about writing non-portable code and being tied to VC++

    I'm sure this opinion will be slightly unpopular. But you've already mentioned that the niche you're looing at is Windows specific. What is the point of writing portable code if you will only ever run it on Windows? This is not a Windows bias coming out, I would make the exact same argument if the platforms were reversed.

    I'm not saying portable code is a bad thing. It is in fact a very good thing. But if there is no potential for using the portability why not take advantage of the platform instead?

    David Thornley : Speaking as a Unix fan, +1 for your last two paragraphs.
  • The answer depends on the type of program you would like to implement.

    If you would like to implement some system utility then the answer is pretty much the same as on *nx world: you will have to programm in C for best results and to know Win API very well.

    For other things, C# is probably the way to go today. Its the best language, IMO, from the existing dotNet languages.

    Learning Windows API is definitelly good thing to do, but I suggest using some of the scripting languages for that for faster experimenting (Lua with Alien library, Python , AutoIt etc..). The good thing about it is that you probably know some of them, coming from *nx community.

    Since you are worried about portability I suggest you using C# with special care about OS specific things like path separator, file name case sensitivity etc.. you can find some nice articles about it on MonoDeveloper site. Java is also good way to go - I am not an expert but from what I know its trading some language sophistication and speed and native feel (looking from C# perspective) for better portability.

    Latest MonoDevelop makes you even load Visual Studio projects, although I never personaly did that.

  • If you're interested in portability of your code, you must produce both a Linux version and a Windows version at the same time. If you try to write Windows code while just thinking about being portable you will invariably end up with Windows specific elements to your code.

    If you're going to use Windows, you might as well learn C#. C# is actually pretty cool; it's pulled more Lisp features in than C++ has. Learning it is straight forward. Your best learning resource is Google, although if you're a book learner, go buy any book on C#.

  • It all depends. Should you choose to use C++ and you're developing a GUI application, there are several GUI frameworks to choose from (wxWidgets, GTK), most of which are also platform-portable. If you're just specifically targeting Windows, having the .NET libraries as a dependancy isn't a problem, and you don't mind the time involved in learning a new (but still familiar) language, then C# might be better in your case.

  • I faced exactly the same questions and I am so happy I tried .NET. I hope this info can help you:

    Should I learn .NET?

    I would highly recomment it.

    Do I need to learn C# in order to use .NET, or can I stick with C++?

    You can stick with C++ but I am sure you will love to learn C#, please try it. You will be able to mix them too. The main challenge with .NET is to learn all the libraries that are out there to help you out (so you do not need to reinvent the wheel). Use msdn often and try to get a map of the fundamental classes and assemblies.

    It is a fun experience if you come from C++ you should not have major problems.

    Where is a good place to do my essential reading?

    I would start with something light, check the free Visual Studio tools, software and examples here, go to the MSDN documentation and compile some of the examples in MSDN (how to access files,...). As you can see you will find C# and C++ examples side by side.

    Then of course books like C# via CLR will eventually need to be read.

    Portability

    Be sure you run your code in Mono and multiple platforms.

    Future investment

    Investing on learning the .NET framework will pay back. Today is costly to learn all the new tools out there, with .NET you know you can evolve. New features and languages appear but the fundamental classes remain so your time/effort investment is more under control.

    Lucas : +1, especially for noting that .NET and C# can be portable (Mono)
    majkinetor : +1 for the map :D
  • This is a great question. The firs thing you need to determine is if you need to write cross platform code. If you do, then C/C++ is the best path using some cross platform UI libraries.

    If not, then I highly recommend .NET 3.5 using Visual Studio 2008 SP1. I also recomned using WPF instead of WinForms for your UI.

    By no means is MSFT de-investing in native code development; but C# .NET 3.5 WPF and related tools are the future for application development - especially for Line Of Business kinds of things.

    I believe you will find this very productive and easy to learn. You can also get good development tools for free here.

  • What Linux-based GUI libraries do you use? QT? GTK? Chances are there are Windows ports of these libraries. If you need to stay platform independent, stick with what you know. If you see yourself needing to be Windows only, only then should you switch a .NET solution.

    David Thornley : He's selling Windows software to businesses. He doesn't need platform independence as much as a standard Windows UI.
    jmucchiello : And his next client only uses Windows? And the next? If he is comfortable with a cross-platform UI library it can't hurt to use it with a Windows-only client. Certainly the learning curve for .Net is steeper than learning the idiosyncrasies of a known library under a new OS.
  • Do I need to learn C# in order to use .NET, or can I stick with C++?

    Go with C#. C# and .net is a great combination.

    Also, not strictly programming related, but a bit Unix vs Windows. Unix have always had an excellent shell that have made life easier for a programmer. Windows now also have that. Learn a bit about Powershell and how to write cmd-lets, it will save you lots of time.

    Powershell is one of the best things that have come out of Redmond in a while.

    http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx

  • Should I learn .NET?

    Yes.

    Do I need to learn C# in order to use .NET, or can I stick with C++?

    Technically, no, you don't have to learn C# for .NET.

    if I start writing for VC++, I might get bound to Windows.

    It's a Windows shop, right? Who cares if Windows programs are portable, if your only target is Windows?

    Where is a good place to do my essential reading?

    Stackoverflow.

    What else can you tell me about transitioning from Linux to Windows programming?

    Buy a Windows machine and Visual Studio. Don't try to half-Unix it. Spend the quality time and effort on learning the Microsoft Way. Just like there is a Unix Way, there is a MS Way. Both apply to their respective systems.

    Good luck and have fun!

  • Lots of people seem to be ignoring the original question of "Differences between UNIX and Windows development" and so I will talk a little about that.


    Regarding should I learn C#:

    I think you need to learn a language like C# [1] at some point. The question is not a matter of if you should learn it but when when you will learn it.


    Regarding alternative similar languages to C#:

    Java is another language that is very similar to C#. Java IMO is the father of C# and IMO I prefer Java.

    I offer you a metaphor to explain my predilection towards Java. Java had this son C# who saw all the success of his father. The son got jealous and tried to do the same thing his father was doing.

    In the this case, MS is the upstart son trying to upstage the older father. However the upstart C# is missing a couple of key things IMO:

    • truly cross-platform
    • smaller library of tricks owning to the shorter lifespan of C# ( or as I like to call it a smaller box of pre-built legos )
    • I prefer Java for the above two bullet points.

    [1 - footnote ] When I say "a language like C#" I am referring to the fact that there are other languages with similar features. Specifically features like: garbage collection, 100% object oriented from the start ( vs C++ hacking in OO ), built in xml-type-documentation ( think of javadoc ) and flexible to do many different things.


    Regarding should I learn .NET:

    I have only done a small/intermediate amount of C# but from that small amount I noticed that .NET is pretty much required when you do anything C#. ( I understand that C# is very very incestuous with .NET and hard to peel apart. ) The way I understand it and I may be wrong... most/all of C#'s standard main library's are C# and therefore you need to have .NET if you are doing C#.


    Back to the original question "Differences between UNIX and Windows development":

    • Windows development is not as diverse IMO... there is only one development environment and that environment is MS compiler and MS IDE both packaged as one in their Visual Studio product line.
    • Windows development focuses on GUI driven tools.
    • Linux development is more diverse with hundreds of compilers/text editors/IDEs/etc. ( I say it is diverse but in reality the majority of Linux development is actually very similar using a collection of common tools: GCC/GDB/GREP/FIND/VIM/EMACS/CTAGS/CSCOPE and some source repository of choice ).
    • Linux development focuses on command-line-interface driven tools.
  • You're going to be selling commercial Windows software to businesses. Check out the businesses. Figure out what else they buy, and check the recommended platform information. That will give you a good idea of what they have, and what to aim for.

    You probably want to learn .NET (hey, you're going to have to learn a new framework anyway), and C# isn't going to be difficult to learn if you're good at C++. That seems to be the standard development environment nowadays, probably for good reasons.

    If you're worried about portability, write the back end in C++ and isolate the system-dependent parts. If you're going to sell Windows software to businesses, it has to look like Windows software. It has to behave as they expect. Do not compromise the UI for any advantage in being cross-platform; instead, separate the UI logically. You can always rewrite it later for other platforms.

    Similarly, go ahead and use Visual Studio. It's a nice environment, although I sometimes miss gcc, gdb, and make, but it's likely to make you more aware that you're writing a Windows program. If you use Cygwin and gcc, you're likely to not think like a Windows programmer, meaning it won't look like a Windows program, meaning your potential customers are going to have problems with it, meaning less money and more chance for a late mover to capture the market.

    I found that moving to Windows programming wasn't difficult. Just be aware that you are learning something new, and that some things are standard in Windows that aren't in Unix. If you aren't afraid of learning new stuff, you'll do fine.

    One more thing: Unix applications are frequently notorious for clunky UIs. Unix users tend to be more technical people, who don't pay as much attention to how things look and are much more forgiving of ugly interfaces. In the Windows commercial software world, looks and ease of use matter, and the actual users are likely to be people with a wildly inaccurate mental model of the computer, who wouldn't recognize a line of Python code if it bit them in the face.

    You are going to need a reasonably attractive UI that can be easily used by people who don't care about computers per se. This is a stretch for a lot of us. If you don't think there's anything special about an iPhone, you badly need another point of view. Read up on user interfaces, find somebody else with some artistic sense and some idea of usability, anything. UI design is a different skill from programming, and many people have only one of them (around here, people tend to be skilled programmers, and may have some UI skill).

A few ListView questions

The documentation of the ListView control (using WinApi) seem to lack some basic information, here are some questions I couldn't seem to find a solutin to:

  1. On most apps, when you double-click the border to the right of a column, the column resizes to some default width. I would have guessed that this width is specified by LVCOLUMN.cxDefault or cxIdeal, but it doesn't seem to do it. What am I missing?

  2. When you click a certain column to sort the list according to, a little arrow indicating the direction of the sort appears on top of it. How do I make it appear? BTW, does anybody know which sorting algorithm ListView uses?

  3. When in report view, any way to select a whole row instead of just the first item? (It's just a visual thing, functionally it's identical)

  4. Any way to insert multiple items at once?

From stackoverflow
    1. It's calculated based on the rendered width of each item in that column.
    2. The arrow is a custom image set by your program. If you don't set an image (by associating an image list with the header and then specifying an image for each header item by index), then you don't get one. I don't know what the sort algorithm is, but the item comparison algorithm is whatever you want it to be - you must specify a callback.
    3. Yes - set the LVS_EX_FULLROWSELECT extended style on the control
    4. No. But you can turn off redraw while adding multiple items.

    My best recommendation for you if you're new to working with the ListView control is to read the numerous articles on CodeProject. Even if you're not working with MFC (as many of the articles are) the concepts still apply - just translate calls to the equivalent PlatformSDK macros.

    Meat : Thanks for the answers. 1. Obvious. Don't know how I didn't notice that. 2. Seems like an overkill. Windows seems to have some default graphics for that arrow. Plus, it's different for each visual style, how should I match that standart with a custom image? 3. Works like magic. 4. Would look into that
    Shog9 : If you can afford to drop pre-XP compatibility, you can use the v6 common controls and get some extra goodies (like, themes, groups, selected column indicator, etc). I haven't worked with this enough to know if you get sort images with that however.
    Meat : Any hint where can I look into it?
    Meat : Found it .
    Meat : "The sorting algorithm is whatever you want it to be - you must specify a callback.". Not entirly true. The callback only compares individual items, it doesn't suuply any sorting logic.
    Shog9 : Sorry, thought you were talking about the comparison function for some reason... Couldn't tell you what algorithm is used for sorting internally.
  • Ok, here's the answer to the second problem: http://www.winapizone.net/tutorials/winapi/listview/columnsortimage.php

SQL Server console like control for ASP.NET

I'm deploying a web site and I need to run large TSQL scripts contained in a single file in a production server where I don't have full access to SQL Server console and I can't connect remotely. The scripts is a mixed of table, stored procedures and views creations. All I can do is to run 1 group of TSQL sentences, like the ones for a stored procedure.

I have two options: to parse the file manually looking for GO's sentences and run each block of sentences before that GO, or to do the same task but with a tool. Using a tool I will be very fast doing the task, but I don't know any tool such that.

Do you know any tool that I can use?

I think it must be something like a control, with an editor where I will paste or load the scripts to run, and it will be able to parse and run them in sequence, like the Microsoft SQL Server Management usually does.

From stackoverflow
  • You could check out some articles on CodeProject on the topic and maybe use one of those tools / component for your needs?

    Most of those come with full source and could also serve you as a starting point for a custom version of your own.

    Marc

  • If those don't work, it's pretty easy to write such a tool yourself. Just use Regex.Split to split the text on the GO lines, then loop, calling ExecuteNonQuery for each section.

    jms : Heads up! If you go this route make sure "GO" is not embedded in a string or that you don't have a column named GO_time. Here is a fairly safe regex to use. "^\GO\w*$"
  • hi, you got many options

    • usually i create stored procedure in sql management studio then save it as string, then use linq2sql to execute the stored procedure, works very well.

    • use sql server smo object where you can really do mostly many things like creating DBs, tables, it is really cool, i create 1 page on my site and use it to update DB with it. here is a good link for that http://www.sqldbatips.com/showarticle.asp?ID=34

    • you can use Redgate SQL data compare, and Compare. they rock really to synchronize DBs, it have saved me a lot of time and it is super easy, highly recommended really.

    hope this helps.

Tutorial regarding the development of a custom Eclipse editor

I wish to learn about developing an editor for Eclipse for a particular programming language. Is there a tutorial available to help me with this? It would be beneficial if it covered such topics as syntax highlighting and auto-completion.

From stackoverflow
  • Have you tried installing a plugin for Eclipse that meets your needs?

    http://eclipse-plugins.info/eclipse/plugin_details.jsp?id=266

  • You're probably looking for something like this article on building Eclipse editors with JFace text. It's got enough to get you started and it goes through syntax highlighting, content assist, content outline, and error markers.

  • I started at this one. It was a year out of date when I used it, but the concepts have stayed the same.

    The best thing I can suggest in lieu of a how-to would be to take find a language that is already integrated, and see how they do it. Here's the real advice - don't pick one with a package name that begins with org.eclipse (like the ant one). There are so much support provided by eclipse, it is much easier to see what code you need to write if it starts with another package prefix. Try looking at the groovy or scala plugins, for example.

    In my experience, it is the error highlighting which is the hardest to do accurately; next hardest is content assist.

    If you are in control of the compiler or runtime of the language that you're writing an editor, it makes life a lot easier if you can get the compiler to give you all the data your IDE will need to present it to the user (e.g. list of tokens - for syntax colouring, tooltips; content assist will be much better, because you're not faking a compiler, but using the real one instead; same with error highlighting).

    The IDE has the relatively easy job of only displaying errors, and colouring, etc.

    Once you have it down to display only, the example XML editor looks quite useful.

    Much of the partitioning rules I have found less useful; I've always ended up building my own - binary search over a list of tokens is extremely useful.

  • The best one I've seen for a standard Eclipse text-based editor is

    http://www.ibm.com/developerworks/edu/os-dw-os-ecl-commplgin1.html

    (you need to sign up for a free IBM account). Prashant Deva, author of a really nice ANTLR2 plugin did this one.

    You may also want to look into tools that will generate an editor:

    Eclipse Modeling Project (EMF/TMF/GMF)

    http://www.eclipse.org/modeling/

    TMF helps build textual editors; GMF helps build graphical editors. A pretty good book is available (also on safari books)

    Tutorial at: http://wiki.eclipse.org/index.php/GMF_Tutorial

    A good intro on GMF: http://www.ibm.com/developerworks/opensource/library/os-ecl-gmf/

    Dynamic Languages Tool Kit

    http://www.eclipse.org/dltk/

    Tutorials available from that site. Note that you can use DLTK for static language editing as well; the "dynamic" part comes from the interpreter configuration and launching.

    Xtext (now part of TMF)

    http://wiki.eclipse.org/Xtext

    Note: good content assist can be quite difficult; it really involves follow-set analysis for every terminal in your grammar. You can simplify it quite a bit by just keeping track of defined symbols and keywords and just suggesting all that match the existing prefix. The generators above make this a little easier, but aren't perfect.

    Good luck!

Simple data - I just need simple way to analyze

Summary

I am after some advice on the easiest way to analyze simple data using SQL server and .net

Details

Really simple data - just need really simple way to analyze (with my simple brain)

I have a SQL Server table:

  • PKID (Int)
  • ApplicationName (VarChar)
  • MethodName (VarChar)
  • TimeInMs (Integer)
  • AdditionalInfo (VarChar)
  • DateTime (DateTime)

This table records the length of time it took for various methods to run in various applications. This table could potentially have tens of thousands of rows. I would like to easily extract useful info from this (some of it in real time). I am not sure of the best way to go about this. This kind of data I would like is:

Data - Average length of time for method call - Top ten slowest method calls - Top ten fastest method calls

For the periods of: - last min, hour, day, week, month - each day for the last 7 days, each week for the last 10 weeks

For the applications: - All - Each individually

From stackoverflow
  • Without adding timestamp information you will not be able to do meaningful analysis. At best you can create queries to summary statistics on the applications performance.

    select count(*) from table_name where ApplicationName = "BAR.EXE";
    
    select sum(TimeInMs) from table_name group by ApplicationName;
    

    Other than writing code to divide those numbers you cannot do very much.

    Update: With timestamp information you can adjust the where clause of the above samples to select the ranges you are interested in. Given the inexact nature of your question I might suggest importing the data into Excel (I don't have Excel installed) and massaging the data in various ways rather than directly messing with SQL.

    James : There is a DateTime column (It was missed off my example). It would be easy to add a timestamp column too if this proves useful. I have added them to my post above for clarity.
    ojblass : Do you have an easy way to run sql against the database?
  • I think ojblass was refering to the DataTime field you omitted from your question.

    The actual timestamp datatype in MS SQL Server is misleading in name. It has nothing to do with dates and times. It is a binary "version number". It is used mostly to deal with concurrency issues when updating a row in the table but would be useless for any analysis tasks.

    I would suggest improving your column names a bit. Calling a column "DateTime" is confusing and could cause you some trouble in writing queries if you aren't careful.

    Anyway... the queries you are looking for range from simple to quite complex if written directly in TSQL.

    Here are some examples (I have not syntax checked these, so they are "approximate" at best):

    Average time for a specific method

    select avg(TimeInMs) as AvgTime from Table 
    where ApplicaitonName = @ApplicationName
    

    Average time for a specific method during the last 1 minute

    select avg(TimeInMs) as AvgTime from Table 
    where ApplicaitonName = @ApplicationName and 
        [DateTime] >= DATEADD(minute, -1, getdate())
    

    You'll end up wanting to write stored procedures for most of these. Some of the queries you talk about will require some grouping and such too... I recommend you get a book on TSQL if you go this route.

    If you are doing this with LINQ to SQL within your applicaiton, it isn't much different, but in general LINQ is easier to write (debatable of course).

    Here are the same two queries using LINQ to SQL in C# (again, I haven't tested these, so I could be minor syntax mistakes).

    var ctx = new MyDataContext();
    var q = (from item in ctx.Table
            where item.ApplicationName == "MyApplication"
            select item.TimeInMs).Average();
    
    
    var ctx = new MyDataContext();
    var q = (from item in ctx.Table
            where item.ApplicationName == "MyApplication" &&
                  item.DateTime <= DateTime.Now.AddMinutes(-1)
            select new item.TimeInMs).Average();
    

    How you do the analysis depends on what technologies you are using and what you are doing with the results.

    Update: In answer to follow-up question from comments:

    I can't think of a good way to handle it via storing the desired time intervals in another table that doesn't get massivly difficult (cursors and dynamically constructed TSQL via the Execture command).

    A simpler query that gets the results you want might look like this in TSQL (I'm not advocating that this is the "best" way, but it works and is pretty fast).

    select avg(TimeInMs) as AvgTime, 'Last 1 minute' as TimePeriod from Table 
    where ApplicaitonName = @ApplicationName and 
        [DateTime] >= DATEADD(minute, -1, getdate())
    union
    select avg(TimeInMs) as AvgTime, 'Last 2 minutes' as TimePeriod from Table 
    where ApplicaitonName = @ApplicationName and 
        [DateTime] >= DATEADD(minute, -2, getdate())
    -- //repeat union as many times as needed for each time period
    
    James : But say I wanted to get the average time for a method for the following number of minutes: 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,120,240,360 Is there a way to, define the list of minuets in another table, then do some kind of join to get the results for all of these? I can see how to get the simple single pieces of info back now (and thanks for your input and Link examples). I am really after the best way to get the "multiple" pieces of data back at once (like the minutes example). I am surprised for such a simple seeming dataset, it is so hard!
    Stephen M. Redd : I amended my answer to include one example of what you are asking about. The problem here is the the queries you want are only simple for the human mind, but are actually reasonably complex problems from a SQL point of view. There are ways in TSQL to write very complex selects like you are asking about more elegantly, but such an answer is far outside the scope of what can be reasonably answered on a simple SO post. I'd recommend some serious training or reading on advanced TSQL if you'll be doing much of this kind of stuff in the future.
    James : Many thanks - that gives me a good starting point.

Set a navigation controller without an app delegate

I would like to show a Navigation Controller after clicking a button. Every tutorial assumes the navigation controller will be the first screen so it links it to the App Delegate, but App delegate only appears at MainWindow.xib. How do you guys add a navigation controller to a view different than the MainWindow?

Thanks!

From stackoverflow
  • UINavigationController is to navigate a heirarchy of views with UIViewControllers. If you don't have a root UIViewController, it won't work (and doesn;t make sense). If you do have a UIViewController, you simply send a - (id)initWithRootViewController:(UIViewController *)rootViewController init message to a new navigation controller passing in your UIViewController.

  • Here is some sample code to expand on Roger's answer. The following method is linked to some user interaction on the current view controller (to compose an email for example). This will give the compose view the navigation bar across the top instead of coding buttons inside your custom view.

    -(void) composeButtonPushed: (id) sender {
        ComposeViewController *controller = [[ComposeViewController alloc] initWithNibName:@"ComposeView" bundle:nil];
        UINavigationController *composeNavController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentModalViewController:composeNavController animated:NO];
    }
    

How can I apply an aspect using annotations in Spring?

Update: I've found the Spring 2.x annotation-based Controllers are horrible for AOP security because you can't make assumptions about the method prototype due to the increased freedom in params and return values. Before 2.x you could intercept handleRequest and know the first param was an HttpServletRequest and the return value was a ModelAndView. This standard allowed you to write simple advices for every controller. Now methods mapped to requests can take anything and return Strings, ModelAndViews, etc.

Original Post: I have a set of existing aspects which implement AOPAlliance's MethodInterceptor running in Spring. They provide security for my webapp by intercepting .handleRequest. methods in the Controllers and either allowing execution or forwarding to a login page.

With the new annotation-based controllers in Spring, the "handleRequest" method no longer needs to be implemented; the methods of the controller can be named whatever I want. This breaks my existing security model. So, how do I get from this:

    <bean class="com.xxx.aspects.security.LoginAdvice" name="loginAdvice">
         <property name="loginPath">
              <value>/login.htm</value>
         </property>
         <property name="authenticationService" ref="authenticationService" />
    </bean>

    <bean name="loginAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
         <property name="advice" ref="loginAdvice" />
         <property name="pointcut">
              <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                   <property name="pattern">
                        <value>.*handleRequest.*</value>
                   </property>
              </bean>
         </property>
    </bean>

    <bean id="someProtectedController" class="org.springframework.aop.framework.ProxyFactoryBean">
         <property name="target">
              <ref local="someProtectedControllerTarget" />
         </property>
         <property name="interceptorNames">
              <list>
                   <value>loginAdvisor</value>
                   <value>adminAdvisor</value>
              </list>
         </property>
    </bean>

...to being able to reuse my existing aspects and apply them to entire controllers or controller methods using annotations?

From stackoverflow
  • Could you use an AnnotationMatchingPointcut to look for methods on your controllers which have the @RequestMapping (or other similiar annotations that you use in your annotation-based Spring controllers)?

Why does my Volume Shadow Copy Service requester fail: cannot find CreateVssBackupComponentsInternal

I have implemented a VSS requester, and it links compiles and executes on Windows Server 2008, but does not execute on Windows Server 2003. Since my requester is inside a DLL, my DLL will not load. Using the Dependency Walker, I discovered that my DLL is finding VSSAPI.DLL just fine, but it reports:

Error: At least one required implicit or forwarded dependency was not found.

Looking at my VSSAPI.DLL, it cannot find CreateVssBackupComponentsInternal, while VSSAPI.DLL exports something completely different: ?CreateVssBackupComponents@@YGJPAPAVIVssBackupComponents@@@Z.

From stackoverflow
  • VSS must be compiled and targeted specifically for each platform and OS, including Windows XP, Windows Server 2003, and Vista/Windows Server 2008.

    The first Microsoft SDK to fully support VSS requesters is v6.1, and it only supports requesters running on Vista. If you want to run on Windows Server 2003 or XP:

    • Download VSS SDK 7.2.
    • Set your include and library paths to search the appropriate directory in the VSS SDK.

    The following is what AlphaVSS does in its Config.h, but the VShadow sample in the VSS SDK does not: it only sets the include and library paths. I would suggest that following VShadow is more likely to succeed. But for completeness:

    If targeting Windows XP:

    #define NTDDI_VERSION NTDDI_WINXPSP2
    #define _WIN32_WINNT _WIN32_WINNT_WINXP
    #define WINVER _WIN32_WINNT
    

    If targeting Windows Server 2003:

    #define NTDDI_VERSION NTDDI_WS03SP1
    #define _WIN32_WINNT _WIN32_WINNT_WS03
    #define WINVER 0x501
    

    If targeting Vista, don't reference the VSS SDK. Instead reference the Windows 6.1 SDK and:

    #define NTDDI_VERSION NTDDI_WS08
    #define _WIN32_WINNT _WIN32_WINNT_WS08
    #define WINVER _WIN32_WINNT
    

    I can't take all the credit for this, I figured this out by reading the source code of a project called AlphaVSS (see announcement), which exposes VSS to .NET code. MSDN did not seem to be very helpful. However, the VShadow tool and sample provided an example of how to compile a VSS requester.

    Also note that you must recompile again for x64 or ia64 vs x86. That means in order to support all platforms, you'll need 9 compiled versions of your executable.

    Jared Oberhaus : I also found someone else asking a similar question; they got the error: error LNK2019: unresolved external symbol _CreateVssBackupComponentsInternal@4 referenced in function "long __cdecl CreateVssBackupComponents(class IVssBackupComponents * *)" (?CreateVssBackupComponents@@YAJPAPAVIVssBackupComponents@@@Z) http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/2d096271-df86-4aa0-b14d-3a6415fd534a?prof=required&wa=wsignin1.0
  • Just wanted to add that AlphaVSS also sets the paths, not only the defines. This is needed in either case.

    Jared Oberhaus : Do you mean paths to the DLL's?

How do I control execution of Maven Jetty Plugin with -Dmaven.test.skip

I am using Jetty and Selenium to automate some unit tests from my Maven 2. We only really want to run these tests as part of the CI build and would like to control it via the -Dmaven.test.skip property.

I cannot find a way to apply this to the executions for the Jetty plugin. Am I missing something obvious?

From stackoverflow
  • see http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin

    bmatthews68 : This link just refers me to the documentation which does not actually cover the use case.
    Michael Lange : hmm there is the automatic execution example (as part of test process) and if there is no test process (with -skip...) well then there is no jetty startup for it
  • The maven.test.skip property is a property that the surefire plugin looks at to decide if it should just skip. The jetty plugin doesn't care at all about this property. The only way to do this would move your jetty plugin execution to a profile and try activating it if the maven.test.skip property is false.

    bmatthews68 : This doesn't work if the -Dmaven.test.skip is omitted. It means that the solution is to create a profile specifically for the CI server and specify that as part of the build instruction.

Vim in Emacs

The question does not refer to some Vim-mode in Emacs, but to Vim inside Emacs. I am not waging any Editor-war. I just want to use Vim in Emacs.

You can get to Vim in Emacs with commands "M-x term" and "vim".

When I am using the Vim-Emacs, the typing is awkward. There are odd signs, such as "4m", "4mm" and "^?^?". The backspace and the x-button in insert mode do not work. The odd signs emerge when I press the latter keys. So

How can I get Vim properly working in Emacs?

[Updated Information]

The malfunctioning Vim-Emacs is at least in the following OSs:

  • Mac OS 10.5.6
From stackoverflow
  • What you're seeing is that the terminal setting $TERM in your shell/Vim session doesn't match what the EMACS terminal is doing. Mine works fine, with the exception that the delete key is mapped to DEL, 0x127, while Vim wants ^H, 0x8. Mine shows the $TERM setting to be "eterm-color".

    Check what you have as $TERM

    $ echo $TERM

    and check the Vim docs for how to fix the backspace issue.

    Masi : I have xterm-color.
    Charlie Martin : Okay, it's probably being set by some x-specific stuff somewhere. I'm running Mac OS/X 10.5.6, Intel, and a fairly old Carbon EMACS, July of last year. Try setting your Vim terminal type explicitly and see if it's better.
  • For backspace,

    stty crt erase <CTRL-V><BACKSPACE>
    

    Worked for me.

    As for the rest, I don't know. Suppose it is something the shell outputs that the terminal doesn't handle. (Never used emacs 'term' before... prefer iTerm or Terminal.app for shell-related stuff. emacs 'term' has been called an "imperfect terminal emulator")

    Masi : Where did you put the command?
    : On the shell that popped up.

UIButton delayed state change

I have a UIButton subview inside of a UITableViewCell.

When this button is touched, the user must hold the button for about a half second for the button's image to change to the UIControlStateHighlighted image.

This means that if the user just taps the button as is usually the case, the highlighted state is never shown.

Why does this occur and how can I fix it?

From stackoverflow
  • Edit: completely re-written following a misunderstanding of the question

    One way of thinking of a UIButton is as a shorthand way of setting up an area of the screen that can respond to various instantaneous touch events the response it makes is defined by UIControl's Target-Action system for delivering messages to other objects.

    UIControlEventTouchDown sounds like the one you need to respond to. It will be triggered as soon as someone touches inside your button - this is what the "Contact Info" button in SMS does.

    UIButton* myButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect]; // SEt up title, frame etc [myButton addTarget:self action:@selector(myButtonWasPressed) forControlEvents: UIControlEventTouchDown]; [myMainView addSubView:myButton];

    Will send a -(void)myButtonWasPressed message to the object this code runs from (ideally you view controller). In myButtonWasPressed you can then add a new view or take any action you like. The SMS app pushes a view controller to display the contact info using a navigation controller.

    If this still doesn't solve your problem, you're going to have to post some code in order to get more insight into what's going wrong.

  • The problem is that your UIButton is inside a UITableView. This means that the table view has to determine whether your tap is going to be a swipe or if it's just a tap intended for the button. The table view has to delay sending a message to the UIButton until it knows that the user doesn't intend to swipe and therefore scroll the view instead of pressing the button.

    If you don't need a table view, get rid of the UITableView.

  • I just change the image from within the target action method:

    [sender setBackgroundImage:[UIImage imageNamed:@"highlighted-image.png"] forState:UIControlStateNormal];
    

    It changes the background image instantly.

UITableView - delete button

Hi, in my app when user swipes a certain row I want to display a delete button. And when the button appears it obscures IndexTitles and another label in my cell (it has subviews).

How can I customize my table when the button appears?

Thank you.

From stackoverflow
  • What do you mean by "obscures"? Does your content shrink to give space to the delete button or the button draws over your content?

    In the latter case, you should be considering adding your content as subviews of the cell's contentView.

  • Building off of E-ploko, may sure you're not positioning things absolutely. ie, if you want something to appear 10 pixels from the right boundary of the content view, calculate what the position should be, don't assume a constant width.

  • Does the cell textLabel allow autosizing and is lineBreakMode set to UILineBreakModeTailTruncation?

    [[cell textLabel] setLineBreakMode: UILineBreakModeTailTruncation];
    [[cell textLabel] setAutoresizingMask: UIViewAutoresizingFlexibleRightMargin];
    

    If the cell contents isn't flexible it will probably be obscured when the delete button appears.

ASP.NET SqlServer Session Replication

Curious whether folks have setup 2 way transactional replication on the tables ASP.NET uses for SqlServer stored session state (ASPStateTempSessions and ASPStateTempApplications) and the tables used for membership, role, and personalization? How did it work out? Were there any gotchas?

From stackoverflow
  • For Membership, you are probably fine with Replication, alhtough a cluster might be better for scale. For state, I would be more inclined to use a cluster.

    I would say the exception to this is when you have a geographically separated set of servers, but it is rare to have websites, except for some of the largest, geographically separated out.

    Have I ever done replication on state or membership tables? no.

iPhone raw touchscreen data

Hello,
I know in my iPhone app I can get touch events. But these touch events are filtered for me. If I press the device against my face, it filters out these touch events because it can detect its not a finger. How would I get the raw touch events, not filtered in any way? Thanks.

From stackoverflow
  • There is no public API for this. The closest you can get is GSEvent, from the GraphicsServices private framework.