Tuesday, March 15, 2011

Jersey in Tomcat+Spring environment can't find ComponentProvider. Why?

I've deployed Jersey on Tomcat and everything works perfectly (when I use the com.sun.jersey.spi.container.servlet.ServletContainer), but as soon as I change it to the com.sun.jersey.spi.spring.container.servlet.SpringServlet (according to all the tutorials I can find), I get a nasty exception:

Apr 19, 2009 5:07:35 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet ServletAdaptor as unavailable
Apr 19, 2009 5:07:35 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /myservice threw load() exception
java.lang.ClassNotFoundException: com.sun.jersey.spi.service.ComponentProvider

Any idea what package/distribution it can reside? What am I missing?

May be I don't need it at all. I'm trying to make sure that when my resource class is loaded it'll be Autowired and initialized with the rest of the Beans it depends on. Can it be done differently?

Thanks.

From stackoverflow
  • The com.sun.jersey.spi.service.ComponentProvider interface is part of the jersey-core JAR so it's odd that you're getting that exception.

    Make sure you're using the same version of the jersey libraries together (i.e. you're using Jersey 1.0.1 libraries, not mixing 1.0 and 1.0.1 as the Spring classes got renamed between those two releases).

    Also ensure you have a ContextLoaderListener in your web.xml like so:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    IgorM : I've removed all the conflicting version JARs and readded only from 1.0.3 - the exception disappeared. As well my JSON functionality was reduced to bare minimum, but, I guess, is a separate issue.
    safetydan : JSON support changed recently in Jersey. Make sure you're configured to use Jackson for JSON support and have the required libraries.

good all character combinations using a given length

Is there a program/tool/utility that would allow me to generate all possible character combinations (lowercase, uppercase, symbols, numbers) over a given length of characters (min-max)

From stackoverflow
  • Online:

    Desktop:

    • Free Password Generator. It's a password generator tool but you are able to

      • fix the length
      • choose to include letters/digits/catpital letters

        alt text

  • This is essentially the same field as brute-force password cracking, which might be what you are trying to achieve. Wikipedia has a reasonable article on password cracking, and lists the most popular software for the task.

  • Thanks Colin, that's what I was looking for.

MVC Preserve carriage return - line feed in html

Hi,

If have a field in my database with crlf's how do I preserve that in HTML??

Is there a standard way of doing this??

Malcolm

EDIT: I am actually doing an MVC app if that hepls.

From stackoverflow
  • I think the best way to do that is to replace the \r\n sequence with <br /> tags, using whatever scripting language your database-backed website is in.

    Other options include placing the text within a <textarea>. Or, if it is appropriate for your site, using akin to the <pre> tag (or the CSS attribute white-space: pre).

  • You can search/replace those characters with <br /> to make the text output with breaklines. You could also use the <pre> tag to specify a particular piece of text's line breaks.

Reordering items in BindingList in C#?

How would I move items in a BindingList in C#? Say, move last added item to the front, or swap with previous item?

From stackoverflow
  • A BindingList has an Items property that implements IList<>

    So you can Use Insert() and RemoveAt()

    flamey : yes, thank you :) just started learning c#, couldn't figure it out -- asked, and suddenly figured if out and came close the question :)
  • InsertItem method is something you should read about. I guess it gives you what you need.

  •     static void Main(string[] args)
        {
            BindingList<string> list = new BindingList<string>();
            list.Add("Hello");
            list.Add("World");
            list.Add("Test");
    
            MoveLastToFirst(list);
    
            Swap(list, 1, 2);
    
            foreach (string s in list)
                Console.WriteLine(s); // Prints Test World Hello
        }
    
        private static void MoveLastToFirst<T>(BindingList<T> list)
        {
            int cnt = list.Count;
            T temp = list[cnt - 1];
            list.RemoveAt(cnt - 1);
            list.Insert(0, temp);
        }
    
        private static void Swap<T>(BindingList<T> list, int first, int second)
        {
            T temp = list[first];
            list[first] = list[second];
            list[second] = temp;
        }
    

Group Union

I have the following query that always give me two rows. I want to group them to one row using tbluser.userid, is it possible to group a union?

SELECT
SUM(tblfooditem.calories)
FROM tblfooditem
INNER JOIN tbluser ON tblfooditem.userid = tbluser.userid
WHERE tblfooditem.userid=?userid AND tblfooditem.date=?date
GROUP BY tbluser.userid
UNION
SELECT
SUM(tbladdedmealitem.calories)
FROM tbladdedmeal
INNER JOIN tbluser ON tbladdedmeal.userid = tbluser.userid
WHERE tbladdedmeal.userid=?userid AND tbladdedmeal.date=?date
GROUP BY tbluser.userid;
From stackoverflow
  • It's possible.

    select sum(s) from (
    SELECT
        SUM(tblfooditem.calories) S,tbl.userid
        FROM tblfooditem
        INNER JOIN tbluser ON tblfooditem.userid = tbluser.userid
        WHERE tblfooditem.userid=?userid AND tblfooditem.date=?date
        GROUP BY tbluser.userid
        UNION
        SELECT
        SUM(tbladdedmealitem.calories) S,tbl.userid
        FROM tbladdedmeal
        INNER JOIN tbluser ON tbladdedmeal.userid = tbluser.userid
        WHERE tbladdedmeal.userid=?userid AND tbladdedmeal.date=?date
        GROUP BY tbluser.userid
    ) Q
    group by Q.userid
    

Is there any way to prevent console application to close ?

Hi

Is there any way to prevent console application to close ?

(that the user can't close the program)

thank's

From stackoverflow
  • Will it be a problem for you if the user switches off the computer?

    Joey : ... or just does a taskkill /f :)
    Cerebrus : No, I think the OP wants to keep the program running even after shutdown! :P
  • Take a look at the Win32 console API.

    You could try creating a windows (non console app) and then create your own console window with AllocConsole(). As I haven't tried this I can't say if Windows will still try to kill your process.

    An alternative would be to create a background process/service to do the work.

  • Normally a console application can be aborted by pressing CTRL-C.

    You can prevent CTRL-C from aborting your application by setting the Console.TreatControlCAsInput property or handling the Console.CancelKeyPress event.

    Of course this won't stop the user from being able to kill your process, e.g. using Task Manager.

    Richard : ... or using control-Break to stop it.

Submit button doesn't work for ajax form rendered in dynamic partial view

I have some jQuery that loads a partial view and inserts it into the DOM. So far, all good.

But now I've made some changes to the rendered user control to include an Ajax form. However, the submit button for this form doesn't appear to trigger the Ajax call. From what I can tell, it's not doing anything at all. My breakpoints in the controller aren't getting triggered either.

If I use a link and add onclick="submit()", the form gets submitted, and triggers the action in my controller fine, but of course, this is doing a plain post and not an ajax post.

The form is like:

<% using(Ajax.BeginForm("actionName", new AjaxOptions {
           OnSuccess = "updatePanel" })) { %>
  <!-- form elements in here -->
  <input type="submit" />
<% } %>

I've just discovered that it does the post if I change OnSuccess to OnComplete, which I don't understand at all.

However, even though changing it to OnComplete is working, I get an exception in the microsoft ajax library, somewhere in:

try {
  a._webRequest.completed(Sys.EventArgs.Empty)
} finally {
  if (a._xmlHttpRequest!=null) {
    a._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
    a._xmlHttpRequest = null
  }
}

The cursor is higlighted at the end of finally, says Object doesn't this property or method.

I suppose I could live with that; it's just annoying testing stuff when it keeps throwing an exception in MicrosoftAjax.js and tripping the debugger in VS.

From stackoverflow
  • If you are using OnSuccess do you not need to have UpdateTarget also which is why it wasnt firing in the first place?

  • Have you made sure you're referencing the Microsoft AJAX JS files?

    You need to make sure you have...

    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    

    Somewhere in your site. By default I don't think the ASP.NET MVC Project adds these JS references.

when is using Cache is to much ?

hi,

  • i am really struggling finding the best solution, what is really confusing me is as long as .net framework purges low priority cached items why should i worry about memory ( i know it is a dump question) ?

  • can i really constrain an ASP.net Caching to use certain amount of RAM, not from IIS cause my site is on shared hosting, also what that affect on caching ?

  • would static classes make better use for some situations ?

thanks in advanced.

From stackoverflow
  • Sadly, the memoryLimit attribute on the processModel configuration element is only allowed to be set at the machine level (in machine.config) - and the way config files work, there's no way to say "this is the maximum memory any one app can have, but they can ask for less if they want".

    IF you're finding that things are constantly spooling out of your cache, should they really be in there? You're either not reading them often enough to bother caching them in the first place, or your trying to put too much stuff into cache at once.


    Cache spooling can be seen with the built in Performance Monitors. Under ASP.NET Applications and ASP.NET Apps v2.0.50727 you can find things like:

    • Cache API Trims
    • Cache API Turnover Rate
    • Cache Total Trims
    • Cache Total Turnover Rate

    More details can be found on TechNet.

    : man, what is a tool to test spooling of cache as you said ?

Outputting to the Console in C# on IIS

We are trying to debug some web services code we're running in C# on IIS. I am new to Windows programming and have no idea how to view output to the console. We've got some write statements in the code, but I can't figure out how to view the console while this thing is running. Help?

From stackoverflow
  • If you're using asp.net then trace.axd should contain trace statements (as long as its turned on).

  • You aren't going to get a console for IIS. CLOSEST you will come is Debug.WriteLine w/ a debugger attached or using page tracing. Recommendation would be to use a logging framework that will write to debugger (when attached) as well as a file and possibly the event log (all configured via your listeners).

    Some great ones are log4net and NLog.

    Arnshea : Since .net comes with built in logging I always wonder why people still use other logging packages...
    Darren Kopp : because tracing doesn't work when in a production environment. and w/ shared components, you don't want to be tied to web based logging if the same code will be used on the web as well as a windows app or service.
    Arnshea : The Trace in System.Diagnostics doesn't work in production? I'm pretty sure they do, as long as it's enabled. Built in trace switches, trace sources, filters and listeners...
    Darren Kopp : if you have set in the config (which you should for production), then it disables it.
  • You'll want to take a look at ASP.NET tracing

    here is a handy link to get you started: http://www.asp101.com/articles/robert/tracing/default.asp

    you can enable application wide tracing if you place the following in your web.config, then you will have access to your trace.axd

    <trace enabled="true" 
        localOnly="false" 
        pageOutput="false" 
        requestLimit="500" 
        traceMode="SortByTime"
    />
    
    MaxGeek : I found it useful.
    RSolberg : Wow - get the answer even after stealing the answer from someone else!
  • I have found the Trace feature extremely helpful. You can get there by going to: http://mysiteurl/trace.axd

    In your web.config, place the following within the System.Web tag:

    <trace enabled="true" 
           localOnly="false" 
           pageOutput="false" 
           requestLimit="500" 
           traceMode="SortByTime"
    />
    

    Now from your code behind, you can inject some logging by doing:

    HttpContext.Current.Trace.Warn("I Made It Here!");
    

Why csv.reader is not pythonic?

I started to use the csv.reader in Python 2.6 but you can't use len on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.

Or is this just an abandoned module in later versions?

From stackoverflow
  • I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.

    import csv
    r = csv.reader(...)
    lines = [line for line in r]
    print len(lines) #number of lines
    for odd in r[1::2]: print odd # print ever other line
    
    Joan Venge : Thanks, I didn't know it was an iterator. I thought it was a multi dimensional list.
    saffsd : You can replace lines = [line for line in r] with lines = list(r)

IHierarchicalEnumerable to SiteMapPath ?

Hi, exists any simple method to use my IHierarchicalEnumerable class in SiteMapPath control?

Thanks

From stackoverflow
  • I am not sure how simple would it be but you need to implement a sitemap provider.

create toolbar in .chm file

Hi all,

I have created a .chm file from multiple html files. Now I want to show my own toolbar on the top of .chm file. I have installed "htmlhelp.exe" to create .chm from html files.

Can we create our own toolbar ?

From stackoverflow
  • Nope, it's not supported. CHMs are not an especially powerful tool, unfortunately. Help 2.x is no help either, as Microsoft's decided not to let anyone except themselves have the viewer tool. (There are third party ones but they're not great.) Not that it would add the functionality you're looking for...just venting a bit I suppose.

How to get rid of maven snapshot versions

I have been using maven for a while now. But I've never learnt how to get rid of the snapshot version.

Please share some articles on how to do a release of the artifacts. i.e. how do I publish my 0.0.1-SNAPSHOT versions to (say) 1.0.0

From stackoverflow
  • Use the mvn:release plugin.

    mvn release:prepare
    mvn release:perform
    

    That's about all you need to do, in the general case. See here for the more complete documentation.

Ruby on Rails cannot connect to database from runner script

In my application I have a runner script running on schedule (crontab) that needs to connect to database and get some information. I get the following error when I try to run a query ( using Model.find(...) ) :

.../vendor/rails/railties/lib/commands/runner.rb:45: .../vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:471:in `real_connect': Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) (Mysql::Error)
From stackoverflow
  • Generally this sort of thing happens because of either paths (so you aren't seeing the right database.yml or something) or permissions (you aren't doing it as the right user).

    A pattern that generally works for me is to put a crontab entry like this:

    cd path/to/rails/app-root; script/runner MyController.thing_to_do
    

    in the crontab of the (pseudo)-user that the app runs as.

    Goro : Turns out my runner scripts were not running production environment by default. Forcing them to use the production database takes care of the problem.

How do I dynamically create multiple controls in Silverlight?

I know how to create a list of Controls and add new instances of them to it:

private List<FirstCircleControl> Circles = new List<FirstCircleControl>();
FirstCircleControl mc = new FirstCircleControl();
Circles.Add(mc);

I want to add a whole bunch of "FirstCircleControls". How would I add 10 controls to my list? I want to be able to "create" and then "add" them to the list using a loop.

From stackoverflow
  • I wonder why you might need to create them all at once and then add them to the list, but here's a solution:

    Enumerable.Range(0, 10)
              .Select(x => new FirstCircleControl())
              .ToList()                        // Forces creation of controls.
              .ForEach(x => Circles.Add(x));   // Adds them to the list.
    
    Ry : Thanks Mehrdad. Enumerable looks super handy.

Visual Studio Project GUIDS

Following on from this question...

"how do you tell the visual studio project type from an existing visual studio project"

How do i add project guids into my csproj file to enable me to add other types of form/controls.

For instance I create a class project solution and want to be able to add web forms and web user controls to the project.

I attended a talk where the presenter showed this was possible but he didn't supply any further information.

From stackoverflow
  • Close the project, open the project file in a text or XML editor, and add the guids manually.

    (Keep an original copy, it make take a few attempts to get right.)

    Rob : I'm trying that by adding this line... {ABF1B333-B149-4DBF-B1D7-B66438F14AD9};{349C5851-65DF-11DA-9384-00065B846F21};{E24C65DC-7377-472B-9ABA-BC803B73C61A} which should give me the class, web app and web site. However i still don't have any additional forms.
  • It's quite easy. Just edit the web project. Add the necessary guids as shown in my post, How to Hack a Class Library Project into a Web Application Project.

    Rob : Excellent stuff, I see my mistake now, thanks.

How can I grep for files that have both expressions?

Hello All,

I would like to display files that contain more than one expression and exclude files that do not have all expressions.

Any ideas?

Thanks!

From stackoverflow
  • egrep -r 'expression1|expression2|expression3' .

  • if you don't have the -r you can just use grep over again on the results grep expression1 * | grep expression 2 | grep expression 3

  • Usually I do that sort of thing by running grep multiple times, something like

    grep -l 'expression1' * | xargs grep -l 'expression2' | xargs grep -l 'expression3'
    

    and so on. It doesn't seem very efficient, and I wouldn't be surprised if there is a better way, but I don't know it.

    Vatine : With some domain knowledge (in this case "what regexp is least likely to match") and starting with that regexp, this is probably close to the most efficient solution.

Difference in regex behavior between Perl and Python?

I have a couple email addresses, 'support@company.com' and '1234567@tickets.company.com'.

In perl, I could take the To: line of a raw email and find either of the above addresses with

/\w+@(tickets\.)?company\.com/i

In python, I simply wrote the above regex as '\w+@(tickets\.)?company\.com' expecting the same result. However, support@company.com isn't found at all and a findall on the second returns a list containing only 'tickets.'. So clearly the '(tickets\.)?' is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?

From stackoverflow
  • Two problems jump out at me:

    1. You need to use a raw string to avoid having to escape "\"
    2. You need to escape "."

    So try:

    r'\w+@(tickets\.)?company\.com'
    

    EDIT

    Sample output:

    >>> import re
    >>> exp = re.compile(r'\w+@(tickets\.)?company\.com')
    >>> bool(exp.match("s@company.com"))
    True
    >>> bool(exp.match("1234567@tickets.company.com"))
    True
    
    jcoon : I second this suggestion.
    BipedalShark : #2 is just me being a newb at stackoverflow. Fixed the initial post. ;)
  • I think the problem is in your expectations of extracted values. Try using this in your current Python code:

    '(\w+@(?:tickets\.)?company\.com)'
    
  • The documentation for re.findall:

    findall(pattern, string, flags=0)
        Return a list of all non-overlapping matches in the string.
    
        If one or more groups are present in the pattern, return a
        list of groups; this will be a list of tuples if the pattern
        has more than one group.
    
        Empty matches are included in the result.
    

    Since (tickets\.) is a group, findall returns that instead of the whole match. If you want the whole match, put a group around the whole pattern and/or use non-grouping matches, i.e.

    r'(\w+@(tickets\.)?company\.com)'
    r'\w+@(?:tickets\.)?company\.com'
    

    Note that you'll have to pick out the first element of each tuple returned by findall in the first case.

    Axeman : Okay, but interestingly, not *obvious*.
  • There isn't a difference in the regexes, but there is a difference in what you are looking for. Your regex is capturing only "tickets." if it exists in both regexes. You probably want something like this

    #!/usr/bin/python
    
    import re
    
    regex = re.compile("(\w+@(?:tickets\.)?company\.com)");
    
    a = [
        "foo@company.com", 
        "foo@tickets.company.com", 
        "foo@ticketsacompany.com",
        "foo@compant.org"
    ];
    
    for string in a:
        print regex.findall(string)
    

How to escape @ characters in Subversion managed file names?

For many Subversion operations, appending the '@' symbol to the end of a file or URL argument allows you to target a specific revision of that file. For example, "svn info test.txt@1234" will give information about test.txt as it existed in revision 1234.

However, when the name of the file contains an @, it is incorrectly interpreted by Subversion as a revision specifier:

svn info 'test@.txt' svn: Syntax error parsing revision '.txt'

I've tried double and single quotes as well as escaping with '/', '\', and '@'. How can I tell Subversion to treat the @ symbols as part of the file name?

From stackoverflow
  • Double the @.

    So try svn info 'test@@.txt'

    weston : Unfortunately this yields the same results: "svn: Syntax error parsing revision '.txt'". Thanks for the suggestion though!
  • From the SVN book (emphasis added):

    The perceptive reader is probably wondering at this point whether the peg revision syntax causes problems for working copy paths or URLs that actually have at signs in them. After all, how does svn know whether news@11 is the name of a directory in my tree or just a syntax for “revision 11 of news”? Thankfully, while svn will always assume the latter, there is a trivial workaround. You need only append an at sign to the end of the path, such as news@11@. svn cares only about the last at sign in the argument, and it is not considered illegal to omit a literal peg revision specifier after that at sign. This workaround even applies to paths that end in an at sign—you would use filename@@ to talk about a file named filename@.

    weston : That did the trick, thanks!

How can you make your custom property of a webpart in SharePoint 2007, sort to the top of the property pane?

In SharePoint 2007, is it possible to programmatically sort the custom property you created to the top of the property pane? So when someone edits your webpart it would show at the top, rather than at the bottom by default, so that the user wouldn't have to scroll to the bottom?

Here's my code, for reference:

    private string _strMainFolder = "Reports";

    [WebBrowsable(true)]
    [WebDisplayName("Reports SharePoint List Name")]
    [SPWebCategoryName("Report WebPart Configuration")]
    [WebPartStorage(Storage.Shared)]
    [WebDescription("Enter the SharePoint List's name that you want to use.")]
    [Personalizable(PersonalizationScope.Shared)]
    public string strMainFolder
    {
        get { return _strMainFolder; }
        set { _strMainFolder = value; }
    }
From stackoverflow

WebRequest and System.Net.WebException on 404, slow?

I am using a WebRequest to check if a web page or media (image) exist. On GetResponse i get a System.Net.WebException exception. I ran through 100 links and it feels like its going slower then it should. Is there a way to not get this exception or handle this more gracefully?

    static public bool CheckExist(string url)
    {
        HttpWebRequest wreq = null;
        HttpWebResponse wresp = null;
        bool ret = false;
        try
        {
            wreq = (HttpWebRequest)WebRequest.Create(url);
            wreq.KeepAlive = true;
            wresp = (HttpWebResponse)wreq.GetResponse();
            ret = true;
        }
        catch (System.Net.WebException)
        {
        }
        finally
        {
            if (wresp != null)
                wresp.Close();
        }
        return ret;
    }
From stackoverflow
  • Try setting

    wreq.Method = "Head";
    

    after the "KeepAlive" line. If the webserver you are calling is smart enough, that will tell it not to return any body contents which should save some time.

SheetBeforeDoubleClick not working from COM Addin

I'm trying to write a COM add in for Excel in C# that disables the ability to double click a cell and then edit it, I want to popup a box saying that editing a cell this way is prohibited and then stop all execution.

Looking through the documentation at Microsoft this seems like a very easy task, you create an Application event AppEvents_SheetBeforeDoubleClickEventHandler with the signature func(object sheet, Range Target, ref bool Cancel) and you set Cancel to true so that execution stops. However, this isn't happening.

I have the following:

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
    Excel.Application app = application as Excel.Application;
    app.SheetBeforeDoubleClick += Excel.AppEvents_SheetBeforeDoubleClickEventHandler(beforeDoubleClick);
}

void beforeDoubleClick(object sheet, Excel.Range Target, ref bool Cancel)
{
    MessageBox.Show("Cannot edit cells this way sorry.");
    Cancel = true;
}

The message box is shown, but the cell is then put into edit mode, however, if I have the same thing from VBA it works.

The exact same thing happens with a VB.NET addin using the following code.

Private WithEvents app As Excel.Application
Public Sub OnConnection(ByVal application As Object, 
                            ByVal connectMode As Extensibility.ext_ConnectMode, 
                            ByVal addInInst As Object, 
                            ByRef custom As System.Array) 
                            Implements Extensibility.IDTExtensibility2.OnConnection
    app = application
End Sub

Sub Worksheet1_BeforeDoubleClick(ByVal obj As Object, 
                                 ByVal Target As Excel.Range, 
                                 ByRef Cancel As Boolean) 
                                 Handles app.SheetBeforeDoubleClick
    MsgBox("Double-clicking in this sheet is not allowed.")
    Cancel = True
End Sub

I'm using Excel XP :(

From stackoverflow
  • Hey PintSizedCat,

    I know this question is a month old, and you've almost certainly moved on from this (I hope!), but I decided to take a look at it.

    I had no problems executing your code: the 'Cancel' behavior worked properly and correctly prevented the double-click operation.

    Some searching turned up the following from MSKB: BUG: Cancel parameter for Office events is ignored in Visual Studio .NET 2003.

    This behavior of ignoring the cancel parameter seems to exist for Excel versions 2002 and below when using .NET code created using Visual Studio .NET 2003 (.NET Framework 1.1).

    There is a complex work-around given in the article that involves hand-tuning the Interop Assembly. It looks pretty doable, though, if a fair amount of effort.

    It would be easier to upgrade to VS 2005 or VS 2008, if that is at all possible for you. I compiled my code using VS 2008 targeting .NET 3.5, and ran my code on Excel 2007 with no troubles.

    By the way, even if you get this running, the user will still be able to enter a value into the cell by typing the value within the Formula Bar, executing a Copy-Paste command, or the like. So I am not sure that this is a great way to try to prevent the user from entering a value into a cell. Perhaps you might want to look into protecting the worksheet instead?

    Anyway, I know that this is very late, but I hope that it is of some value or help.

    Mike

    PintSizedCat : Hey, just wanted to say thank you for putting in the time. I've been working on a project recently that I need this kind of functionality for and actually I compile with VS 2008 using .NEt 3.5 but for Excel 2002. I'll try the workaround. Thanks again.
    Mike Rosenblum : According to that article, you should be ok with VS 2008. Hmmm... Ok, you might want to check out http://support.microsoft.com/kb/948461. It states that an error should be thrown, but, if not, then .NET 1.1 might just quietly run, and therefore kick in the 'ignore the cancel event' behavior'?

How can I make my Windows Form to do and display my database query?

I have 3 Tables:

  • Titles:

    • TitleId (int 6, primary key)
    • TitleName (varchar 50)
  • Authors:

    • AuthorId (int 6, primary key)
    • AuthorName (varchar 50)
  • AuthorsTitles (this is a junction table for Titles and Authors)

    • TitleId (int 6)
    • AuthorId (int 6)

There's a "many to many" relation: A Title may have many Authors, and an Author may have many Titles. This is why I need the junction table.

All I want is to get a Windows form with a ComboBox with Titles. The user selects a Title, and the Author or Authors of the selected Title will be listed in a ListBox.

I'm using Microsoft Visual C# Express Edition 2008 and SQL Server Express Edition 2008.

Thanks

From stackoverflow
  • I don't have sample code but hope this link helps you.

    Data Binding in .NET / C# Windows Forms

  • To set up a database connection in Visual Studio, see this.

    For examples on how to bind a combobox to a field in a table, view this.

  • Michael and Gulzar:

    Thanks very much for your help, but what I need is something little different.

    In your answer there is an "one to many relation" (one customer with many orders) followed by another "one to many relation" (one order with many order-details).

    In my problem there is an "one to many relation" (one title has many authors) followed by a "many to many relation" each one of these authors has a name.

    I want to select a TitleName (and its TitleId) in a Combobox, and with this TitleId try to find all the AuthorName's in the Authors Table through the junction Table AuthorTitle.

    In other words: I select a book with many authors in my ComboBox and I want to see their names in the ListBox.

    It looks very simple! But I can't get a code that solves this problem.

Add own javascript to validation

Hi, I don't know very much about c#. I am updating a page built by someone else and I want to add a script to a button web control. The form is using c#'s validation and when I look at the returned markup from opening the page, there already is an onclick event handler for the postback submission and validation. So how do I add my own as well? Thanks for your help

From stackoverflow
  • You can use the button's OnClientClick property to place custom clientside script. Documentation on it here.

  • Here is the official ASP.NET QuickStart Tutorial for ASP.NET Validation Controls. By the way if you're looking for your custom validation, check CustomValidator Control, specifically it's ClientValidationFunction property.

How to form this Regex

Suppose the string is:

string item = "t-ewrwerwerwerwer\r-rr\wrjkwlr";

I want to Replace all - except when it is preceded by r.

So resut will be

string cleanItem = "tewrwerwerwerwer\r-rr\wrjkwlr"'

What regular expression can be used?

From stackoverflow
  • A replacement on (?<!r)- by an empty string should do the trick I think.

  • (?<!r)-
    

    As long as your regex flavor supports zero-width look-behind, that is.

  • I think this regular expression is a little more efficient:

    -(?<!r-)
    

    Or if your language doesn’t support negative look-behind assertions, use this expression:

    (^|[^r])-
    

    and replace it by \1 (first matching group).

How do I reference the PDF IFilter (dll) interface built into Windows to extract text and properties (author, title, etc.) of a pdf document via Classic ASP

I need to extract and parse Text from a pdf file in a classic ASP environment. I read another post about using the PDF iFilter driver installed with Adobe Acrobat 9 which can be referenced through COM.

Is this even possible? If so how do I get started?

Thanks

From stackoverflow
  • If you know the COM class name or clsid, you should be able to use Server.CreateObject() to get an instance. You should then be able to call IFilter methods on it.

What is the difference between My.Computer.FileSystem.MoveFile and File.Move

The question says it all really.

What are the differences between these two methods that appear to carry out exactly the same function?

Is there guidance to say which should be used or are there conditions when you may use either?

From stackoverflow
  • I believe they have near-identical functionality. Most people I've seen would prefer to use the latter, because "MyComputer." is a VB.NET-only construct, whereas File.Move is used in both C# and VB.NET. This makes it easier to get help, and easier for C# coders to read the VB.NET code and vice-versa.

    Camilo Martin : but C# can also use the "My" namespace, correct?
    GWLlosa : I haven't seen the My namespace accessible from C# at all. There may be some way to get a reference to it, but its certainly atypical.
  • I haven't checked My.Computer.FileSystem.MoveFile, but you can state if they are differences moving html files with associated images directories., because File.Move just move the file, but doesn't move the associated directory

  • The FileSystem.MoveFile has some more options than File.Move, like for example optionally showing a progress dialog, and creating the destination folder if it doesn't exist.

    If you just want to move or rename a file, the File.Move method will be called in the end whichever you use, so calling it directly means slightly less overhead.

Best Practices in creating software appliances?

I have an application that a customer has asked us to package into a software appliance and wanted to find a list of all of the things that I need to consider. Stuff related to choosing the operating system is well-documented, but other aspects such as building usable web consoles, frameworks I should consider (the application is written in Java) and things that I may need to refactor in terms of design are not.

Any guidance is greatly appreciated.

From stackoverflow
  • There are several things you need to consider when creating an appliance. The one thing you don't want to be in the business of is maintaining the OS. So pick an OS that is considered stable and secure. When installing the OS, only include those packages absolutely required for your application. Always pick stable versions of any application frameworks. Ideally you'll use something that is relatively mainstream. Once again, you should be supporting your application, not the framework.

    A non-exhaustive list would include things like:

    • Picking a stable, supported, secure OS.
    • Choosing commodity, off the shelf hardware. Parts should be easy to find and replace.
    • Don't install unused packages.
    • Figure out how you'll patch / update your software once deployed.
    • Provide a Web-base configuration option so you don't have to log into the shell to change settings.
    • Make log files available via a web front end for the same reason as above.
    • bootstrap your application during start up.
    • Determine how you'll secure your web front end and the appliance in general.
    • Provide a way to migrate your application to another appliance in case of general hardware failure.
    • Does your app merit clustering and failover?
    • Make backing up your application easy and pain free. Ideally your users won't have to shutdown the app to backup their data.

How to debug JVM resources loading?

Hi everybody, this is my first question here in stackoverflow (and I hope not the last one :P).

To debug class loading in a JVM we can use the param -verbose:class, but... Anyone knows how to debug resources loading (e.g. properties files)?

Thank you in advance!

From stackoverflow
  • I suppose you need to look at using a profiler. Or something that uses the instrumentation interface.

    Not sure how stable it is, but there is BTrace, which is kind of a Java version of DTrace.

    BTrace is a safe, dynamic tracing tool for the Java platform. BTrace can be used to dynamically trace a running Java program. BTrace dynamically instruments the classes of the target application to inject tracing code ("bytecode tracing"). Tracing code is expressed in Java programming language.

    If you are doing this on a development machine, and the number of events (resources being loaded) is not too frequent, you could also just set a breakpoint in the debugger.

  • Resources are provided as URLs. So, I guess to do it in "pure" Java: Install a custom ClassLoader that copies URLs into a version with a custom URLStreamHandler. Put your monitoring code in the stream handler and forward to the original.

  • In a Linux environment you can try:

    lsof -p <jvm pid>
    

    It will give you a list with the descriptors used by the program associated with the specified pid.

    More Info

    erickson : The problem is that many resources can be loaded from a single jar file, which might only be opened one time.
    Daniel H. : I agree, in that case I think the best option is to go with the ClassLoader solution

Is that possible to cache UIWebView in iPhone?

I was using NYTimes iPhone application, I become bit curious when I notice that it cache UIwebview even though I didn't open that article.Does anyone have idea how to do that?

How NYTimes iPhone application doing offline reading?

Any help greatly appreciated.

Thanks,

Amit

From stackoverflow
  • You can use UIWebView to load html files stored locally on the iPhone.

    NYTimes app is probably caching html and images in local storage.

    Search google for "UIWebView local" and you get several useful hits.

    I tried it out and it works great:


    First, create a "view based application" and add a UIWebView to the NIB.

    Second, add this code to your UIViewController code:

    - (void)viewDidLoad 
    {
    
        NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
        [webView loadRequest:request];
    
    
        [super viewDidLoad];
    }
    

    Third, add a file called "index.html" to your "Resources" folder in xcode and it will be displayed.

    bentford : The code works, but I'm not sure I described the app creation clearly. Let me know if it helps!

Setting my own probes with Dtrace in C++

I have some custom dtrace probes in a C-library, and when linking and using the library with a C application my probes work fine, however when linked against C++ it says it can't find them. The reason seems to be because of C++ mangling, and trying to get it to work has become a duck chase.

Any ideas?

Note: Using gcc

From stackoverflow