Archive for the ‘Software Development’ Category

Password Protect All but One File (htaccess)

Sunday, July 20th, 2008

Once in a while need to allow someone access to one file but no other files in the same directory. I often solve this problem by moving the one file to a sub directory and then adding the following to an htaccess file in that same sub directory.

allow from all
satisfy any

This normally works well but is not a perfect solution since it is not always appropriate to move the file to a different directory. So, I took the time and figured out how to password protect everything but one file. Below is the basic password protection that I had in the htaccess file that blocked everything in the directory (and sub-directories).

AuthGroupFile /dev/null
AuthName "A Blog"
AuthType Basic
AuthUserFile /path/to/.htpasswd
require valid-user

Now in order to exclude a file I just had to add the following below the above six lines of code.


  Allow from all
  Satisfy any

Of course this can be taken one step further if you wanted to exclude multiple files from password protection.


  Allow from all
  Satisfy any

FilesMatch can take a regular expression so you don't necessarily have to list out each file. The below code will also accomplish the same thing (as above).


  Allow from all
  Satisfy any

Count Lines of Code in C#

Tuesday, December 4th, 2007

When I am programming I often wonder how much code I have actually typed. Sometimes when I get in the zone, have a well thought out design and have auto-completion helping, I can generate code pretty quick. Although there are quite a few programs out there that will count the lines of code some are a bit more intelligent than others.

At the most basic level a simple command in DOS can count the lines of code in a file or directory. But, I often want to a little more than just the the number of lines in each file. I want to know things like the lines of code vs empty lines and the number of lines that contain comments. Fortunately, there is a plug-in for Visual Studio that will do just that. Since, I am normally using Visual Studio to write any program in C# this is a very logical place to have this tool.

C# count lines of code

My next mission will be to find a good line counter for Java. Anyone know of any?

Extra Update Center Module – Netbeans 6 beta 2

Thursday, October 25th, 2007

In the nightly build of netbeans there is a module that can be installed called "Extra Update Center Module". This can be made available in Netbeans 6 beta 2 by going to Tools–>Plugins–>Settings and clicking the "add" button. Then use the following url:

http://deadlock.netbeans.org/hudson/job/javadoc-nbms/lastSuccessfulBuild/artifact/nbbuild/nbms/updates.xml.gz

Click "ok" and you should now have access to the "Extra Update Center Module". Of course the plugins that are provided by this module could be unstable. That is why it is only included with the nightly builds.

Extra Update Center Module

Regular Expression Search and Replace via Command Line (Editplus)

Thursday, December 14th, 2006

Editplus is definitely my favorite text editor but it does not entirely support Regular Expression. Below is an example of when Editplus has failed me:

Editplus-regex

So, I used the regular expression .*<table.*\n.*<tr>\n.*<td>. This unexpectedly returned everything from the beginning of the file down to the <td>. Basically it seems to have a little bit of trouble with multi-line regular expressions.

My solution to this problem was to develop a little regular expression command line program and add it as an Editplus user tool. An added benefit to creating this application is I can now do Regular Expression search and replace via the command line. At the time of creating this application I did not know about Powershell as that would have provided the same functionality. But this little application works so I will stick with it for now.

So, how does the search and replace program work? If you type SearchReplace.exe at the command line you will get the following:

Usage: searchReplace.exe "regular expression" "replacement string" file.txt

Pretty simple ehh?  Note: if you happen to have double quotes in your regular expression they will need to be escaped.

Now to set this up with Editplus just go to Tool —> Preferences —> User Tools and put in the following values:

Command: SearchReplace.exe
Argument: "$(Prompt)" "$(Prompt)" $(FileName)
Initial: $(FileDir)
Check: Run as text filter

When this user tool is run the first pop up box will be where you put the regular expression and the second will be the replacement string.

At this point I have to give a little warning that I have not thoroughly tested this program and I am not liable for any data loss caused by this program. If you happen to encounter any problems let me know. 

Determine File Encoding

Thursday, December 14th, 2006

I ran into a problem where I wasn’t sure if I could trust the encoding that my text editor was displaying. I also wanted to check the encoding on about 10,000 files and determine if it was not a specific encoding. So, I created a little program to tell me the encoding of a file. This in combination with powershell allowed me to loop recursively through all the files in a directory and create a list of the files that were not the correct encoding.

A Good portion of the code that I used for this application was available on the another site that describes how to determine the Encoding of a Unicode file.

The application can be downloaded below:

DOWNLOAD: Determine File Encoding (583 Downloads)

Formatting SQL

Thursday, December 7th, 2006

Today I found a nice little Java tool to help format long SQL queries. It has many options on how the string will be formatted. It will also take sql input types such as:

  • SQL
  • DB2/UDB
  • Oracle
  • MSAccess
  • SQL Server
  • Sybase
  • MYSQL
  • PostgreSQL
  • Informix

It then can take this input SQL and format it into a different type such as:

  • SQL
  • Java StringBuffer
  • Java String
  • C# StringBuilder
  • PHP String
  • ASP StringBuilder
  • VB String
  • VB StringBuilder
  • Concatenated SQL
  • HTML Code

This tool really has a lot of options and is very handy when trying to read/edit a long SQL query.

format sql screenshot

Java to C# Comparison

Wednesday, November 22nd, 2006

The first high-level language that I learned was Java. Of course I shortly found that there was a need to know C# too. So, as I started  to learn C# I kept a list of the differences between C# and Java (as can m be seen below). 
 
Class
--------
    Java: class GMTTime extends Time implements ICloneable{...}
    C#: class GMTTime: Time, ICloneable{...}
Constructor
-----------
    Java: GMTTime(){
              this(System.DateTime.Now);
          }
    C#:GMTTime():this(System.DateTime.Now){...}
       GMTTime(long millis): base(millis){...}//if base not specified default constructor
                                              //called

Java            =       C#
---------------------------
    Finalizer     =       destructors //spedifies code that will execute once an object is no
                                    //longer usable
    Package       =       namespace
    import        =       using
    StringBuffer  =       StringBuilder
   
    indexer: allows a class to be accessed as an array
    struct: lightweight class, value type instead of reference type (like class)

Method Inheritance
-------------------
    class BaseClass{
        //virtual is required  to allow this method to be overridden by a sub class
        virtual long GetTime(){...}
    }

    class childClass: BaseClass {
        //override allows an object to be a base class (BaseClass) but will still use
        //this method
        override long GetTime(){...}
    }

    class childClass2: BaseClass {
        //new overwrites the method but uses the method of the class that the calling
        //object is.
        new long GetTme(){...}
    }

Java Final
----------
    class = sealed //can not be inherited
    method = no virtual
    variable = const or readonly

Accessibility
-------------
    public = visible to all
    protected = only derived classes
    private = only withen given class
    internal = visible only to project/assembly/jar file
    protected internal = visible only to project/assembly/jar file and derived classes
    default = private

Getters/Setters
---------------
    //new C# way...old way used getter and setter methods
    class Circle {
         private int radius;
         public int Radius {
              get {return radius;}
              set {radius = value;}
         }

         public int Area {
              get { return 3.14 * radius * radius; }
         }
    }

    class otherClass{
        Circle c = new Circle();
        c.Radius = 3;//Note: no need to call a setter method.
        int area = c.Area;//Note no need to call a getter method
    }

synchronous = responds immediately
asynchronous = responds when ready to.

How to do events in C#
-----------------------------
1. Manually Trigger Event
    //namespace level, also specifies signature for event/handling methods
    public delegate void MyEventHandler();
2. Create an Event (requires a delegate)
    public event MyEventHandler TriggerIt;//class level
3. Register the event handlers with the event
    obj.TriggerIt += new MyEventHandler(obj.method);
4. Manually Trigger Event
    obj.TriggerIt();

// Declare the delegate handler for the event:
public delegate void MyEventHandler();//determines signitures of handling methods.

class TestEvent{
    // Declare the event implemented by MyEventHandler.
    public event MyEventHandler TriggerIt;

    public void MyMethod1(){
        System.Console.WriteLine("Hello!");
    }
    public void MyMethod2(){
        System.Console.WriteLine("Hello again!");
    }
    public void MyMethod3(){
        System.Console.WriteLine("Good-bye!");
    }

    static void Main(){
        TestEvent myEvent = new TestEvent();

        // Subscribe to the event by associating the handlers with the events:
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod1);
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod2);
        myEvent.TriggerIt += new MyEventHandler(myEvent.MyMethod3);
        // Trigger the event:
        myEvent.TriggerIt();

       
        // Unsuscribe from the the event by removing the handler from the event:
        myEvent.TriggerIt -= new MyEventHandler(myEvent.MyMethod2);
        System.Console.WriteLine("\"Hello again!\" unsubscribed from the event.");
        // Trigger the new event:
        myEvent.TriggerIt();
    }
}

typeof, GetType, is
----------------------
    Type s = typeof(String);
    Type s = "my String".GetType();
    "my string" is String //returns true

Array
-----
    MyArray[column,row]
    int[] arr = new int[]{1,2,3);
    int[] arr = {1,2,3};
    foreach(int i in arr){
        Console.WriteLine("Value is {0}",i);
    }

Force No Cache on a Webpage

Monday, November 6th, 2006

Sometimes it is usefull to force a web page to not be cached. One example where this could be used is on a form that takes credit card information. Once the user submits their data you may not want someone to be able to hit the back button and be able to view the users credit card information. Microsoft has an article explaining how to force the browser to not cache the page but when I tried their method it did not work. Instead with a little trial and error I came up with the following solution:

In ASP (vbscript):
<%
Response.AddHeader "Expires", "Mon, 21 Jul 1979 01:00:00 GMT"
Response.AddHeader "Cache-Control", "no-store, no-cache, must-revalidate" ' HTTP/1.1
Response.AddHeader "Cache-Control", "post-check=0, pre-check=0" ' HTTP/1.1
Response.AddHeader "Pragma", "no-cache" ' HTTP/1.0
%>

In PHP:
header("Expires: Mon, 21 Jul 1979 01:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.1
header("Pragma: no-cache"); // HTTP/1.0

Character Encodings

Wednesday, November 1st, 2006

A text document can be saved with many different types of character encodings. The question is which one is correct? Is there a best encoding for web development or to use in the <meta http-equiv="Content-Type"?

A great guide to understanding the different encodings can be found here.

ftp with 2 connections transfer from remote server to remote server

Tuesday, October 24th, 2006

Every so often I need the ability to transfer files directly from one server to another. Now this could be done by using a standard ftp program like filezilla and first copying it from a remote computer to the local computer and then again copying it back to another remote computer. Although, sometimes it is nice to go the more direct route and use a program that supports fxp which allows connecting to 2 remote servers and transfering directly from one to the other. Wikipedia has a nice list of programs that support this.