Saturday, February 19, 2011

CSS cleaner

I've taken over looking after a fairly complex site developed by another company, and frankly it's a mess. One of my problems is that there seems to have been no discipline when writing the html so that although they have used css extensively, there are half a dozen css files and a cursory analysis reveals that there is a significant number of styles in the css files that are not referenced by any of the html - rather they contain trail of false redesign starts and old, now redundant, styles mixed in with the current items.

I'd really like to clean all this up before moving onwards. Does there exists any tool, open source or otherwise, that can take a bunch of html and css files and cross reference them so as to highlight the cruft in the css?

From stackoverflow

Curl post data and headers only

I want to get the headers only from a curl request

curl -I www.google.com

All grand. Now I want to do that but to pass in post data too:

curl -I -d'test=test' www.google.com

But all I get is:

Warning: You can only select one HTTP request!

Anyone have any idea how to do this or am I doing something stupid?

From stackoverflow
  • -d means you are sending form data, via the POST method. -I means you are just peeking at the metadata via HEAD.

    I'd suggest either

    • Download to /dev/null and write the headers via the -D headerfile to the file headerfile
    • Use -i to include the headers in the answers and skip everything from the first empty line.
    J.D. Fitz.Gerald : Cheers, makes sense
    Bryan Ross : Old, I know, but I would suggest adding `-s` to clean up the output a little bit.
  • curl -s -d'test=test' -D- www.google.com -o/dev/null

    That is the neatest way to do this as far as I can find.

What is the best way to password protect folder/page using php without a db or username

What is the best way to password protect folder using php without a database or user name but using. Basically I have a page that will list contacts for organization and need to password protect that folder without having account for every user . Just one password that gets changes every so often and distributed to the group. I understand that it is not very secure but never the less I would like to know how to do this. In the best way.

It would be nice if the password is remembered for a while once user entered it correctly.

From stackoverflow
  • Assuming you're on Apache:

    http://httpd.apache.org/docs/1.3/howto/htaccess.html#auth

    Salt Packets : I would like to do this with php. Yes I know how to do it with .htaccess
  • Well since you know it's insecure to begin with, you could store a password in a text file somewhere on your web server. When someone accesses the page you could show a form that asks for a password. If the password matches what is in the text file, then you reload the page and display the information. Using the text file will allow you to change the password without having to modify the page they are accessing when you want to change it. You're still going to be sending plaintext everywhere unless you're using SSL. Let me know if you need some code.

  • I doubt if this would count as the best wasy of doing it, but it would work. And since security doesn't seem to be a big issue for you, the fact that this way's as insecure as hell probably won't bother you either.

    Have a login.php page that takes a password and then sets a cookie if the login details are correct. Each php file can then check for the existence of the cookie to determine whether or not the user is "logged in" or not, and display information accordingly.

    login.php
    ...
    if(isset($_POST['password']) && $_POST['password'] == 'my_top_secret_word') {
        setcookie('loggedin', 'true', time() + 1200, '/url/');
    } else {
        setcookie('loggedin', 'false', time() - 1200, '/url/');
        // display a login form here
    }
    etc
    

    each "protected" page would then check for this cookie:

    if(isset($_COOKIE['loggedin'])) {
        if($_COOKIE['loggedin'] == 'true') {
            $showHidden = true;
        } else {
            $showHidden = false;
        }
    } else {
        $showHidden = false;
    }
    

    I'm sure you get the (highly insecure) idea ...

  • You could quickly throw together a script like this, e.g. access.php.

    <?php
    //put sha1() encrypted password here - example is 'hello'
    $password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';
    
    session_start();
    if (!isset($_SESSION['loggedIn'])) {
        $_SESSION['loggedIn'] = false;
    }
    
    if (isset($_POST['password'])) {
        if (sha1($_POST['password']) == $password) {
            $_SESSION['loggedIn'] = true;
        } else {
            die ('Incorrect password');
        }
    } 
    
    if (!$_SESSION['loggedIn']): ?>
    
    <html><head><title>Login</title></head>
      <body>
        <p>You need to login</p>
        <form method="post">
          Password: <input type="password" name="password"> <br />
          <input type="submit" name="submit" value="Login">
        </form>
      </body>
    </html>
    
    <?php
    exit();
    endif;
    ?>
    

    Then on each file you want to protect, put at the top:

    <?php
    require('access.php');
    ?>
    secret text
    

    It isn't a very nice solution, but it might do what you want

    Edit

    You could add a logout.php page like:

    <?php
        session_start();
        $_SESSION['loggedIn'] = false;
    ?>
    You have logged out
    
    Abyss Knight : +1 For using a hashing algorithm to precalcuate and store. Though, SHA2 or at least SHA1 would be more secure.
    rodey : I don't know how much security the OP cares about.
  • I am doing approximately what David Heggie suggested, except without cookies. It does seem insecure as hell, but it is probably better having a bad password protection then none at all.

    This is for internal site where people would have hell of a time remembering their login and password and would never go through sign up process... unless it is really easy they would not use the system at all.

    I wanted to see other solutions to this problem.

    With user base consisting of not very tech savvy people what are other ways to do this.

    Abyss Knight : If it is for an intranet application you could use Windows Authentication or another single sign on system. At least, that's what we do here. Of course, our userbase is enormous so YMMV.
    Salt Packets : It is not on a windows system and people will access it through internet. It is all sorts of bad.
    rodey : Looks like tomhaigh has exactly what you're looking for.
  • If you want to avoid cookies, sessions and don't want to play with .htaccess files, you can also do http authentication soley with PHP:

    http://www.php.net/manual/en/features.http-auth.php

    You can hard code the password into the file and change it as needed, or include it from a file not in your web_accessible directory.

    The downside is you don't have the ability to format the "login" screen - it will be a standard http authentication dialog box

  • Well since you know it's insecure to begin with, you could store a password in a text file somewhere on your web server. When someone accesses the page you could show a form that asks for a password. If the password matches what is in the text file, then you reload the page and display the information. Using the text file will allow you to change the password without having to modify the page they are accessing when you want to change it. You're still going to be sending plaintext everywhere unless you're using SSL. Let me know if you need some code.

    THAT'S INSANE! The most unsecure idea ever.

Getting values between quotes

How can I get the value between quotes with an RegEx

for example I want to find all the parameters from the function test

<html>
   test("bla");
   print("foo");
   test("moo");
</html>

The result must be { "bla", "moo" }

From stackoverflow
  • edit: Removed old code and made a linq version...

        var array = (from Match m in Regex.Matches(inText, "\"\\w+?\"")
                     select m.Groups[0].Value).ToArray();
    
        string json = string.Format("{{{0}}}", string.Join(",", array));
    
  • If you just want the args to test, you'll need to include that in the regex:

        StringBuilder sb = new StringBuilder("{");
        bool first = true;
        foreach (Match match in Regex.Matches(html, @"test\((""[^\""]*\"")\)"))
        {
            if(first) {first = false;}
            else {sb.Append(',');}
            sb.Append(match.Groups[1].Value);
        }
        sb.Append('}');
        Console.WriteLine(sb);
    

    From the question, I am using quote detection here.

    Alternatively - if you just want the values:

        foreach (Match match in Regex.Matches(html, @"test\(""([^\""]*)\""\)"))
        {
            Console.WriteLine(match.Groups[1].Value);
        }
    

    The main change here is that the group is now inside the quotes.

How do I do a SVN Update from ASP.NET?

I'd like to call svn up from an asp.net page so people can hit the page to update a repository. (BTW: I'm using Beanstalk.com svn hosting which doesn't allow post-commit hooks, which is why I am doing it this way).

See what I've got below. The process starts (it shows up in Processes in Task Manager) and exits after several seconds with no output message (at least none is outputted to the page). The repository does not get updated. But it does do something with the repository because the next time I try to manually update it from the command line it says the repo is locked. I have to run svn cleanup to get it to update.

Ideas?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    startInfo = New System.Diagnostics.ProcessStartInfo("svn")
    startInfo.RedirectStandardOutput = True     
    startInfo.UseShellExecute = False
    startInfo.Arguments = "up " & Request.QueryString("path")

    pStart.StartInfo = startInfo
    pStart.Start()
    pStart.WaitForExit()

    Response.Write(pStart.StandardOutput.ReadToEnd())
End Sub
From stackoverflow
  • Does it write to stderr?

  • Chris -- Thanks for the reply. I added

    Response.Write(pStart.StandardError.ReadToEnd())
    

    And nothing writes to screen. Is that what you were asking?

  • You might be able to do this more effectively by using a .net SVN wrapper or library like this one. I'm sure there are others out there that would support the limitations of beanstalk as well.

  • Using SharpSvn:

    using(SvnClient client = new SvnClient())
    {
       client.Update(Request["path"]);
    }
    

    But I would recommend not to use a user passed variable directly for security reasons.

  • You can also use the Subversion library that comes with Ankh SVN. I used it in a project to manage files in a Subversion repository and it worked well.

    If you insist on using the command line client make sure you check the StandardError output for any error messages. Also make sure the user you run the process as has the appropriate rights.

How to test User Control with unit that relies on the Session object

I'm using ASP.NET to build an application and the latest version of NUNIT framework to test it. I'm constructing a User Control to build a custom menu. That control at some point checks whehter a specific object exists in the Session Collection or not to add some elements to the menu.

The exact functionality it provides is this: if the registered user is a regular user display the regular set of links, if the registered user is a administrator add extra links to the already displayed links. The control works as expected.

My problem:
I want to take the control outside the web application, and test it separately inside the NUNIT testing framework. My only concern is that it relies on the existence of the Session object. I don't know how to simulate it inside a nunit test method, if its possible or are there alternative solutions I haven't thought of.

From stackoverflow
  • You will need stroke the framework in the right direction but you can do this by mocking the http context.

    I tend to wrap operations like these in a custom class I can more easily mock.

    As an alternative you can probably use mstest's web tests to achieve the same results.

    Cristian Libardo : It's the test framework included in visual studio 2008. It's similar to NUnit, but different =)
    Nikola Stjelja : Thank you for your answer

Html.BuildUrlFromExpression with reference type parameters for action

I hope my terminology is right. Edit if not.

From my Linq2Sql classes I have a Color class. One of my controller's actions accepts an instance of this Color class.

I want to create a link to this action so I use

<%=Html.ActionLink<ColorController>(c=>c.Details(ViewData.Model.ActiveColor), "test")%>

Where ViewData.Model.ActiveColor is off course the aforementioned instance of Color.
This renders as follows:

/Color/Details?color=- Not exactly what I had in mind off course..

What am I doing wrong? Should I start creating custom ModelBinders?

EDIT
I have found where the "-" came from. Apparantly the ActionLink is calling upon ToString. This is rather weird since I see tostring more of way to display something then to identify something (isn't that what GetHash is for?). Even after implementing the Iserailizable interface on my object, it's still using the ToString method. Can I define somewhere how to serialize my class rather then using the ToString()? I'm feeling like I'm completely on the wrong track.

From stackoverflow
  • Actionlink is indeed calling upon ToString(). I ran into the same problem using dates. In my urls I wanted dates to be dd-mm-yyyy instead of the default DateTime.ToString().

    First option is to override your Color's ToString() method. If that isn't possible (as with DateTime) there are other ways, but they're a bit "hacky"...