Saturday, February 19, 2011

Code is HttpClient or servlet API to parse Cookie header

Is there any existing code in Apache HttpClient or in the servlet API to parse Cookie header and obtain from a string that contains "name1=value1; name2=value2; ..." a list of Cookie? Writing code to parse this doesn't seem too hard, but if there is already some existing code, I'd like to use it.

From stackoverflow
  • If you call getCookies() on the HttpServletRequest object, it will return an array of Cookie objects. If you need to frequently look up cookies by name, then it may be easier to put them in to a Map so it's easy to look them up (rather than iterate over the Array each time). Something like this:

    public static Map<String,Cookie> getCookieMap(HttpServletRequest request) {
     Cookie[] cookies = request.getCookies();
     HashMap<String,Cookie> cookieMap = new HashMap<String,Cookie>();
     if (cookies != null) {
      for (Cookie cookie : cookies) {
       cookieMap.put(cookie.getName(), cookie);
      }
     }
     return cookieMap;
    }
    

    If you're using HttpClient and not servlets, you can get the Cookie array using:

    client.getState().getCookies()
    

    where client is your HttpClient object.

Double value returns 0.

Here's an example:

Double d = (1/3);
System.out.println(d);

This returns 0, not 0.33333... as it should.

Does anyone know?

From stackoverflow
  • That's because 1 and 3 are treated as integers when you don't specify otherwise, so 1/3 evaluates to the integer 0 which is then cast to the double 0. To fix it, try (1.0/3), or maybe 1D/3 to explicitly state that you're dealing with double values.

  • Wow, thank you!

    But how about if i have:

    double d = (height/imageHeight)*imageWidth;

    What would I use on that? Double.valueOf() or something else?

    tvanfosson : Then just use a simple cast of one of the variables in the division: double d = ((double)height/imageHeight)*imageWidth;
    chriscena : Please add additional comments and questions as comments to the related answer and not as a separate answer to you question.
    recursive : Try double d = height*imageWidth/imageHeight;
  • If you have ints that you want to divide using floating-point division, you'll have to cast the int to a double:

    double d = (double)intValue1 / (double)intValue2
    

    (Actually, only casting intValue2 should be enough to have the intValue1 be casted to double automatically, I believe.)

  • And thank you too! Problem solved :)

  • Use double and not Double unless you need to use these values in the object sense. Be aware about the Autoboxing concepts

Hook to WM6 sound

How can i hook to the window mobile sound (driver?) and read the data while it is passing it to the speaker.

From stackoverflow

boost spirit extracting first word and store it in a vector

Hi,

I have problems with Boost.Spirit parsing a string.

The string looks like

name1 has this and that.\n 
name 2 has this and that.\n 
na me has this and that.\n

and I have to extract the names. The text "has this and that" is always the same but the name can consist of spaces therefore I can't use graph_p.

1) How do I parse such a string?

Since the string has several lines of that format I have to store the names in a vector.

I used something like

std::string name;
rule<> r = *graph_p[append(name)];

for saving one name but

2) what's the best way to save several names in a vector?

Thanks in advance

Konrad

From stackoverflow
  • I presume there is a reason why you are using Boost.Spirit and not STL's string's find method? E.g:

    string s = "na me has this and that.\n";
    myVector . push_back( s.substr( 0, s.find( "has this and that" ) ) );
    
  • I think this will do the trick:

    vector<string> names;
    string name;
    parse(str,
        *(  
           (*(anychar_p - "has this and that.")) [assign_a(name)]
           >> "has this and that.\n") [push_back_a(names, name)]
         ))
    
    BenoƮt : +1. Clean and simple !
  • vector<string> names;
    parse(str,
        *(  
           (*(anychar_p - "has this and that.")) [push_back_a(names)]
           >> "has this and that.\n")
         ))
    

    Hi,

    thanks for your response. I have some problems with this version because there are following lines which have a completely different format and they are also parsed as true because there obviously is no "has this and that.". So I changed it to

    vector<string> names;
    parse(str,
        *(  
           (*(anychar_p - "has this and that.") >> "has this and that.\n"))[push_back_a(names)]      
         ))
    

    Now it parses the lines right but I got a new problem with the push_back actor because now it is pushing the complete line " has this and that" into the vector. Is it possible to remove the "has this and that. " before pushing it back or do I have to manually edit the vector afterwards?

Opening separate windows with Start

Hello,

I am tring to open several instance of IE with the start command in a batch file. For example I want to open www.google.com and www.yahoo.com at the same time in separate windows.

Any help would be appreciated.

Regards, Aaron

From stackoverflow
  • $>start iexplore http://google.com
    $>start iexplore http://yahoo.com
    

How do you change a connection string dynamically in an object datasource in asp.net?

how to change connection string dynamically in object datasource in asp.net ?

From stackoverflow
  • protected void ObjectDataSource1_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
    {
        if (e.ObjectInstance != null)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = MyConnectionManager.ConnectionString;
            e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);
        }
    }
    

    I hope it helps.

  • I didn't get the above to work but this did:

      if (e.ObjectInstance != null)
      {
        ((ReportPrototype.ReleasedRatingsDataTableAdapters.RatingsViewTableAdapter)e.ObjectInstance).Connection.ConnectionString = ConfigurationManager.ConnectionStrings["RADSDataConnectionString"].ConnectionString;
      }
    

    ObjectInstance is the table adapter which in my case was the type bound to the ObjectDataSource.

can I set the constraints for a variable once and generate a few times in specman?

I have a variable that I want to generate a few times in the same function, each time with the same set of constraints. Can I set the constraints once and the just gen it many times? That is, instead of this:

var a:uint;
gen a keeping {it in [100..120];};
// some code that uses a
.
.
.
gen a keeping {it in [100..120];};
// some code that uses a
.
.
.
gen a keeping {it in [100..120];};
// some code that uses a
// etc...

I'd like to do this:

var a:uint;
keep a in [100..120];
.
.
.
gen a;
// some code that uses a
.
.
.
gen a;
// some code that uses a
.
.
.
gen a;
// some code that uses a
// etc...

That way if I want to change as constraints I only have to do it once.

From stackoverflow
  • You can do this by making the variable an instance member of the enclosing object.

    a : uint;
    keep a in [100..120];
    my_method()@qualified_clk_rise_e is {
    
        gen a;
        ...
        gen a;
        ...
        gen a; 
    };
    

    This implementation isn't thread-safe if multiple my_method()'s are running on the same object at the same time.You can make it [specman] thread-safe by assigning the generated 'a' to a 'my_a' within the scope of the method:

    var my_a : uint;
    gen a;
    my_a = a;
    

    Or you can just write a method to generate 'a':

    gen_a(): uint is {
        gen result keeping { it in [100..120] };
    };
    
    my_method()@qualified_clock_rise_e is {
        var a : uint;
        ...
        a = gen_a();
        ...
        a = gen_a();
        ...
        a = gen_a();
        ...
    };
    

Fastest way to share data objects between a Java server and a C# client

What is the fastest way to share data structures between Java and C#? I want something where I can literally send a "car" object or a "foo" object and have it serialized and deserialized on both server and client.

From stackoverflow
  • Not necessarily applicable, but there's an interesting blog spot that I've seen about this topic: link text

  • You might be able to use IKVM, it's a Java-like environment on top of .NET; you could use Java serialization on IKVM and use interop to use the objects from "regular" .NET languages.

  • It looks like the IKVM seems like a good idea. But if that doesn't meet your needs especially since it is still in development. However, Uri's post points you in a good direction with the use of xml and passing messages, which can be built back together on either side.

  • Would you be able to use a SOAP web service on the server and have the client consume the web service? The object's data structure would be described in the WSDL for the web service.

  • WSDL (SOAP) is fairly interchangeable. If you want something less chatty, anything like Google's "protocol buffers", "ICE" (ZeroC), etc offer interchangeable binary serialization and code generation.

    For .NET / C#, there are currently two viable protocol buffers implementations here; protosharp is essentially inactive and incomplete) - either would be fine, but neither currently has a complete RPC stack, so you'd have to handle message passing yourself.

WPF TreeView with horizontal orientation?

What would be the bast way to change the orientation of the WPF treeview. I would like to work the expand-collapse-functionality to work left to right instead of top to down. I.e. when I click on on the expand button of a treenode I would its subnode to appear right of the parent and the indent should work top-down instead. Also the vertical lines that connect the node must now be horizontal.

From stackoverflow

How can I make a Table of Contents frame in XSL?

I have an XML file that I am creating an XSL stylesheet for.

What I would like is to have two frames and do two passes on the data, the first would create a Table of Contents in the left frame, and the second would have the body of data in the right.

I can do the two passes, the problem is putting them in separate frames. The frame HTML element takes in a source; I can't put my source directly in there.

I can think of a few ways to get around this, none of which I'm thrilled with, so I wanted to see if anyone had found a way to do this.

From stackoverflow
  • If you want to use frames you need three separate files.

    1. The frame file. This is just a strict HTML file
    2. A file for your table of contents
    3. A file for your content

    The first one is as specified just an HTML file. The second two are XSL files that will eventually turn into HTML. A good tutorial on frames is here at W3Schools.

    EDIT: The more I think about this, the more I dislike the solution. It requires the XSL parser to be run twice for each time the initial page is served

    Have you thought about using CSS or tables to do your layout? There are some really good open source CSS templates flying about here on the interwebs.

  • This was relatively stable data that would be generated by a script, so what I ended up doing was creating separate stylesheets for the TOC and the main window, then using those to generate html files for each of them after I generate the html.

    Then my main page was just a static html page that referenced these generated html files.

    There's probably a better way to do it, but this is an internal reference, so this is enough to get me going.

  • As said before, you need 3 files for this.

    In XSLT 2.0 you can generate multiple output files from one xsl stylesheet using the xsl:result-document instruction.

    In XSLT 1.0 you don't have that function, but depending on the processor it might be possible. For example for Xalan see http://xml.apache.org/xalan-j/extensions_xsltc.html#redirect_ext

Linq To SQL caching VS multi-user application.

We develop Win32 application that access to SQL 2005 database through Linq to SQL. The issue is when 2 users access to same record (View and Edit)… User 1 update record (DataContext.SubmitChanges()), User 2 will continue to see old information until he restart application. So, we would like to update context of user 2… The solution that appears right now is to call DataContext.Refresh to sync object with SQL table… We wondering if other solution exist ?

Thank you

From stackoverflow
  • I've noticed that Refresh can be really nasty depending on the data you've already grabbed from an entity, another solution is to reset the context you are using to a new instance.

    context = new MyDataContext(ConnectionString);
    

    This, at least in the scenarios where I am using it is less overhead and less DB calls.

    Philippe sillon : The issue with that is when we want to update entity that was attach to previous DataContext instance... A DataContext.SubmitChanges call update nothing because no change are detected... So, I think, I need to re-attach entity to new datacontext
    Quintin Robinson : Yes I admit I was frustrated by this as well, with pending changes on one context this becomes an issue. One of the LINQ quirks i'm beginning to live with.
  • Have you looked at the ObjectTrackingEnabled property of the datacontext. Try setting it to false? Ref: http://www.rocksthoughts.com/blog/archive/2008/01/14/linq-to-sql-caching-gotcha.aspx

Linq to SQL - "This member is defined more than once" error.

I have the following linq code...

CMSDataContext dc = new CMSDataContext();

var q = from u in dc.CMSUsers 
        join d in dc.tblDistricts
          on u.DistrictCode equals d.District into orders
        select u;

District shows this error: Ambiguity between 'tblDistrict.District' and 'tblDistrict.District'

Any ideas?

EDIT:

It turns out that I had the same table in two different dbml files. Apparently, I cannot do this. I will have to end up joining a table from one dbml file with another table from a different dbml file. If anyone can enlighten me on how to do this, I will deem it as an answer. Thanks.

From stackoverflow
  • If you have a FK releationship between two tables, LINQ-to-SQl will automatically create a property for it.

    For example, if you Order object has a CustomerID which is a Foriegn key to the Customers table, Order will automatically have a Customer property. If you already have a Customer property, there will be a conflict.

nHibernate Share References?

I'm getting a

"Found shared references to a collection" exception when saving an object.

Does anyone know what this means?

From stackoverflow
  • Do you have a reference to any of the objects in the collection somewhere else? Another session, possibly, or even within the same session in another object? Make sure that when you access hibernate, you are controlling the ONLY reference to those objects within any hibernate session.

  • quick google says

      rel   Group n --- 1 User
             m             ^
             |             | inh
             |  rel        |
             --------- n Member
    

    rel stands for relation (association) inh stands for inheritance

    The exception is thrown after Member objects have successfully been created and then have been read from the database. After the last Member object was read the transaction is committed but this fails.

    what do your mappings look like?

  • In theory it means that you have 2 records which contain the same reference to another object. At the database level this is most likely a weak entity, however at the code level this is likely to be represented as a collection.

    Have you copied another records collection? E.g.

    Blog blog1 =  Blog.Find(1);
    Blog blog2 = new Blog();
    blog2.Entries =  blog1.Entries;
    blog2.Save();
    

    This code is for ActiveRecords, but as it is built on top of nHibernate the underlying principles are the same.

    The interesting thing when i came across this issue was that the collection it referred to was incorrect. It was a different one.

    If this is your issue try iterating through each item and assigning it to the new collection in stead. E.g.

    Blog blog1 =  Blog.Find(1);
    Blog blog2 = new Blog();
    
    foreach (BlogEntry entry in blog1.Entries)
       blog2.Entries.Add(entry);
    blog2.Save();
    
  • Thanks a ton (@Xian). I'm a newbie to NHibernate. Your solution save me a lot of time

ASP.NET Session State Migration

I was hoping someone could validate my assumptions before I recommend that my client upgrade from a 30/mo to a 80/mo hosting package.

Site: the site is a custom ASP.NET ecommerce site. the shopping carts are stored in the inproc session.

Problem during busy seasons like we are having now, users are frequently losing their shopping carts and their FormsAuthentication Login information.

Solution I wanted to migrate the site to use a SQL Server Session state. My assumptions are that the customers are losing their shopping carts because the InProc sessions are recycling more frequently then their 20 minute timeout, due to load. Will moving the Session to SQL Server or a Session State Server allow customer to store their Shopping Cart Session without the recycle, If so, can once their will I have any issues if I increase the Session timeout to say 40 or 60 minutes

From stackoverflow
  • The assumptions sound reasonable to me. might also want to look at the settings on the AppPool and try to figure out why its recycling. Maybe all you need to do is change those (if you can).

    bendewey : I'm on a very strict shared hosting, the reason for the upgrade would move me to my own personal Virtual Private Server.
    Greg Dean : I was afraid of that...
  • Could you just add some RAM to the box? That might help and would likely be cheaper and simpler than moving the session to SQL Server. Of course, it would only be a stopgap, but if it saved them $50/mo for a few years it's probably worthwhile.

    You might also check the code to see if some other data is left in the session for much longer than necessary.

  • Using the SQL Session state means that sessions should survive a recycle of IIS, (but not a recycle of SQL Server if you use the default script which creates the session database in the tempdb).

    There is a script available from the Microsoft website which creates a permanent session state db. I would recommend using that one instead (See here).

    So, to basically answer your question. Yes, the SQL Session state will help. You might want to consider also using the out-of-proc state server to test your theory.

    Also, as a co-worker has just reminded me, make sure anything you store in the session is marked as serializable before migrating, otherwise you will run into problems.

How to write macro for Notepad++?

I would like to write a macro for Notepad++ which should replace char1, char2, char3 with char4, char5, char6, respectively. Thanks

From stackoverflow
  • This post can help you as a little bit related :

    http://stackoverflow.com/questions/283608/using-regex-to-prefix-and-append-in-notepad

    Assuming alphanumeric words, you can use:

    Search = ^([A-Za-z0-9]+)$ Replace = able:"\1"

    Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

    Search = ^(.+)$

    ^ points to the start of the line. $ points to the end of the line.

    \1 will be the source match within the parentheses.

  • Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
    After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:

    <Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
        <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
        <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
        <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
        <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
        <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
        <Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
        <Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
    </Macro>
    

    I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
    I don't think it will record actions in dialogs (like search/replace).

    Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
    I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.

    Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
    Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
    I tried some tricks, but I fear such task is beyond the macro capabilities.

    Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)

    [EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.

  • Actually, the shortcuts.xml file does not store user-generated macros and no obvious candidates contain this info. These instructions are out of date.

    Contrary to various websites' tips, storing user-generated macros isn't enabled for v.5.4.2. That XML file is there, but your macro does not get stored it in.

    I'm guessing it's a bug that'll be fixed by the next version.

    John Saunders : -1: This does not answer the question.
    svend : How so if the feature wasn't working! (Hopefully, it's been fixed now.)
    Robert Claypool : It still does not work in 5.6.4. Bummer.

Ironpython Studio forms question

This is a two part question. A dumb technical query and a broader query about my possibly faulty approach to learning to do some things in a language I'm new to.

I'm just playing around with a few Python GUI libraries (mostly wxPython and IronPython) for some work I'm thinking of doing on an open source app, just to improve my skills and so forth.

By day I am a pretty standard c# bod working with a pretty normal set of MS based tools and I am looking at Python to give me a new perspective. Thus using Ironpython Studio is probably cheating a bit (alright, a lot). This seems not to matter because however much it attempts to look like a Visual Studio project etc. There's one simple behaviour I'm probably being too dumb to implement.

I.E. How do I keep my forms in nice separate code files, like the c# monkey I have always been ,and yet invoke them from one another? I've tried importing the form to be invoked to the main form but I just can't seem to get the form to be recognized as anything other than an object. The new form appears to be a form object in its own code file, I am importing the clr. I am trying to invoke a form's 'Show' method. Is this not right?

I've tried a few (to my mind more unlikely) ways around this but the problem seems intractable. Is this something I'm just not seeing or would it in fact be more appropriate for me to change the way I think about my GUI scripting to fit round Python (in which case I may switch back to wxPython which seemed more approachable from a Pythonic point of view) rather than try to look at Python from the security of the Visual Studio shell?

From stackoverflow
  • I'm not totally clear on the problem. You can certainly define a subclass of System.Windows.Forms.Form in IronPython in one module, and then import the form subclass in some other module:

    # in form.py
    from System.Windows.Forms import Form, Button, MessageBox
    class TrivialForm(Form):
       def __init__(self):
           button = Button(Parent=self, Text='Click!')
           button.Click += self.show_message
    
       def show_message(self, sender, args):
           MessageBox.Show('Stop that!')
    
    # in main.py
    import clr
    clr.AddReference('System.Windows.Forms')
    from System.Windows.Forms import Application
    from form import TrivialForm
    if __name__ == '__main__':
       f = TrivialForm()
       Application.Run(f)
    

    Is it that IronPython Studio's form designer/code generator won't let you structure your code like that? (I've never used it.)

  • In the end it was even simpler.

    I was trying to invoke the subform thus:

    f = frmSubform()
    f.Show()

    But I actually needed to do it this way

    f = frmSubform()
    Form.Show(f)

    Form.ShowDialog(f) worked also; in a Dialog format of course.

    A simple enough error but until you know you, well, don't know.

    I'm not 100% sure I understand at this stage why what works, works, but I'm sure I shall learn with experience.

What is the best way to determine application root directory?

I need to get all dlls in my application root directory. What is the best way to do that?

string root = Application.StartupPath;

or

string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName;

and after that

Directory.GetFiles(root, "*.dll");

Which way is better? Are there better ways?

From stackoverflow
  • AppDomain.CurrentDomain.BaseDirectory is my go to way of doing so.

    However:

    Application.StartupPath gets the directory of your executable

    AppDomain.BaseDirectory gets the directory used to resolve assemblies

    Since they can be different, perhaps you want to use Application.StartupPath, unless you care about assembly resolution.

    BeowulfOF : Correct, I follow the same path ;-)
    faulty : Application.StartupPath will be effected by "Working Directory" if it's set in the exe shortcut, or the process is started from another apps. I didn't realized it until much later, which had cost me days of sleepless night to troubleshoot what went wrong.
  • It depends. If you want the directory of the EXE that started the application, then either of your two examples will work. Remember though, that .NET is very flexible, and it could be that another application has linked to your EXE and is calling it, possibly from another directory.

    That doesn't happen very often and you would probably have written if it did, but it is a possibility. Because of that, I prefer to specify which assembly I am interested in and get the directory from that. Then I know that I am getting all of the DLLs in the same directory as that specific assembly. For example, if you have an application MyApp.exe with a class in it MyApp.MyClass, then you would do this;

    string root = string.Empty;
    Assembly ass = Assembly.GetAssembly( typeof( MyApp.MyClass ) );
    if ( ass != null )
    {
       root = ass.Location;
    }
    
    Bob : Nice variable naming
    Rob Prouse : I especially like determining my ass.Location ;D
    Steven Sudit : It requires two hands.
  • Environment.CurrentDirectory
    

ReSharper configuration in VS solution.

Anyone have experience with adding a ReSharper profile to the VS2008 solution and share between developers - would like to mimmick the behavior of CodeStyle Enforcer and how it 'follows' the solution.

Any thoughts?

Thanks /Jasper

From stackoverflow
  • Look in Options / Languages / Common / Code Style Sharing

    jaspernygaard : Excellent - I'll try it out.

How to create a mock object based on an interface and set a read-only property?

I'm new to TDD. So any help would be appreciated. I'm using NUnit and Rhino mocks. How can I set the ID value to 1 in my mock object?

I had a look at this: http://www.iamnotmyself.com/2008/06/26/RhinoMocksAndReadOnlyPropertyInjectionPart2.aspx but the reflection doesn't seem to work against interfaces.

    public interface IBatchInfo
    {
        int ID { get;}
        Branches Branch { get; set; }
        string Description { get; set; }                                
    }

 [SetUp]
       public void PerFixtureSetup()
       {

           _mocks = new MockRepository();
           _testRepository = _mocks.StrictMock<IOLERepository>();

       }

    [Test]
            public void ItemsAreReturned()
            {
                IBatchInfo aBatchItem=  _mocks.Stub<IBatchInfo>();

                aBatchItem.ID = 1; //fails because ID is a readonly property
                aBatchItem.Branch = Branches.Edinburgh;


                List<IBatchInfo> list = new List<IBatchInfo>();

                list.Add( aBatchItem);

                Expect.Call(_testRepository.BatchListActive()).Return(list);
                _mocks.ReplayAll();

                BatchList bf = new BatchList(_testRepository, "usercreated", (IDBUpdateNotifier)DBUpdateNotifier.Instance);
                List<Batch> listofBatch = bf.Items;

                Assert.AreEqual(1, listofBatch.Count);
                Assert.AreEqual(1, listofBatch[0].ID);
                Assert.AreEqual( Branches.Edinburgh,listofBatch[0].Branch);
            }
From stackoverflow

How to read list of string

Hi,

I have this:

Public stringList As New List(Of String)

I need to read the whole list using For each statement, what is the best way to do so using VB.net syntax?

Thanks,

From stackoverflow

VS2008 binary 3x times slower than VS2005?

I've just upgraded a native C++ project from VS2005-SP1 to VS2008-SP1
The first thing I tested was a very basic functionality test of the application and the first thing I noticed is that the main number-crunching algorithm performs three times slower in the VS2008 binary.
I tested again the VS2005 binary to make sure there isn't any other difference and it still performed as it did before.
Did anyone stumble into this?

From stackoverflow
  • Strangest. Thing. Ever.

    It seems that the project upgrade wizard of vs2008 simply doesn't copy the 'Optimization="2"' property so the new project is left with no optimization in release.

    The fix was to go to the properties dialog, change optimization to 1 and then back to 2. compile again and everything works it should.

    I couldn't find any official reference for this only this obscure reference in an MSDN forum.

    Drew Hoskins : It's nice to know the optimizer is kicking that much butt, at least.

How to know in Ruby if a file is completely downloaded

Our issue is that our project has files being downloaded using wget to the file system. We are using ruby to read the downloaded files for data.
How is it possible to tell if the file is completely downloaded so we don't read a half complete file?

From stackoverflow
  • The typical approach to this is to download the file to a temporary location and when finished 'move' it to the final destination for processing.

  • I asked a very similar question and got some good answers... in summary, use some combination of one or more of the following:

    • download the file to a holding area and finally copy to your input directory;
    • use a marker file, created once the download completes, to signal readiness;
    • poll the file twice and see if its size has stopped increasing;
    • check the file's permissions (some download processes block reads during download);
    • use another method like in-thread download by the Ruby process.

    To quote Martin Cowie, "This is a middleware problem as old as the hills"...

Pasting an image from clipboard to a website

I need to come up with a solution for users to be able to paste an image on to a website, then upload that image on to the web server. I'm not sure what the right solution for this - I am pretty sure javascript is out of the question because I don't think it can handle binary clipboard data (or any clipboard data?)

So, I'm not sure which way to go with this. Is this something possible with a Java applet? Or maybe a Flash SWF? Any other alternatives?

From stackoverflow
  • Rad Upload (java applet). It's not free, but it is relatively cheap.

  • Or this free one (via another StackOverflow question)

How to create a custom loading screen in JavaFX?

I'd like to create a custom loading screen for a JavaFX application. Don't want the user to see the Java coffee cup icon, I want to put my own graphic there!

I've found out how to provide a static image, or even an animated GIF, but I'm more interested in a Flash-like screen where I can specify what the state of the image looks like at certain percentages.

Any ideas?

From stackoverflow
  • If you're setting things up as shown on This blog entry, it looks like the answer would be 'no' - the loading graphic is just part of the overall options that are passed to the applet. Because this applet could be any java code (not just javaFX), there's no way to tie your custom renderer in.

Weird VS2008 Intelliesense problem

I have a class library (.dll) that i included in a asp.net website. Adding the reference was easy but for some weird reason when i try to type "imports blah.blahblah" vs2008 intellisense will not refelect the namespace of that project. does anyone ever come across this problem? Forgot to mention the project contain one module, could that be the problem?

From stackoverflow
  • Stupid question: does the code in your included project specify that it's in a namespace? If it doesn't then you could just start using the types without an imports statement.

Delete All Emails in a Highrise App

How do I delete all the emails in my highrise app? I don't want to delete the entire thing and start over, I've got companies and tags and metadata. What's the easiest way?

This question paraphrased from Tibor Holoda's question on GetSatisfaction

From stackoverflow
  • It looks like this is available through the API, and should be easy with the ruby bindings:

    #!/usr/bin/env ruby
    ENV['SITE'] = "http://passkey:X@my.hirisehq.com"
    require 'highrise'
    Highrise::Person.each do |person|
      person.emails.each {|email|
        email.destroy
      }
    end
    

ASP.NET MVC: Controller ViewData & ViewPage ViewData

Hello,

I seem to be unable to find the "link" between a controller's ViewData collection and a ViewPage's ViewData collection. Can anyone point me to where in the MVC framework a controlle's ViewData collection is transferred to a ViewPage's ViewData collection?

I have spent quite a lot of time using Reflector to try and work this one out but I'm obviously not looking in the right place.

From stackoverflow
  • The Controller.View method transfers the ViewData into the ViewResult.

    ViewResult.ExecuteResult transfers this into its ViewContext.

    In WebFormView, the private RenderViewPage method transfers the ViewData from the context argument to the view itself. Other view in genes may work differently.

Consuming a "Table of data" in Silverlight

Since silverlight does not have any support for DataSets/DataTables, what would be the best approach if I wanted to consume a table of data from a database?

A bit like this: user action in silverlight -> get data from server -> display in GridView

The thing is, I do NOT know how many and which columns the data will have...

Can I bind the DataGrid to some loose form of XML, generated on the server or will I have to parse The datasets returned by the webservice myself in another format or ... ?

From stackoverflow
  • One approach that is working for me is the following one I just found: http://blog.bodurov.com/How-to-bind-Silverlight-DataGrid-from-IEnumerable-of-IDictionary

    By consuming the XML file, and putting the data in a List of Dictionary objects (the list is the records and the dictionary per listitem is the fieldlist with value) I can use the method in the URL above to dynamically create objects. With these objects I can fill the GridView.

Is there a way to customize Firebug's keyboard shortcuts?

Is there a way to customize Firebug's keyboard shortcuts? I love being able to step through javascript code using the Firebug console, but it looks like I'm limited to either using the default keyboard shortcuts for stepping over/into/out of code or using the mouse to click the appropriate button.

Am I missing something?

Is there some secret about:config hack in Firefox/Firebug that would help me?

From stackoverflow
  • As stated in their discussion forum, you can try keyconfig... otherwise, it is a known bug/limitation.

  • As @VonC mentioned, there is an open ticket on this. In my experience, keyconfig doesn't work for this purpose. I did write a patch that allows for the debugger execution control keys to be customized in about:config. I have also posted an XPI with this fix if you don't want to wait for it to be accepted upstream, and/or you don't want to build it yourself.

  • Another option would be to configure the shortcuts manually in file

    %APPDATA%\Mozilla\Firefox\Profiles\<profile>\extensions\firebug@software.joehewitt.com\content\firebug\browserOverlay.xul
    

    For example, I removed the shortcut on F12 by commenting the corresponding section because it conflicts with the Undo Closed Tab shortcut of Tab Mix Plus.

    Disadvantage: An update of Firebug will overwrite the modified configuration.

How can I completely remove TFS Bindings

I have a solution that contains a good deal of projects,

I would like to remove the source control bindings completely, how can I do this?

Update: What I really want to do is move one solution and its projects from TFS 2005 -> 2008. Thats why I am removing the bindings, is there a better way to do this?

From stackoverflow
  • The simplest solution would be to open Visual Studio, deactivate the TFS Plugin in Tools > Options > Source control and reopen the solution you want to clean. Visual Studio will ask to remove source controls bindings

    Michael L : Also I forgot to mention, this is a VS 2008 Solution, and I think your answer only works with VS 2005.
  • File -> Source Control -> Change Source Control and then unbind and/or disconnect all projects and the solution.

    This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).

    The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)

    Michael L : this is a great answer, I would also like to add - disable your network adapter to avoid any prohblems during this operation

Why do I get an error using moveTo in JavaScript?

I am opening a new window from a button using var myWindow = window.open(...). I then want to move that window to the correct location on the screen. I use myWindow.moveTo(10,10) to do this but I get an Access Denied error.

The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?

I am using IE7. (The work is for an existing Intranet that includes lots of ActiveX so all users use IE7)

From stackoverflow
  • The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?

    Browsers security model have been increasingly restrictive over the last couple of years. What you could do a few years ago, isn't allowed any more. Blame it on advertising companies.

    Baffled by ASP.NET : Is there a way around it though? With IE configuration?
    troelskn : I'm pretty sure this is the "Same Origin Policy" in action (Google that). You can change the clients configuration to lax on security, if you have access to them.
  • You could try to put the information from the other site in an iframe located on the same host that runs the window.open JavaScript. Or maybe even better, get the information server-side and present it directly from your site. Iframes can be trouble.