Monday, April 25, 2011

How to change LINQ O/R-M table name/source during runtime?

I've got a database, and an entityset created by the O/R-Mapper, using all this with LINQ.

In the O/R-Mapper I need to enter a table name (source) for every table, which is being used for the SQL generated by LINQ. In the .dbml file it looks like this:

<Table Name="dbo.Customers" Member="Customers">

Now I'd like to change this table name during runtime, so the SQL will be run against some other table (customers2008 instead of customer, for example).

Is there any way to change the table name (source name) during runtime?

[Update] After some testing to my dismay I had to discover that XmlMappingSource does render computed properties which are not persisted in the database unaccessable (yes, even the mapping created by SqlMetal does ignore everything which is not persisted).

From stackoverflow
  • Kind of ... You'd have to do something like this:

    1. Create the entities in the designer.
    2. Use SqlMetal to generate an xml mapping file from the .dbml file generate by the designer.
    3. Update the table names in the xml file.
    4. Then in your code, use the DataContext constructor overload that accepts an XmlMappingSource created with the xml mapping file.

    Here's a blog post that explains this process step by step: http://weblogs.asp.net/guybarrette/archive/2008/07/23/linq-to-sql-dynamic-mapping.aspx

    I'm using a similar process with an ERP database that has table names like ttccom001xxx where xxx is the installation ID (I know it's a horrible schema, but there's nothing I can do about it). We have multiple installations, so I copy the initial xml mapping once for each installation and then replace xxx with the installation ID. I wrote a small console app that uses Regex to take care the replacements and added it as part of my build process.

    Sam : Now I only need a way to create this mapping files during runtime, so I won't have to try and keep the mapping file in alignment with the data classes.
    Sam : Oh well, I managed to create these files, but alas, they do not work as expected. Running out of time now, more tomorrow.
    jrummell : I would recommend creating the xml mapping in the post-build event instead of at runtime.
    Sam : Even the mapping files created with SqlMetal do render the DataContext unusable, since they disable access to computed properties which are not persisted in the database. Pity.
    jrummell : Did you add these properties in a partial class? If so, they should still be accessible. You wouldn't be able to use them in a query, however, because they don't map to a column in the database. This is true for xml and attribute based mapping.
  • Here's a link to Microsoft's External Mapping Reference.

    External mapping overrides attribute-based mapping.

    Here's the essentials.

    1. Create some xml that represents your mappings.
    2. New up an XmlMappingSource and give it your xml.
    3. When you construct your DataContext, use a Constructor that accepts the XmlMappingSource, such as this one.
    Sam : You don't happen to have a link or some source how to create a mapping file in a running program?

Can an ASP web service return a ZIP file?

I'd like this to be possible!

Can you write a web service (using C# and an asmx) that returns a ZIP file?

If so, can you give a simple example?

Thanks

From stackoverflow
  • Sure thing,

    No matter if it's a ZIP, DOC, PDF. We call that MTOM in the SOAP world

    see this example yourself

  • This article shows how to return a file from webservice: http://articles.techrepublic.com.com/5100-10878_11-5805105.html.

  • I'm not sure you can use MTOM with vanilla .NET asmx services ( see here) . I know it's possible if using WCF though.

    As a (poor) alternative, you could write a web method that returns the zipped data as a base64-encoded string (which would be probably quite long depending on the size of the file, so useful for small datasets only). Then you decode the string in the client to get the original data.

    Tony Peterson : For sending the base64 encoding back to the caller, should the InsertLineBreaks option of Base64FormattingOptions be used?
    axel_c : I think you can get away with just Convert.ToBase64String (byte[] data). See http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx for details.
  • Thanks empi, I've got it all working. Marvellous...

Can signed applets connect with a different host from which they originate?

I need an applet to open a socket and communicate with a server listening on the local host to which the applet downloaded (the end user machine).

contrary to what I have read about applet security, it seems that even signed applets cannot open a socket to a different host from which they were downloaded (on the same machine it works perfectly)

I have certified the applet using -selfcert, signed it using jarsigner, and still, whenever it tries to open a socket to a different host, I get:

Java.lang.Exception: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:9999 connect,resolve)

I even tried changing the Java policy file, although with signed applets it is not required to do so:

grant codeBase "http://applethost:8080/socket" { permission java.security.AllPermission; permission java.lang.RuntimePermission "usePolicy"; };

What is the deal with sigend applets, can they connet to a different host or not?

From stackoverflow
  • Yes, when you load your applet, if you choose to accept its certificate and trust it, it is granted AllPermission, which includes SocketPermission. I have written a signed applet before that connects to a host other than the one from which it was loaded. You could try temporarily changing your java policy file to just have

    grant {
      permission java.security.AllPermission;
    };
    
    • Look in your policy file to see if it defines any other policy.url locations, perhaps they are interfering.
    • Check your browser settings for javascript maybe.
    • Make sure that you accepted the certificate for the applet and that it gets installed to your list of site certificates.
    • Make sure the grant codeBase line you have is the same as the codebase in your applet's manifest.
    • You could try printing out the list of permissions that your applet has before you try the connect.
    • You could try to programatically grant AllPermission from within the applet.
    adilei : @John, it seems that just granting permission java.security.AllPermission; works but that is still the only way I could make it work. I made the applet print its codeBase and it seems fine. Very frustrating, but at least thanks to you I know it is security related indeed and not some weird issue.
    adilei : @John, I am going to accept this answer since it's true - it is possible for an applet to open a socket to a different host. I am going to set up a follow up question though if you are interested in following me there. Cheers, Adi.
    A. Levy : How can you "programatically grant AllPermission"? What is the point of having a security manager to prevent execution of malicious code if the code can just grant itself permissions to do whatever it wants? It that is even possible, it shouldn't be!. @John, if you read this, could you please delete that last bullet to prevent other people from going down the wrong trail by trying to implement something the Java standard explicitly prevents. Either that or explain why I'm wrong. Thanks!
    Knife-Action-Jesus : I know this is old, but you can't do this programatically. It would defeat the whole purpose of applet security. The proper way to get the permissions you need is to sign the jar. And wrap all of your code in a privileged block.

Looking for MsPaint alternative with alpha support

In our codebase I write many things that, for testing, depends on the image Im loading have alpha. Usually, I make all my own testimages/programmers-art in MsPaint. But every time I need an image with alpha, I have to go and disturb one of our artists. (Or start the loading of GIMP and go for a coffee break.)

So Im looking for alternatives, as quick and simple as MsPaint but which has alpha support. I tried GIMP but the time it takes to load that behemoth makes it not an option.

Is there no software in the middle grounds between mspaint and gimp? From the looks of my googling and searching through wikipedia, most raster graphics editors aim to be a Photoshop alternative.

From stackoverflow
  • Paint.NET

    It's basically exactly what you're asking for. Not hardcore as Photoshop, more advanced than Paint.

    Built on the .NET Framework so may only run on Windows (might work with Mono, I don't know), but as you've said you use Paint I'm assuming you're on Windows anyway.

    Matt Hamilton : I'd upvote this twice if I could. :)
    banjollity : +1 for Paint.NET (and if I were 38 seconds quicker those upvotes would be mine!!! :)
    Garry Shutler : Hehe, yes, just a little too slow :)
    banjollity : Enjoy your reputation Mr Shutler. I'll get you next time. *shakes fist*
    WestDiscGolf : +1 fast finger typing :-)
  • Paint.Net is a simple and easy alternative that gives you a little more features than MSPaint, without having to load big heavy monsters (or read 500-page manuals).

    As far as I can tell, it supports Alpha quite nicely, as well as many other features a non-artist might need for their graphics work.

    http://www.paint.net/

    mizipzor : Seems like Paint.Net is the way to go. Found it on wikipedia but deemed to much photoshop-ish. Im downloading it now, and to compensate for your "lost" upvotes, Ill accept your answer. ;)

getting System.ServiceModel.AddressAccessDeniedException on Vista for WCF service

We have an application that starts a WCF server and the app reads from it.

It starts and can be read fine on all Windows XP machines.

On our Vista machine, however, we get:

System.ServiceModel.AddressAccessDeniedException
"The process has no rights to this namespace."
System.Net.HttpListenerException

The URL is at localhost:

http://localhost:8731/ABC.Testing.Business.Core/SecurityService/?wsdl

The error message sent us here:

http://msdn.microsoft.com/en-us/library/ms733768.aspx

And we did what it said:

netsh http add urlacl url=... user=...

which changed the rights but the WCF service still cannot start on Vista.

Does anyone have any experience with this that could move us forward? Thanks.

From stackoverflow
  • I've had similar problems on Vista, which I haven't figured out yet. What error is it throwing now that you have run that netsh command? Have you tried giving that user local administrator privileges?

    Edward Tanguay : In the netsh command I gave the rights to the user than runs the application, but what I think I need to do is find out which process needs the rights, but this is a Unity-based app and the WCF is started before it even gets to the bootstrapper, so which process do I need to give rights to?
    Andy White : I think I'm in the same boat as you now... not sure what to do :) I've done the same thing with my service (netsh command), and it still won't run in Vista, but it runs fine in XP if I run the equivalent httpcfg command. There must be some cryptic setting somewhere in Vista that is block us.
  • Hi Edward, try reading through this blog post and see if it helps.

    http://blogs.msdn.com/paulwh/archive/2007/05/04/addressaccessdeniedexception-http-could-not-register-url-http-8080.aspx

How to check that a disk is RAID1 on Windows Server 2003/2008?

I am usually renting dedicated servers under Windows Server 2003/2008. Those servers are said to be "hardware RAID1"; yet I am wondering how can I verify this property of the server remotely?

As far I can see, disks appears as classical IDE disk from the windows disk manager, and it does not tell me anything about the RAID properties of the disk.

From stackoverflow
  • Probably, you can't. Hence the "hardware"-ness of the setup – the drives appear to the operating system as a single IDE drive.

  • You'd need to install the dedicated vendor disk management tools. eg Dell used to replace the disk manager MMC snap in with one that showed all this stuff.

    Windows itself does not care, whether it's a 10 disk RAID 10 or a single one.

    Joannes Vermorel : Thank for the answer. Hum, what if you have not single clue about the identity of the vendor? :-)
    gbn : Ask your vendor? For one of my projects, we can see what the server make and model is when we rent it...

How to get Eclipse to give Cygwin's GDB a posix path to the executable?

I'm using Eclipse on Windows to program C++ using Cygwin's toolchain. I would like to use it for debugging as well, but my problem is the following:

  • The executable to debug is in a sub-folder of the workspace (pretty standard, I guess) but not of the actual Project from which the executable is built.
  • Eclipse and GDB have different path formats: Eclipse works with Windows paths, whereas GDB works with posix paths. Eclipse knows D:\Path\To\Exe whereas GDB needs /cygdrive/d/Path/To/Exe.
  • Eclipse insists that it can find the executable to debug when I enter the path in the "Debug configurations..." dialog. The "Debug" button is disabled until the path is correct.
  • Eclipse does not seem to take ${workspace_loc} in that particular input box.

Is there some hidden option I don't know about? Have you had the problem before?

What I've tried so far

  • Forcing Eclipse to pass the path I input to GDB --- did not work.
  • Fiddling with source lookup paths and path mappings --- did not work, it's really just for source files.
  • Creating a C++ Project for the output folder where the executable is, so I could have a relative path to the exe inside the project --- did not work.

Things I could still try

  • Use the .gdbinit file to discard the path given by Eclipse and load the real executable with posix paths --- tried that, but not very hard.
  • Specify a wrapper as argument to GDB --- pollutes the root of my workspace.
  • Provide my own plug-in to deal with the case --- adds another piece of code to maintain in another language.
From stackoverflow
  • Cygwin comes with a program called cygpath to translate paths from windows to unix and vice-versa, e.g.

    $ cygpath -u 'c:\Users\Andrew\Documents\svn'
    /cygdrive/c/Users/Andrew/Documents/svn
    

    do a cygpath --help for more info.

    So you probably want to write a wrapper for GDB that translates any windows-specific paths to unix paths, and then invokes the real GDB.

  • In Eclipse in Preferences->C/C++->Debug->"Common Source Lookup Path" add new path mapping. As compilation path you should use Unix like path (e.g. /cygdrive/c), as local system path you should use Windows like path (e.g. c:).

    Carl Seleborg : Thanks, pensamiento, I did try that, but it did not work. My understanding is that this path mapping does not affect the path that Eclipse hands to GDB as executable to debug. The name of the setting does not suggest that this should work, either.
    Ben Gartner : This worked for me. Thanks pensamiento!
  • The problem went away when upgrading to Eclipse Ganymede.

Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the results of malloc. I.e.

int *sieve = malloc(sizeof(int)*length);

rather than

int *sieve = (int *)malloc(sizeof(int)*length);

Why would this be the case?

From stackoverflow
  • In C you get an implicit cast from void* to any other (data) pointer.

  • It's optional. Typically you do the cast to avoid compiler warnings.

    Marco

    dreamlax : You won't get a warning because a void pointer can always be cast to any other pointer.
    Lars Wirzenius : Thus, if you get a warning without the cast, your code has a bug, probably not including .
    quinmars : Or he has an ancient libc version, where malloc returns a (char *)-pointer: http://en.wikipedia.org/wiki/Malloc
  • In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically cast to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:

    int *sieve = malloc(sizeof *sieve * length);
    

    which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve.

    Casts are bad, as people have pointed out. Specially pointer casts.

    Thomas L Holaday : In the preferred alternative, what is "a" ?
    dirkgently : Typo. Thanks though!
  • You don't cast the result, since:

    • It is unnecessary, as void * is automatically and safely promoted to any other pointer type.
    • It can hide an error, if you forgot to include <stdlib.h>.
    • It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
    • It makes you repeat yourself, which is generally a badness.
    jalf : True. However, in C++ the cast is required, so if you want your code to work in both, you'll have to compromise. But in pure C, don't do the cast for the reasons you stated.
    Jonathan Leffler : Agreed with @jalf. My code normally compiles under C or C++ compilers, even though it is primarily C. I sometimes use /*=C++=*/ comments to indicate why the cast is present.
    Matt Joiner : amen for a straight C answer, none of this C++ nonsense
  • In C you can implicitly cast a void pointer to any other kind of pointer, so an explicit cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.

  • As other stated, it is not needed for C, but for C++. If you think you are going to compile your C code with a C++ compiler, for which reasons ever, you can use a macro instead, like:

    #ifdef __cplusplus
    # define NEW(type, count) ((type *)calloc(count, sizeof(type)))
    #else
    # define NEW(type, count) (calloc(count, sizeof(type)))
    #endif
    

    That way you can still write it in a very compact way:

    int *sieve = NEW(int, 1);
    

    and it will compile for C and C++.

    Hosam Aly : Since you're using a macro anyway, why don't you use `new` in the definition of C++?
    quinmars : Because there is no reason to do so. It is mainly for C programs that are compiled with a C++ compiler. If you are going to use 'new', the only thing you get are problems. You need then also a macro for free. And you need a macro to free an array, a differentiation that doesn't exists in C.
    quinmars : Not to mention if it's not you who frees the memory but maybe a C library you are using, etc. Many possible problems without any gain.
    Hosam Aly : Hmmm... I didn't think of that. Is it an error to use `free()` to free memory allocated with `new`?
    quinmars : Heh, I always thought so, but I'm not 100% sure. Maybe a good SO-question :)
  • I like this explanation because it's throughout, talking about possible goodness and bad consequences: Casting.

  • This is kind of off topic, but a lot of people here I think are being a little harsh on casting. There are perfectly legitimate reasons to do it, like the following:

    int x = 1;
    int y = 2;
    double z;
    z = (double) x / (double) y;
    

    Lest we forget our painful integer division bugs!

    David Cournapeau : It was about casting the return of malloc. Of course, casting is sometimes necessary - but casting in C should not be done lightly. It can hide a lot of bugs, and explicit cast bypass the C system (C is nothing more than a typed assembler after all :) ).

Definitive website or pdf that explains about linux?

like what is X windows,Cygwin,file system

From stackoverflow
  • I think this is a great way to start

  • Well, first you have to choose which Linux distribution you wish to use/learn, then you just use that distro's documentation, which normally has allot info.

    You can find here some linux beginner lessons: http://www.linux.org/lessons/beginner/toc.html

    Finally the best way to learn, besides reading is "getting your hands dirty". Install a distro of your choice and mess with it :)

    Rich : Getting my hands dirty is definitely how I learned - you install it, fiddle, wonder how to do something, search, and learn :)

Why does Cocoa return an empty string occasionally?

I have some code in my application that looks something like this:

char *hash = (char*) sqlite3_column_text(get_bookmark, 0);
NSString* postHash = [NSString stringWithUTF8String:hash];

This works for me every time; I've never seen it not work. Most of my users do not experience problems (as far as I know). However I find that postHash is an empty string (@"") for some users some of the time.

Can anyone explain why?

Some more context/speculation:

This only seems to happen on jailbroken handsets. Is there anything different about them? I gather that there's usually less memory available. Anything else that could contribute here?

postHash is used in a table cell and is occasionally seen to be populated correctly so I'm reasonably confident that the database call should work. In fact, if the database also has an empty string it's because of a very similar piece of code so the question remains.

hash is certainly returning with a non-NULL value. If I force a NULL here, the app crashes. Similarly, postHash is not nil as that would also crash the app (for the same reason).

I am thinking that this is possibly memory related. If the method tries to allocate too much memory before -didReceiveMemoryWarning can get called what happens? I know that, at some point, the Springboard ejects the app. But is it possible that Cocoa returns a null string here rather than the expected value? I've heard of a few reports that, as far as I can tell, can only have been caused by an empty string being present where something longer should have been present.

Any other speculation, theories or ideas welcome.

From stackoverflow
  • However I find that postHash is an empty string (@"") for some users some of the time.

    Can anyone explain why?

    Because hash is an empty string (hash[0] == '\0').

    Stephen Darlington : I agree that this would be the most likely scenario but, as noted in the question, I'm pretty confident that it can't be an empty string.
    Peter Hosey : It's not “the most likely scenario”; it's the *only* scenario. NULL gets you an exception. Any non-empty string gets you a non-empty string. Only an empty string gets you an empty string. Simple proof: NSLog the length in (strlen(hash)) and length out ([postHash length]).
  • I finally found the solution to this. I'm going to give Peter the accepted answer as he is right but the reason that I was getting an empty string is... interesting.

    The database is populated correctly. The query is also correct. The difference between my phone and my users is that they have jail broken handsets. And apparently jail broken iPhones sometimes use a different version of SQLite than found in shipping versions of iPhone OS.

    The change in version exposed a bug in my code that caused one of the parameters to be set incorrectly and sqlite3_column_text to return an empty string.

    Max Howell : There needs to be a way to detect a jailbroken phone and then decline users support. How much time did you waste because of this? It's not on.
    Stephen Darlington : Difficult to be sure, but I think it took me about twenty hours -- and I only found the solution by accident! On the flip side, they were paying customers. Still, I have said that I reserve the right not to support jail-broken phones. I wrote more on the apps blog: http://www.yummyapp.com/2009/05/pirates-and-jail-break.html

file_get_contents: failed to open stream: Host is down

Hello, I am running php5 on my mac osx 10.5. If I write a simple php script:

<?php
file_get_contents('http://www.google.com');
?>

And run it in the command line, I get the following error:

"Warning: file_get_contents(http://www.google.com): failed to open stream: Host is down"

I'm not sure if I'm missing some setting in php.ini or something. I know if I run the same script off of my server, it executes w/o warning.

Any ideas as to what I'm missing here?

Thanks!

From stackoverflow
  • Check your firewall?

  • Firewall or you aren't connected to the internet (or maybe you are running something like LittleSnitch which is blocking Terminal.app's access).

  • Check that the PHP setting allow_url_fopen is set to On. Use phpinfo() to check all settings.

    Bart S. : That throws a different error.

Are ids in mysql guaranteed not to be repeated, even if rows are deleted?

Of course if I put enough rows eventually there will be a repeat. But let's assume I choose a big enough id field.

I want to know if I can assume that the id uniquely identifies the row over time. And if the client sends me an id I want to be able to determine what row it refers or if the row was deleted (or if it is a fake id, but in that case I will not care telling, wrongly, that the row was deleted).

Please refer also to the following: if I restart the database, or backup and restore - will it be continue creating ids where it left - or may be it will decide to "fill in the holes"

From stackoverflow
  • If you have a "int not null auto increment primary key" that you never reset, then yes IDs will not be reused.

    However, this raises an interesting question - what happens if you happen to reuse an old ID (even though it won't happen by default in MySQL, but the human factor always counts) ?

    If your database is properly normalized, cascaded and constrained your application should be able to handle the reuse of an ID.

    Edit (since you edited your post, I'll flesh out my answer), about this quote: "And if the client sends me an id I want to be able to determine what row it refers or if the row was deleted". It's always possible to determine what row an ID belongs to if it's not deleted (kind of vital to be able to extract information out of your database).

    However if the row the id refers to is deleted, then it's not possible to determine what row it belongs to... since it's not there. If you need this I would advice you to implement some type of auditing functionality, preferably by triggers .

    flybywire : and when do I reset it? Is it something I do with a command or can it happen as a side effect of something.
    thr : Well, it's not something that will likely happen - but it is possible through various sql commands in mysql.
    tehvan : If you're not certain about when to reset, then don't reset it. Automatically generated ids are not meant to be be meaningful nor reusable.
    thomasrutter : Usually an auto_incremement column will also be a primary key would it not. So in that case you wouldn't have to worry about manually re-using an ID, right? You'd get a clear duplicate value on primary key error.
    thr : thomsarutter: true
  • The current autoincrement value is preserved across backup/restores via an extra attribute attached to the table. You can see it in a dump just after the ENGINE=:

    mysql> create table foo ( bar int(11) primary key auto_increment );
    Query OK, 0 rows affected (0.06 sec)
    
    mysql> insert into foo () values (), (), (), ();
    Query OK, 4 rows affected (0.00 sec)
    Records: 4  Duplicates: 0  Warnings: 0
    
    mysql> show create table foo \G
    *************************** 1. row ***************************
           Table: foo
    Create Table: CREATE TABLE `foo` (
      `bar` int(11) NOT NULL auto_increment,
      PRIMARY KEY  (`bar`)
    ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
    1 row in set (0.00 sec)
    

    You can reset it using "ALTER TABLE tablename AUTO_INCREMENT=", but it looks to me like the attribute value is ignored if it isn't more than the maximum existing id when you do an insert.

  • also note that the described behaviour of not reusing a previously used ID is valid for the MyISAM engine, but actually is not valid for all available engines.

How to render animation or effects using Core Graphics

I want to draw a projectile of a cannon moving and explosive effects (just simple broken bits flying around). How should I approach this using Core Graphics (on iPhone)?

I am using an NSTimer to call a render method and update the animated projectile or explosive effects and I have no problem drawing each individual pieces (such as filled rec, or line) but I found that drawRect always erases the previous content and only render the new stuff.

How would you approach this?

From stackoverflow
  • There's a really good book on this at the Pragmatic Programmers site.

    hhafez : I looked at that book at the book store it only has one chapter on iphone? Is coreanimation on iphone and macosx that simmilar?
    Boon : This is not so much an animation issue as it is a rendering issue, so that book won't be of much help (case in point, I have that book so I know).
  • Found the solution, use setNeedsDisplayInRect instead of setNeedsDisplay and limit to the small area I was drawing into (Thanks Erica).

How to determine programmatically how a DVD or HDD is connected - Master or Slave?

On a desktop one can easily look at the jumpers. The same is not true for laptops and it would be useful to determine how a drive is connected if one wants to replace it.

Any ideas of how to do this, or even whether it is possible?

Intended platform is Windows (either XP or Vista).

Recent experience is with a Toshiba A50 laptop where the firmware turned out to be Toshiba specific, and a drive through standard channels (Toshiba's) was 5 times more expensive than was supportable by the value of the PC and the BIOS was unhelpful in the extreem.

It took 5 attempts and a very helpful supplier to crack that one and I wondered about avoiding this issue, should it arise, in future! :)

From stackoverflow
  • If you're using a Windows platform, WMI may be able to tell you...

    David Max : How can you use WMI to tell you?
  • Most older BIOSes (and I say older, since you are talking about PATA) provide a summary table for detected hard-drives - where you can usually override some parameters. Try entering BIOS setup (F2, Delete) during boot sequence and look in either Basic Setup/IDE HDD configuration or something along those lines.

    David Max : Laptop BIOS, in my experience, are not so helpful!

E-Mail address widget from Hotmail

When emailing someone from hotmail, the "To" field has a widget where individual email addresses are automatically encapsulated in a the closable box.

What is this widget or control called?

Can I downnload or purchase this control from anywhere?

From stackoverflow

How to implement live video broadcasting in C#?

Hi, I want to plug a live video broadcasting facility to a website. I'm planning to use silverlight and C# but I'm very newbie in this topic.

What is the best way to do this?

Thanks in advance.

Update:

I have a camera. I want it to capture it and show on my website. Live. But I have no idea about what I must do inside. Tell me everything about the capturing, streams, api's, dll's, whatever else I need to know. Thanks.

From stackoverflow
  • Hi, do you have a live stream? Or is that the part you need? If you already have a live stream with a URI, then you could use Silverlight to display it as all you need is a player and a URI (you can get a player anywhere, here's one http://sl2videoplayer.codeplex.com).

    If you don't have the stream, then what you will need is some mechanism to capture video and stream it. You can use Windows Media Server to do the streaming.

    Can you clarify what pieces you have and what you need?

    yapiskan : The only thing I have is just a camera and I don't know the phases to make it live. It will be great, if you could clarify the phases. Because, I don't know exactly what pieces I need. So thanks!
  • If you're on Windows, you may want to consider the free Windows Media Encoder 9 SDK (http://www.microsoft.com/windows/windowsmedia/forpros/encoder/features.aspx). The idea is that Windows Media Encoder allows you to use any device as a media source (say, a video capture card or a streaming-enabled camcorder) and to push it out as an ASF stream, or even to multicast/broadcast it via Windows Media Services.

    The WME SDK is simply a programmatic (COM) interface to WME. In principle you can automate the encoder and instruct it to use your camera as a source, and push it out to a specified UDP port or publishing point (for the latter you'll need Windows Server 2003/2008 with Windows Media Services installed).

    A newer alternative is Microsoft Expression Encoder SDK (http://www.microsoft.com/downloads/details.aspx?FamilyId=9A077A3D-58CE-454C-B486-153F0578BE4A&displaylang=en), which "talks" to Expression Encoder and allows you to stream out to Silverlight clients (among others), but the caveat here is that EE is not free (WME is).

What is a good way to shutdown Threads blocked on NamedPipeServer#WaitForConnection?

I start my application which spawns a number of Threads, each of which creates a NamedPipeServer (.net 3.5 added managed types for Named Pipe IPC) and waits for clients to connect (Blocks). The code functions as intended.

private void StartNamedPipeServer()
  {
    using (NamedPipeServerStream pipeStream =
                    new NamedPipeServerStream(m_sPipeName, PipeDirection.InOut, m_iMaxInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.None))
    {
      m_pipeServers.Add(pipeStream);
      while (!m_bShutdownRequested)
      {
        pipeStream.WaitForConnection();
        Console.WriteLine("Client connection received by {0}", Thread.CurrentThread.Name);
        ....

Now I also need a Shutdown method to bring this process down cleanly. I tried the usual bool flag isShutdownRequested trick. But the pipestream stays blocked on the WaitForConnection() call and the thread doesn't die.

public void Stop()
{
   m_bShutdownRequested = true;
   for (int i = 0; i < m_iMaxInstancesToCreate; i++)
   {
     Thread t = m_serverThreads[i];
     NamedPipeServerStream pipeStream = m_pipeServers[i];
     if (pipeStream != null)
     {
       if (pipeStream.IsConnected)
          pipeStream.Disconnect();
       pipeStream.Close();
       pipeStream.Dispose();
     }

     Console.Write("Shutting down {0} ...", t.Name);
     t.Join();
     Console.WriteLine(" done!");
   }
}

Join never returns.

An option that I didnt try but would possibly work is to call Thread.Abort and eat up the exception. But it doesn't feel right.. Any suggestions

Update 2009-12-22
Sorry for not posting this earlier.. This is what I received as a response from Kim Hamilton (BCL team)

The "right" way to do an interruptible WaitForConnection is to call BeginWaitForConnection, handle the new connection in the callback, and close the pipe stream to stop waiting for connections. If the pipe is closed, EndWaitForConnection will throw ObjectDisposedException which the callback thread can catch, clean up any loose ends, and exit cleanly.

We realize this must be a common question, so someone on my team is planning to blog about this soon.

From stackoverflow
  • You must Close() the pipe, it will interrupt all blocking operations associated with the pipe.

    If you don't have a reference to the pipe, you'll have to redesign your app for signaling that you want to Close() that pipe.

    Gishu : Doesn't work. Disconnect(), Close() and Dispose() all execute successfully but the WaitForConnection call is not unblocked. I've updated question with code for the Stop() method.
    John Leidegren : It should, I have some trouble understanding your program, posting all the code isn't really gonna help with that. But you need to manually close all the pipes. Are you sure you aren't blocked by those Join() calls? The .NET runtime will remain active until all non-background threads exit.
    John Leidegren : For all I know you could be waiting for the current thread to exit, I think you're misusing those Join() calls. They block the calling thread, how are you spawning your threads?
    Gishu : Thread aNewThread = new Thread(new ThreadStart(StartNamedPipeServer)); followed by aNewThread.Start() - I've got thru to someone on the MS team.. will post back with answers/solutions/workarounds..
    John Leidegren : How do you prevent the entry thread (Main thread) from exiting?
  • Switch to the asynchronous version: BeginWaitForConnection.

    If it does ever complete, you'll need a flag so the completion handler can just call EndWaitForConnection absorbing any exceptions and exiting (call End... to ensure any resources are able to be cleaned up).

  • One way that could work is checking for m_bShutdownRequested right after the WaitForConnection.

    During the shutdown process set the bool. After that send dummy messages to all the existing pipes so they open the connection and check the bool and shut down cleanly.

  • This is cheesy, but it is the only method I have gotten to work. Create a 'fake' client and connect to your named pipe to move past the WaitForConnection. Works every time.

    Also, even Thread.Abort() did not fix this issue for me.

  • I have the same problem. Who wrote this API?

    Gishu : we all make some non-optimal choices:) see update in the question for a resolution.

Debug javascript in Eclipse

How can I debug javascript in eclispe. I am using eclipse 3.2.1. Everytime I click on the side it gives option for adding bookmark but no break point. Could youone assist me on this.

From stackoverflow
  • I don't believe Eclipse has a JavaScript debugger - those breakpoints are for Java code (I'm guessing you are editing a JSP file?)

    Use Firebug to debug Javascript code, it's an excellent add-on that all web developers should have in their toolbox.

  • JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.

    However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.

  • I'm not a 100% sure but I think Aptana let's you do that.

    Daniel Lew : I'll have to try Aptana sometime, I keep hearing good things about it, and this just adds to the list.
    Gabe Moothart : +1. Aptana will let you debug javascript in both firefox and (if you pay for the pro version) IE.
  • I tried to get aptana running on my ubuntu 10.4. Unfortunately I didn't succeed. Chrome on the other hand, has an eclipse plugin that lets you debug javascript that's running in a chrome instance. Works very well. YOu'll have to install the eclipse plugin you'll find here:

    http://code.google.com/p/chromedevtools/

    Set Breakpoints in the javascript sources you edit in eclipse and browser your page in chrome. As soon as a javascript breakpoint is hit, the eclipse debugger halts and lets you step into, step over, browse the variables etc. Very nice!

Boost adjacency_list help needed

I'm trying to use Boost's adjacency_list type and I'm having trouble understanding the documentation.

Say I define a class named State and I instantiate one instance for each state in the USA:

class State { ... };
State california, oregon, nevada, arizona, hawaii, ...

I want to enter these into a boost::adjacency_list the vertices are states and the edges are borders. For the states I listed above, I think the graph would have this data:

california : oregon, nevada, arizona
hawaii :
oregon : california, nevada
nevada : oregon, california, arizona
arizona : california, nevada

I understand how to put ints into the graph and I considered just making an array of states and inserting their array index into the graph, but it seems like I should be able to just say:

add_edge(california, oregon, graph);

but of course that doesn't work. Please help!

Edit:
Here's an example of almost exactly what I need.

From stackoverflow
  • Reading up on boost::adjacency_list, it appears you are supposed to use properties for the vertices rather than something like a class:

    struct VertexProperties {
        std::string stateName;
    };
    
    typedef adjacency_list<listS, listS, bidirectionalS, VertexProperties> Graph;
    Graph adjacentStates(50);
    
    property_map<Graph, std::string VertexProperties::*>::type
        stateName = get(&VertexProperties::stateName, adjacentStates);
    
    add_edge(vertex("california", adjacentStates), vertex("oregon", adjacentStates), adjacentStates);
    

    (Poorly) adapted from an example in boost.

    criddell : Oy! It's worse than I thought. I think I'll find a different way to do this. I'd don't want to have to maintain code that... clever. Thanks for the answer.
    BenoƮt : Please add VertexProperties as Graph's 4th template parameter. That means you'll have to add bidirectionalS as 3rd.
    sixlettervariables : Thanks, i've made those changes.

java += question

Why does:

public class Addition { 
public static void main() { 
int a = 0; 
double b = 1.0; 
a = a + b;
System.out.println(a); 
} }

not compile but:

public class Addition { 
public static void main() { 
int a = 0; 
double b = 1.0; 
a  += b; 
System.out.println(a); 
} }

compiles.

From stackoverflow
  • int = int + double is essentially

    int = double + double

    and you cannot do that without casting...

    The int += double forces the result to an int while the other one requires casting.

    So a = (int)(a + b);

    should compile.

    Edit: as requested in the comments... here is a link to more reading (not the easiest read, but the most correct info): http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2

    hhafez : could you provide some link on that for further reading? Thanks
    Johannes Schaub - litb : i think the "deep" reason is because it's disallowed to assign while narrowing: byte = int is disallowed and int = double too. would one do a simple byte a; a += 2; and fail to compile, people would throw shoes at java. but i would still have liked extra rules that make it work without that cast :(
    DefLog : I'm not certain there is a deep reason, but the Java language specification explicitly defines the implicit cast: http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304
  • In Java += operator has an implicit cast to the left hand type. This goes for all composed operators.

    matt b : I think this is a more concise answer
  • double + int returns double, so double = double + int is legitimate, see JLS 5.1.2 Widening Primitive Conversion on the other hand int = double + int is "Narrowing Primitive Conversion" and requires explicit cast

What are Covering Indexes and Covered Queries in SQL Server?

Can you explain the concepts of, and relationship between, Covering Indexes and Covered Queries in Microsoft's SQL Server?

From stackoverflow
  • A covering index is one which can satisfy all requested columns in a query without performing a further lookup into the clustered index.

    There is no such thing as a covering query.

    Have a look at this Simple-Talk article: Using Covering Indexes to Improve Query Performance.

  • A covering query is on where all the predicates can be matched using the indices on the underlying tables.

    This is the first step towards improving the performance of the sql under consideration.

  • A covered query is a query where all the columns in the query's result set are pulled from non-clustered indexes.

    A query is made into a covered query by the judicious arrangement of indexes.

    A covered query is often more performant than a non-covered query in part because non-clustered indexes have more rows per page than clustered indexes or heap indexes, so fewer pages need to be brought into memory in order to satisfy the query. They have more rows per page because only part of the table row is part of the index row.

    A covering index is an index which is used in a covered query. There is no such thing as an index which, in and of itself, is a covering index. An index may be a covering index with respect to query A, while at the same time not being a covering index with respect to query B.

  • Here's an article in devx.com that says:

    Creating a non-clustered index that contains all the columns used in a SQL query, a technique called index covering

    I can only suppose that a covered query is a query that has an index that covers all the columns in its returned recordset. One caveat - the index and query would have to be built as to allow the SQL server to actually infer from the query that the index is useful.

    For example, a join of a table on itself might not benefit from such an index (depending on the intelligence of the SQL query execution planner):

    PersonID ParentID Name
    1        NULL     Abe
    2        NULL     Bob
    3        1        Carl
    4        2        Dave
    

    Let's assume there's an index on PersonID,ParentID,Name - this would be a covering index for a query like:

    SELECT PersonID, ParentID, Name FROM MyTable
    

    But a query like this:

    SELECT PersonID, Name FROM MyTable LEFT JOIN MyTable T ON T.PersonID=MyTable.ParentID
    

    Probably wouldn't benifit so much, even though all of the columns are in the index. Why? Because you're not really telling it that you want to use the triple index of PersonID,ParentID,Name.

    Instead, you're building a condition based on two columns - PersonID and ParentID (which leaves out Name) and then you're asking for all the records, with the columns PersonID, Name. Actually, depending on implementation, the index might help the latter part. But for the first part, you're better off having other indexes.