Friday, April 29, 2011

Commits and merges on SVN subdirectories considered harmful?

We have several large subprojects inside our main SVN project root.
I commit and merge only my subproject when working with our release branches, mainly because it's faster.

However, a colleague pointed out this reference to merging subdirectories in Version Control with Subversion (a.k.a "The SVN Book"):

Unfortunately, this is the extent of the warning. The linked section does not give an explanation either.

Is committing and merging SVN subdirectories harmful for release branches?
What about short-lived feature branches?

From stackoverflow
  • One possible explanation is that you could forget parts of a change set.

    If the change sets that you are merging cover files that are outside the subdirectory that you have checked out, then there is always the possibility that you will forget to merge those files.

    For example, if you have a commit like this on trunk:

    r5 | rich | 2009-04-16 22:22:46 +0200 (Thu, 16 Apr 2009) | 2 lines
    Changed paths:
       M /trunk/subdir1/main.c
       M /trunk/subdir2/main.c
    
    Change some stuff
    

    And you then have a checkout of subdir1 from your branch "stable", then you could merge the change set r5 like this:

    $ svn co http://example.com/svn/branches/stable/subdir1
    $ cd subdir1
    $ svn merge -c 5 http://example.com/svn/trunk/subdir1 .
    --- Merging r5 into '.':
    U    main.c
    $ svn ci -m"Merged r5 from trunk"
    

    But this will only merge half of revision 5. Worse still, if you go back and look at the log, it will now show this:

    $ svn log -g http://example.com/svn/
    ...
    ------------------------------------------------------------------------
    r5 | rich | 2009-04-16 22:22:46 +0200 (Thu, 16 Apr 2009) | 2 lines
    Changed paths:
       M /trunk/subdir1/main.c
       M /trunk/subdir2/main.c
    Merged via: r6
    
    Change some stuff
    

    So it looks like you've merged the whole commit, when in fact you have only merged some of it. Of course r6 does show that only 1 file has changed on the stable branch.

    ------------------------------------------------------------------------
    r6 | rich | 2009-04-16 22:28:16 +0200 (Thu, 16 Apr 2009) | 1 line
    Changed paths:
       M /branches/stable/subdir2
       M /branches/stable/subdir2/main.c
    
    Merge revision 5 from trunk
    

    Someone has to remember, or notice, that only part of the change set got merged and the rest needs doing. Not using subdirectory merges avoids this problem.

    There are times when you really don't want to merge all of a previous commit, and the above scenario is exactly what you intended to do. In that case, it is probably best to add a good commit message describing your intentions.

    Gary.Ray : +1 - Great answer and example
  • Committing should not have a problem, but in merges SVN tracks what is and is not merged.

    Therefore I assume you want to merge at the root to simplify future merges (in respect to the data set size being compared by SVN).

  • For subversion versions prior to 1.5, merging subdirectories made later merges of the rest of the directory tree really complicated. If you merged a directory, svn simply applied all the changes made in that directory to the other branch. If you had already merged a subdirectory and then tried to merge the main directory, all the changes in the subdirectory were already in the target branch (since you merged them before). Svn now didn't know that these changes were from a previous merge, it just saw that there were things "in the way" when it tried to merge the subdirectory, resulting in lots of conflicts.

    To avoid this you would have had to take care to only merge the directories that you hadn't merged before, making the whole process much more complicated. You had to remember exactly which revisions of which subdirectories you already had merged and only apply the remaining changes of the remaining directories/revisions. This can get confusing. Always merging the whole branch made this much easier. Current versions of subversion keep track of previous merges internally, so that these problems can be avoided.

    Committing subdirectories is no problem. For svn this is just a normal, global revision of the repository. In that revision there will be only changes in one subdirectory, but for svn it's still a new version of the whole repository, just like any other commit.

    rq : In svn 1.5+ this is not actually the case. Merging a subdirectory, then merging the rest of the same commit from the root does not "re-merge" the stuff already merged in the subdirectory causing a conflict. The svn:mergeinfo property prevents that from happening.
    sth : Glad to hear that. It really made subversions merging unnecessarily and annoyingly complex, to the point of uselessness.
  • Another reason for this could be that merging only to the root limits the number of svn:mergeinfo properties that are going to be set on the folders/files in your repository.

    mskfisher : Your answer is more in the spirit of my question, thanks. My gut feel is that since our subprojects are only one level deep, setting mergeinfo on one of those would still be reasonable.

Creating anonymous types based on lambda expression

Hi,

I'm trying to create a Fluent Interface to the Winforms Datagrid. This should allow me to use a typed datasource and easy use of properties of properties (Order.Custom.FullName)

I'm adding the columns on initialization and trying to set the property to use there:

dgv.With<Order>().Column("Client Name").On(x => x.Client.FullName);

The original question then poses itself when setting the Datasource:

dgv.SetTypedDatasource<T>(IList<Order> orders)

A big problem here is that Generic Controls are not possible (I guess), so that T cannot be specified for the class, but has to be specified per method...

I want to create a list of anonymous types, based on a given property in a lambda expression:

something like:

ProcessList<Client>(clientList, x => x.FullName);

Is it possible to do something like this:

[Edit] Note that in practice, the expressions will be set earlier, and will be fetched elsewhere...

public void ProcessList<T>(IList<T> sourceList, Expression<Func<T, object>> expression)
{
    var list =
        (from T x
         in sourceList
         select new { expression })
         .ToList();

    // process list ....  grid.DataSource = list;
}

So, I would like to create anonymous types based on the given expression. I know I can evaluate that expression to retrieve the correct properties.

I'm kinda stuck, is something like this possible?

Any ideas?

From stackoverflow
  • Well, with a simple call to Select you can come very close:

    ProcessList(clientList.Select(x => new { x.FullName }));
    
    ...
    
    public void ProcessList<T>(IEnumerable<T> list)
    {
        // process list ... T will be an anonymous type by now
        grid.DataSource = list;
    }
    

    (That assumes you don't need the original list in ProcessList as well. If you do, move the select into there.)

    Bertvan : so true, I was getting it all wrong...
    Marc Gravell : Note that if that is a winform grid, it will need a ToList() - webform grids are happy with IEnumerable, though.
    Bertvan : Still, not quite what I need, I'll explain a bit more in the question.
    Bertvan : @Marc, yes I forgot that line :)
  • isn't that just grid.DataSource = sourceList.AsQueryable().Select(expression).ToList();

    Note that it would be better to introduce a second generic, such that the list is typed:

        public static void ProcessList<TSource, TValue>(
            IList<TSource> sourceList,
            Func<TSource, TValue> expression)
        {
            grid.DataSource = sourceList.Select(expression).ToList();
        }
    

    Note I switched from Expression<...> to just Func<...>, as it seemed to serve no purpose.

Possible to export FireFox extensions and settings?

Want my FireFox at work to be in sync with my FireFox at my home. Is there a way to simply export all extensions and settings?

From stackoverflow
  • Try MozBackup

  • Just copy the files from your FireFox/Profiles folder to get the settings/saved passwords etc.

    That contains settngs and passwords. I believe you can do a similar process for extensions as well

  • Take a look at Mozilla Weave. An alternative is Foxmarks although I think that's limited to just bookmarks.

  • Since extensions are stored in your profile, you could just make a copy of it to a Flash drive or something.

  • FEBE / CLEO for plugin export/import

filter for many to many field

so I have this model:

class Message(models.Model):
    creator = models.ForeignKey(User, unique=True)
    note = models.CharField(max_length=200, blank=True)
    recipients = models.ManyToManyField(User, related_name="shared_to")
    read = models.ManyToManyField(User, related_name="read", blank=True)

I want to filter on people who are in both recipients and read, currently I'm doing this.

messages = user.shared_to.all()

for message in messages:
    if user not in message.read:
        do something

I'm sure there is a way to filter this but I can't figure out how.

From stackoverflow
  • I think that I originally misread your question. Try the following query.

    for message in user.shared_to.exclude(read__id__in=[user.id]):
      do_something()
    
  • If you use the Django development version, or wait until version 1.1 is released, then your filters can reference other fields in the model. So, your query would look like this:

    >>> Message.objects.filter(reciepients=F('read'))
    

    (Note: I spelled reciepients the same as you had in your model, although the correct spelling would be "recipients")

    Edit:

    Ok, your question is confusing. When I gave the above answer I was reading your statement that you wanted all users who were in both "recipients" and "read"). But then reading your code snippet it looks like you want a list of users who are recipients, but not yet in the "read" list.

    This is probably what you want, but I'm not completely sure because of the vague requirements and I can't quickly test it:

    # Get list of recipients
    shared_to = Message.shared_to.all().values('id')
    
    # Now list of recipients who are not in the read field
    unread = Message.objects.exclude(recipients__in=shared_to)
    

    This will make a single query, but if you are using MySQL it could still be more efficient to do two queries (read the Performance considerations warning).

Odd Bibtex behaviour in a Latex document

I added a line "\cite{test}" as a test to my working Latex document. When I compiled the bibtex "!bibtex name_of_my_file, I got the expected error:

Warning--I didn't find a database entry for "test"

Then, I removed the line and compiled the bibtex again, hoping to have a working Latex file again. However, the same error occurs, even with a fresh shell. I cannot understand the behaviour. What is the logic? How can I get my Latex document working again?

[Updated Info] The problem dissapeared as unexpectedly as it emerged. I have no idea why but it works now. Do you know the reason for the odd behaviour?

From stackoverflow
  • Rerun latex to regenerate the aux file.

    Have a look at this discussion for pointers to a bit more information. Basically, you may have taken your citation out of the .tex file, but it still exists in one of the derived files (aux, bbl, whatever...)

  • I think you are tripping over the multi-pass nature of LaTex plus Bibtex. If you look at Step 3 in this discussion, you'll see the following:

    The first run (through latex) generates an auxiliary file, paper.aux, containing information about citations (and other types of references), the bibliography style used, and the name of the bibtex database. The second run (through bibtex) uses the information in the auxiliary file, along with the data contained in the bibtex database, to create a file paper.bbl. This file contains a thebibliography environment with \bibitem entries formatted according to the bibliography style specified.

    So, what I think is happening is that your name_of_my_file.aux file still contains your placeholder \cite{test}. If you remove the auxiliary file, you should be able to start over with:

    latex name_of_my_file
    bibtex name_of_my_file
    latex name_of_my_file
    latex name_of_my_file
    

    [Update based on additional info]: The problem was that you had a .aux file with your \cite{} still embedded. The second time that you ran latex, you overrode the old file with the new. That's why the complete set of steps includes an initial latex call, a bibtex call and two follow-up latex calls. Think of it as a multi-pass compiler and it might be more intuitive.

    Jouni K. Seppänen : It is even possible to get the aux file into a sufficiently bad state that LaTeX quits before writing a new aux file (this has happened to me), and probably also to a state that is propagated into the new aux file even though the TeX file no longer produces it (this is just speculation and might make a fun research problem). To be sure that your document is reproducible, you need to remove the aux file before the command sequence.
    Bob Cross : Very true - if you're really panicked, the one file that you must keep is name_of_my_file.tex.
    Masi : "The second time that you ran latex, you overrode the old file with the new." I did more than two times. I run the command "!bibtex the_file" at least 50 times, and the command "pdflatex %" about 30 times. It may well be some other reason. Perhaps, it is due to the Mac OS, or something like that. Dunno.
  • You could have a look at latexmk, which will take care of the fix point compilation for you.

    Anyway, you should be able to build the document (pdflatex blah.tex), even if you're missing a bibliography item. The corresponding references will just appear as question marks in the PDF.

actionscript + javascript

Hello all. I'd like to call a javascript function from an embedded .swf file. Specifically, I'd like to call a function in one of my externally linked javascript files from within:

function loadTrack(){



//Radio Mode feature by nosferathoo, more info in: https://sourceforge.net/tracker/index.php?func=detail&aid=1341940&group_id=128363&atid=711474

if (radio_mode && track_index==playlist_size-1) {

 playlist_url=playlist_array[track_index].location;

 for (i=0;i<playlist_mc.track_count;++i) {

  removeMovieClip(playlist_mc.tracks_mc["track_"+i+"_mc"]);

 }

 playlist_mc.track_count=0;

 playlist_size=0;

 track_index=0;

 autoload=true;

 autoplay=true;

 loadPlaylist();

 return(0);

}



start_btn_mc.start_btn._visible = false;

track_display_mc.display_txt.text = playlist_array[track_index].label;

if(track_display_mc.display_txt._width>track_display_mc.mask_mc._width){

 track_display_mc.onEnterFrame = scrollTitle;

}else{

 track_display_mc.onEnterFrame = null;

 track_display_mc.display_txt._x = 0;

}

mysound.loadSound(playlist_array[track_index].location,true);

play_mc.gotoAndStop(2)



//info button

if(playlist_array[track_index].info!=undefined){

 info_mc._visible = true;

 info_mc.info_btn.onPress = function(){

  getURL(playlist_array[track_index].info,"_blank")

 }

 info_mc.info_btn.onRollOver = function(){

  track_display_mc.display_txt.text = info_button_text;

 }

 info_mc.info_btn.onRollOut = function(){

  track_display_mc.display_txt.text = playlist_array[track_index].label;

 }

}else{

 info_mc._visible = false;

}

resizeUI();

_root.onEnterFrame=function(){

 //HACK doesnt need to set the volume at every enterframe

 mysound.setVolume(this.volume_level)

 var load_percent = (mysound.getBytesLoaded()/mysound.getBytesTotal())*100

 track_display_mc.loader_mc.load_bar_mc._xscale = load_percent;

 if(mysound.getBytesLoaded()==mysound.getBytesTotal()){

  //_root.onEnterFrame = null;

 }

}

}

which is in an .as file which I assume somehow becomes the swf file. How would I go about this and 're-compile' the .as file?

From stackoverflow
  •   getURL("javascript:displayPost(" + postId + "," + feedId +")");
    

    From:

    You can also look into the following:

    http://osflash.org/projects/flashjs/tutorials/jstoas

    danwoods : Whoa! Super fast response! I can't test it right now but that looks like it should work. Thanks!
    danwoods : I'm assuming postId and feedId are parameters of displayPost?
  • Also incase anyone in the future is looking at this question the Actionscript 3 version of altCognito's answer is like this:

    ExternalInterface.call("displayPost",postId,feedId);
    
  • Let's compile those answers together for AS2 and AS3 using JS injection AND the ExternalInterface (both ways work in BOTH languages)

    AS2:

    
    // to use javascript injection in a url request
    getURL("javascript:displayPost(" + postId + "," + feedId +");", "_self");
    
    // to use the external interface
    import flash.external.ExternalInterface;
    ExternalInterface.call("displayPost",postId,feedId);
    

    AS3:

    
    // to use javascript injection in a url request
    navigateToURL(new URLRequest("javascript:displayPost(" + postId + "," + feedId +");"), "_self");
    
    // to use the external interface
    import flash.external.ExternalInterface;
    ExternalInterface.call("displayPost",postId,feedId);
    

    Notice that in AS2 and AS3 the ExternalInterface method is the exact same (ExternalInterface was introduced in Flash 8 for AS2). And in AS2 and AS3 the javascript injection method are the same except that it's navigateToURL instead of getURL, and the url string is wrapped in new URLRequest(), because it needs a URLRequest object. Also when using javascript injection, it's a good practice to set the target window to "_self" to avoid a new tab or window from opening.

How to validate compliant XML sitemap?

For the following header I get the same two errors on all my sitemaps. It's confusing because, if Google can't read my sitemap, then how can they say that each URL has the same priority? The header counts as line 2, after the XML declaration. Google claims only to have indexed about 2% of the URLs from the maps. Please help.

UPDATE: I think the problem is that I don't know how to validate against a schema. How to do that?

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

==Parsing error
We were unable to read your Sitemap. It may contain an entry we are 
unable to recognize. Please validate your Sitemap before resubmitting.

==Notice
All the URLs in your Sitemap have the same priority...

UPDATE: Please be patient, first time validating XML. I don't understand the errors.

Errors in the XML document:
    4: 80 SchemaLocation: schemaLocation value = 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd' must have even number of URI's.
    4: 80 cvc-elt.1: Cannot find the declaration of element 'urlset'.

XML document:
1   <?xml version="1.0" encoding="UTF-8"?>
2   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4     xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
5     <url>
6       <loc>http://nutrograph.com/1-butter-salted</loc>
7       <changefreq>monthly</changefreq>
8       <priority>0.8</priority>
9     </url>
10    <url>
11      <loc>http://nutrograph.com/2-butter-whipped-with-salt</loc>
12      <changefreq>monthly</changefreq>
13      <priority>0.8</priority>
14    </url>
15  </urlset>
From stackoverflow
  • It's real hard to diagnose what could be wrong without the sitemap itself. Or did I miss something obvious?

    Jesse : The sitemap is well-formed. I think the header is wrong.
  • Have you validated your XML against the schema given here: http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd

    If yes, what was the result?

    If not, what is the URL of your sitemap?

    If you don't know how to validate the XML against the schema, use http://www.xmlvalidation.com/

    Paste the sitemap-XML there, click on "Validate against external XML schema" and paste the schema after clicking the Validate-button.

    This will tell you what's wrong with your XML. If you don't know how to interpret the result, please amend your original question accordingly.

    Edit: The error was a missing namesapce-URL in the schemaLocation. The first tag has to look like this:

    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    
    Jesse : I'm not sure how to do that..
  • Strike the above. Looking at Googles site, their sitemap header seems to be a little longer than yours.

    It's on this page: https://www.google.com/webmasters/tools/docs/en/protocol.html

    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    
    Jesse : I think the problem is that I don't know how to validate against a schema.
    Jesse : That was the format I tried first. It didn't seem to work. I'll try it again.
  • Nottice that the schemaLocation has 2 URi's... (must have even number of URI's)

    It should look like this: **

    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"

    **

Why won't Silverlight sounds play on some computers?

My Silverlight app successfully plays a repeating alert sound every ten seconds on a number of my own computers. One of my clients hears no sounds. I was just on the phone with him and verified that he could hear basic Windows sounds, sounds from another application, and sounds from another web page (not Silverlight, however) within IE.

Does anyone know of any settings which might affect Silverlight's ability to play sounds on a system which otherwise sounds (ha, ha) fine?

Thanks, Ben

From stackoverflow
  • Maybe he has a problem with his DirectX (or more specifically DirectSound) installation.

Perl script to parse output of cvs log command

Does anyone have a perl script or package that parses the output of a cvs log command and turns it into perl structures for further processing?

From stackoverflow

XML Code Comments in .NET

How much do you use the XML comments in your code files, and how do you use them? I've seen that you can use them to generate XML documentation, but can this XML documentation be used to generate an HTML help file or schema file for your code?

Also, have you used any auto-generating comment tools (i.e. GhostDoc), and what are your impressions?

Thoughts?

From stackoverflow
  • Yes! I use them, and it is a requirement on ALL projects that I do what we include them. As for the level of detail included, it depends on the purpose of the code. At minimum all parameters and public methods will have summary information. Complex items typically have code examples, and all specifically thrown exceptions are documented.

    Right now I am using SandCastle to do the documentation build and you can go to HTML or CHM without any issue at all! I've also used SlickEdit which does an on the fly parsing, and it worked great as well!

  • Yes, I do use this feature and think that it is a good practice for all developers to comment their api's. Once you've done this for a few apis, and as long as you stay on top of it, it's really not too hard to maintain.

    Option 1: SandCastle I tried using this, but I found that there were far too many installers that I had to run and install and learn to configure. In the end, I ended up with a chm file, but really I wanted something a little lighter weight.

    The upside is that the end product looks very professional. It didn't work for my situation though.

    Option 2: NDoc Last time I checked, this project was not being maintained and only worked with version 1.1 of .NET.

    Option 3: XSLT Someone on CodeProject has written a xslt file for this

    http://www.codeproject.com/KB/XML/XMLDocStylesheet.aspx

    I've tried it, and here's how it works. Build your project and drop in the xslt file into the same directory as the outputted xml file. When you double click your xml file, a formatted webpage will displayed instead of the xml document.

    For me, this was the best option.

  • As a minimum I include comments for the public API and generate the xml file. That is enough to make intellisense work, and it also shows up in Reflector.

    Personally, I don't bother with sandcastle etc - but I might for ISV projects.

  • We document all methods and properties with XML comments. Both for internal documentation purposes, and to be able to provide help files for our binaries. It is particularly nice to have the documentation of a method pop up in the intellisense.

    We are using GhostDoc - it can provide an - often OK - default documentation, but keep in mind that GhostDoc can only document what it can infer from the method and parameter names. Therefore, our rule is that you can use GhostDoc to start the documentation; then edit it appropiately - in many cases the default documentation for parameters will be just fine. In simple cases we also just stick with the default documentation, if it makes sense.

    Help files can be generated using Sandcastle (download). Also, the Sandcastle Help File Builder is a GUI that can make it easier for you to get started with Sandcastle.

  • I try to do it for any method that isn't glaringly obvious as to what it does. I like that it includes the documentation in the Intellisense.

  • I've used the SandCastle tool from Microsoft in the past to generate MSDN style documentation from Xml comments and had really good luck. Supposedly it's the tool used to generate all the .net framework docs which also happen to come from Xml comments.

    http://msdn.microsoft.com/en-us/vstudio/bb608422.aspx

  • XML documentation by itself can be useful if you distribute the XML files from the build along with the DLLs. This way, any consumers of the API have useful information available from within the IDE (via Intellisense or the object browser).

    Now perhaps the greatest use of XML comments is the generation of help documentation from these built XML files. Microsoft Sandcastle is the way to go regarding this at the moment. It can produce HTML Help 1 (i.e. CHM) files or HTML Help 2 (i.e. help files that can integrate into Visual Studio Help). (Note: In the past, the option of NDoc may have seemed more appealing - and some people still use it - but Sandcastle seems to be the official and recommended method at this moment, especially given that it's reasonably stable and complete enough for almost any purpose.) See the SandcastleDocs website to get started (this was unofficially put together by one of the developers at Microsoft I believe). In particular, you'll want to check out the Sandcastle Help File Builder GUI - in my experience I've found it to be an excellent tool.

How to build RUNAS /NETONLY functionality into a (C#/.NET/WinForms) program?

Our workstations are not members of the domain our SQL Server is on. (They're not actually on a domain at all - don't ask).

When we use SSMS or anything to connect to the SQL Server, we use RUNAS /NETONLY with DOMAIN\user. Then we type in the password and it launches the program. (RUNAS /NETONLY does not allow you to include the password in the batch file).

So I've got a .NET WinForms app which needs a SQL connection, and the users have to launch it by running a batch file which has the RUNAS /NETONLY command-line and then it launches the EXE.

If the user accidentally launches the EXE directly, it cannot connect to SQL Server.

Right-clicking on the app and using the "Run As..." option doesn't work (presumably because the workstation doesn't really know about the domain).

I'm looking for a way for the application to do the RUNAS /NETONLY functionality internally before it starts anything significant.

Please see this link for a description of how RUNAS /NETONLY works: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982

I'm thinking I'm going to have to use LOGON_NETCREDENTIALS_ONLY with CreateProcessWithLogonW

From stackoverflow
  • I suppose you can't just add a user for the app to sql server and then use sql authentication rather than windows authentication?

    Cade Roux : Nope. And I do actually want users who access this control panel to be themselves. It's like a control dashboard that shows a number of processes and allows users to trigger them, see results, etc.
  • I just did something similar to this using an ImpersonationContext. It's very intuitive to use and has worked perfectly for me.

    To run as a different user, the syntax is:

    using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
    {
        // code that executes under the new context...
    }
    

    Here is the class:

    namespace Tools
    {
        #region Using directives.
        // ----------------------------------------------------------------------
    
        using System;
        using System.Security.Principal;
        using System.Runtime.InteropServices;
        using System.ComponentModel;
    
        // ----------------------------------------------------------------------
        #endregion
    
        /////////////////////////////////////////////////////////////////////////
    
        /// <summary>
        /// Impersonation of a user. Allows to execute code under another
        /// user context.
        /// Please note that the account that instantiates the Impersonator class
        /// needs to have the 'Act as part of operating system' privilege set.
        /// </summary>
        /// <remarks>   
        /// This class is based on the information in the Microsoft knowledge base
        /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158
        /// 
        /// Encapsulate an instance into a using-directive like e.g.:
        /// 
        ///  ...
        ///  using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
        ///  {
        ///   ...
        ///   [code that executes under the new context]
        ///   ...
        ///  }
        ///  ...
        /// 
        /// Please contact the author Uwe Keim (mailto:uwe.keim@zeta-software.de)
        /// for questions regarding this class.
        /// </remarks>
        public class Impersonator :
            IDisposable
        {
            #region Public methods.
            // ------------------------------------------------------------------
    
            /// <summary>
            /// Constructor. Starts the impersonation with the given credentials.
            /// Please note that the account that instantiates the Impersonator class
            /// needs to have the 'Act as part of operating system' privilege set.
            /// </summary>
            /// <param name="userName">The name of the user to act as.</param>
            /// <param name="domainName">The domain name of the user to act as.</param>
            /// <param name="password">The password of the user to act as.</param>
            public Impersonator(
                string userName,
                string domainName,
                string password)
            {
                ImpersonateValidUser(userName, domainName, password);
            }
    
            // ------------------------------------------------------------------
            #endregion
    
            #region IDisposable member.
            // ------------------------------------------------------------------
    
            public void Dispose()
            {
                UndoImpersonation();
            }
    
            // ------------------------------------------------------------------
            #endregion
    
            #region P/Invoke.
            // ------------------------------------------------------------------
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern int LogonUser(
                string lpszUserName,
                string lpszDomain,
                string lpszPassword,
                int dwLogonType,
                int dwLogonProvider,
                ref IntPtr phToken);
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern int DuplicateToken(
                IntPtr hToken,
                int impersonationLevel,
                ref IntPtr hNewToken);
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern bool RevertToSelf();
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            private static extern bool CloseHandle(
                IntPtr handle);
    
            private const int LOGON32_LOGON_INTERACTIVE = 2;
            private const int LOGON32_PROVIDER_DEFAULT = 0;
    
            // ------------------------------------------------------------------
            #endregion
    
            #region Private member.
            // ------------------------------------------------------------------
    
            /// <summary>
            /// Does the actual impersonation.
            /// </summary>
            /// <param name="userName">The name of the user to act as.</param>
            /// <param name="domainName">The domain name of the user to act as.</param>
            /// <param name="password">The password of the user to act as.</param>
            private void ImpersonateValidUser(
                string userName,
                string domain,
                string password)
            {
                WindowsIdentity tempWindowsIdentity = null;
                IntPtr token = IntPtr.Zero;
                IntPtr tokenDuplicate = IntPtr.Zero;
    
                try
                {
                    if (RevertToSelf())
                    {
                        if (LogonUser(
                            userName,
                            domain,
                            password,
                            LOGON32_LOGON_INTERACTIVE,
                            LOGON32_PROVIDER_DEFAULT,
                            ref token) != 0)
                        {
                            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                            {
                                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                                impersonationContext = tempWindowsIdentity.Impersonate();
                            }
                            else
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    if (token != IntPtr.Zero)
                    {
                        CloseHandle(token);
                    }
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        CloseHandle(tokenDuplicate);
                    }
                }
            }
    
            /// <summary>
            /// Reverts the impersonation.
            /// </summary>
            private void UndoImpersonation()
            {
                if (impersonationContext != null)
                {
                    impersonationContext.Undo();
                }
            }
    
            private WindowsImpersonationContext impersonationContext = null;
    
            // ------------------------------------------------------------------
            #endregion
        }
    
        /////////////////////////////////////////////////////////////////////////
    }
    
    DJ : I have used similar code in a custom installer - however the 'Act as part of operating system' right is very powerful and I got a lot of pushback from system admins in granting this to average users. YMMV of course
    Cade Roux : Well this code is only good for logging on locally - for remote access credentials (basically for just the SQL connection) you have to use the equivalent of the /NETONLY flag, I'm trying to nail it down right now.
    Cade Roux : This link kind of illustrates the difference: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982 - I might need to create a new process.
    Jonathan : A different logon type and provider may help: http://blogs.catalystss.com/blogs/jonathan_rupp/archive/2008/02/26/sometimes-impersonation-isn-t-enough.aspx. In original scenario, the local machine was part of the same domain, so that solution may not work here.
    John Rasch : @Jonathan - Great point, I was using this to pull event log data from remote machines on the same domain
  • This code is part of an RunAs class that we use to launch an external process with elevated privleges. Passing null for username & password will prompt with the standard UAC warnings. When passing a value for the username and password you can actually launch the application elevated without the UAC prompt.

    public static Process Elevated( string process, string args, string username, string password, string workingDirectory )
    {
        if( process == null || process.Length == 0 ) throw new ArgumentNullException( "process" );
    
        process = Path.GetFullPath( process );
        string domain = null;
        if( username != null )
            username = GetUsername( username, out domain );
        ProcessStartInfo info = new ProcessStartInfo();
        info.UseShellExecute = false;
        info.Arguments = args;
        info.WorkingDirectory = workingDirectory ?? Path.GetDirectoryName( process );
        info.FileName = process;
        info.Verb = "runas";
        info.UserName = username;
        info.Domain = domain;
        info.LoadUserProfile = true;
        if( password != null )
        {
            SecureString ss = new SecureString();
            foreach( char c in password )
                ss.AppendChar( c );
            info.Password = ss;
        }
    
        return Process.Start( info );
    }
    
    private static string GetUsername( string username, out string domain ) 
    {
        SplitUserName( username, out username, out domain );
    
        if( domain == null && username.IndexOf( '@' ) < 0 )
         domain = Environment.GetEnvironmentVariable( "USERDOMAIN" );
        return username;
    }
    
    Cade Roux : The ProcessStartInfo (and therefore the Process.Start method) doesn't have any equivalent settings to RUNAS /NETONLY, where the network credentials are used only for the network connection, not for the local thread/process permissions.
    Paul Alexander : Bummer...you may have to resort to PInvoke and CreateProcess.
  • I gathered these useful links:

    http://www.developmentnow.com/g/36_2006_3_0_0_725350/Need-help-with-impersonation-please-.htm

    http://blrchen.spaces.live.com/blog/cns!572204F8C4F8A77A!251.entry

    http://geekswithblogs.net/khanna/archive/2005/02/09/22430.aspx

    http://msmvps.com/blogs/martinzugec/archive/2008/06/03/use-runas-from-non-domain-computer.aspx

    It turns out I'm going to have to use LOGON_NETCREDENTIALS_ONLY with CreateProcessWithLogonW. I'm going to see if I can have the program detect if it has been launched that way and if not, gather the domain credentials and launch itself. That way there will only be one self-managing EXE.

JPanel Margin in BoxLayout

For custom rendering purposes, I've created a class (axialPanel.java) that extends JPanel and overrides the paintComponent method. An instance of axialpanel is added to the west side of a container class set with a BorderLayout. I would like to have a few pixels of margin around the axialpanel, but setting axialpanel's border to an instance of EmptyBorder with some moderate size doesn't appear to work. Any thoughts on how I might accomplish this?

Thanks in advance.

From stackoverflow
  • Your paintComponent method should honour the component's insets.

    An easy way not to bother with that is to next your painted component inside a panel that has a border and your component as center of a BorderLayout.

    (BTW: IMO it's a bad idea to extend JPanel when you don't want a panel. Just extend JComponent. There is a difference in layout and also a JPanel may or may not default to being opaque depending upon which version of which PL&F is in use (so you always need to call setOpaque unless you feel lucky).

GridView doesn't report an exception

Hello,

If I bind GridView to SqlDataSource and also set AutoGenerateEditButton to true, and if I then try to update a field ( this field being a primary key in database ), then database should return an error and thus SqlException should be thrown?!

So why doesn’t page report an exception? Instead, all Gridview does is setting all fields in that row back to their original values.


When I executed same update statement with the following code, I got Cannot update identity column 'EmployeeID' exception, so I’m assuming Sql Server did report same error when GridView tried to update, but for some reason exception wasn't raised:

        SqlConnection sc = new SqlConnection();
        sc.ConnectionString = @"Data source=localhost; integrated security=sspi; initial catalog=northwind;";
        SqlCommand sComand = new SqlCommand();

        sComand.Connection = sc;
        sComand.CommandText = "update Employees set EmployeeId=100,FirstName='Suzy',"+ 
                   "LastName='Smile',City='Moon' where EmployeeId=1";
        sc.Open();
        int I = sComand.ExecuteNonQuery();


BTW - I tried with setting DataKeyNames="EmployeeId", but exception was still not raised

thanx

EDIT:
Hello,

Sorry for not replying sooner, but I haven't noticed I got a reply.

Anyways, for some reason it's working now, meaning GridView does report an exception. Thus I must've made some mistake in my code, but due to constant rewriting of my code I have no idea where would that mistake be. Sorry for wasting your time and thank you for helping me out


From stackoverflow
  • Looking at the error and your code. It appears to be a SQL Database Error and not an issue with the GridView.

    SQL does not allow updates to IDENTITY columns since they get generated by the database engine. In this case "EmployeeId" is such a field.

    Meff : I came here to say this..+1
    SourceC : But why did above code, which executed the same update statement as GridView, report an SqlException, but Gridview didn't?
    Jose Basilio : It appears that the GridView control swallows the Exception unless you set the property-> EnableModelValidation="true"
  • I the same kind of problem: I caught the exception in the object datasource's Selecting handler, but forgot to set the exception as handled: e.ExceptionHandled = true. The page rendered without my error message on the page, like if no error happened. With e.ExceptionHandled = true, everything was fine.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Here's the problem. I have an image:

<img alt="alttext" src="filename.jpg"/>

Note no height or width specified.

On certain pages I want to only show a thumbnail. I can't alter the html, so I use the following CSS:

.blog_list div.postbody img { width:75px; }

Which (in most browsers) makes a page of uniformly wide thumbnails, all with preserved aspect ratios.

In IE6 though, the image is only scaled in the dimension specified in the CSS. It retains the 'natural' height.

Here's an example of a pair of pages that illustrate the problem:

I'd be very grateful for all suggestions, but would like to point out that (due to the limitations of the clients chosen platform) I'm looking for something that doesn't involve modifying the html. CSS would also be preferable to javascript.

EDIT: Should mention that the images are of different sizes and aspect ratios.

From stackoverflow
  • Well, I can think of a CSS hack that will resolve this issue.

    You could add the following line in your CSS file:

    * html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; }
    

    The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

  • The only way to do explicit scaling in CSS is to use tricks such as found here.

    IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.

    If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).

    Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto after your width: 75px rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.

    I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).

    Good luck!

  • Adam Luter gave me the idea for this, but it actually turned out to be really simple:

    img {
      width:  75px;
      height: auto;
    }
    

    IE6 now scales the image fine and this seems to be what all the other browsers use by default.

    Thanks for both the answers though!

    mager : Awesome! This fixed a bug for me.
    kalengi : worked brilliantly for me! great find :)
  • I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

    I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

    1. The image aspect ratio is preserved
    2. The image's original size is maintained (that is, it can never shrink only grow)

    The markup relies on a wrapper element:

    <div id="wrap"><img src="test.png" /></div>
    

    Given the above markup you then use these rules:

    #wrap {
      height: 100px;
      width: 100px;
    }
    #wrap img {
      min-height: 100%;
      min-width: 100%;
    }
    

    If you then control the size of wrapper you get the interesting scale effects that I list above.

    To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

    1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
    2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

    So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

    This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

Writing Software technical documentation

What is the best resource where I can get samples of software life cycle documentation such as User Requirement Specification, etc?

From stackoverflow

Easy way to remove warning messages after converting vb6 project to VB.NET

I have converted a VB6 project to VB.NET and am left with a large number of inline 'warning messages' such as "UPGRADE_WARNING: Couldn't resolve default property of object varJonSkeet" that I would like to get rid of. Is there a way to do this within Visual Studio 2008? Will it be easier to remove the warning messages with regex? I would prefer to do the removals one file at a time, but it isn't a dealbreaker.

From stackoverflow
  • Rewrite the project in VB.NET. Getting rid of the warnings might is only a means to get to the goal which (i presume) is a working program.

  • The best way to get rid of warnings is to address the suspicious code that the warnings complain about. That is, change the code such that it is no longer warning-worthy. Don't just seek to disable the generation of warnings altogether.

    You'll need to provide more details about the specific warnings you're concerned about, and the accompanying code. But remember to search previous answers here first.


    I see the warnings are actually text literally in your code, not messages issued in the compiler output. The way to get rid of those is to search for the keyword (UPGRADE_WARNING, I guess), consider whether the issue that it warns about has been addressed or is still a valid concern, fix the problem if there is one, and the delete that warning line. For example, does varJonSkeet have a default property, and if not, does it need one? Should you use to a non-default property instead? (You're not really asking how to delete a line of text, are you?)

    If you've already gone through the whole file and determined that none of the warnings are valid, there's a quick way of removing all the warning lines.

    grep -v UPGRADE_WARNING input_file.vb > output_file.vb
    ren output_file.vb input_file.vb
    

    If you don't already have grep on your system, then you don't have a complete development environment yet. Go get a copy. The -v option tells it to invert the search results, thus printing all lines that don't contain the search pattern. Those get written into the new file. Then replace the old file with the new one.

    The Talking Walnut : I have clarified my question. I am fixing what originally caused the warnings, but that doesn't remove the comments that are added from the code.
  • I believe he is saying that he wants to remove the inline comments from his code.

    Fastest way is to perform a find in files for UPGRADE_WARNING: and remove them by hand.

    Or,

    You could create a new .Net program to iterate through each .vb file in your source directory and read them in using a StreamReader and then write them out 1 line at a time to the same file and as you go omit any lines containing UPGRADE_WARNING:.

    If you do the second way you will be that much better for having done some more vb.net coding.

    
       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim FileName As String = "c:\form1.vb"
            Dim SourceFile As System.IO.FileInfo = New FileInfo(FileName)
            Dim SourceTextStream As System.IO.TextReader = SourceFile.OpenText()
    
            Dim SourceFileContent() As String = Split(SourceTextStream.ReadToEnd(), vbCrLf)
            SourceTextStream.Close()
    
            Dim CurrentSourceLine As String
            Dim CurrentSourceLineNumber As Long
    
            Dim DestStream As StreamWriter = New StreamWriter(FileName)
            Dim LogStream As StreamWriter = New StreamWriter(FileName + ".log")
    
            For Each CurrentSourceLine In SourceFileContent
                CurrentSourceLineNumber += 1
                If InStr(CurrentSourceLine, "UPGRADE_WARNING") = 0 Then
                    DestStream.WriteLine(CurrentSourceLine)
                Else
                    ' Write to Log File
                    LogStream.WriteLine("Line Skipped at number: " + CurrentSourceLineNumber.ToString())
                End If
            Next
    
            DestStream.Close()
            LogStream.Close()
    
    
    
    
        End Sub
    
    The Talking Walnut : I think I was looking for too complex of a solution. Searching with wildcards worked great. When doing the replace, is there a way to delete the line instead of replacing it with a blank line?

Excel Reference To Current Cell

How do I obtain a reference to the current cell?

For example, if I want to display the width of column A, I could use the following:

=CELL("width", A2)

However, I want the formula to be something like this:

=CELL("width", THIS_CELL)
From stackoverflow
  • A2 is already a relative reference and will change when you move the cell or copy the formula.

    GSerg : Don't worry about addressing style. All formulas use R1C1 internally anyway, it doesn't matter.
    Joey : Ah, thanks. Didn't bother to look it up right now (wading through the XML isn't exactly fun usually :))
  • You could use

    =CELL("width", INDIRECT(ADDRESS(ROW(), COLUMN())))
    

    but Johannes's answer will work just as well

    GSerg : This makes the formula volatile. Therefore, provided there are non-volatile solutions, don't use this one.
  • Leave off the second argument entirely, it is an optional argument. When you omit it, the function uses the host cell as the reference.

    =CELL("width")

VS2008: Breakpoints window gone while debugging?

This is probably silly but very frustrating.
Using VS2008 with a C++ project, when I'm working normally, the breakpoints window is visible and active but when I'm debugging it disappears and can't be shown. This is a problem if I want to edit the condition of a breakpoint while running. Pressing the breakpoints window button doesn't do anything and neither does pressing Ctrl+Alt+B

Does this happen to anybody else? It's a brand new install with Visual Assist and QT integration as extensions. same configuration with VS2005 doesn't have any problems.

From stackoverflow
  • You may try to reset Visual Studio Layouts by launching Visual Studio with the following command line:

    devenv.exe /resetuserdata
    

    More info here on MSDN

    shoosh : This will also reset every other settings I have what-so-ever...
  • There is a menu item Window->Reset Window Layout.

    Stefan Steinegger : Did you try it in debug mode, when you miss the window? There are different window settings for debugging and "normal" mode.
  • The solution was to export the settings using "Tools->Import and Export Settings" Then, using the same wizard, to reset the settings to the default and then when re-importing the saved settings file uncheck the "Windows Layout" item in the import list.
    This allowed me to save all the my previous settings and reset only the windows layout and not the breakpoints window is finally visible.

  • [Debug] -> [Windows] -> [Breakpoints]

    shoosh : Did you even bother reading the question?