safish.com

home of a small fish

08 February 2012 at 01:19

I'm perpetually restoring databases, and doing it via the GUI using SQL Server Management Studio is tedious. Instead, I like to use a script to restore my database. This involves the creation of a .bat file and an accompanying .sql file, as follows:

The batch file (e.g. restore.bat)

There are three things to note here that you may need to change:

  1. The SQL Server instance
  2. The database name - in my example 'MyDatabase'
  3. The name of the accompanying .sql file (in my example called restore.sql). This assumes the .bat and .sql files are in the same database

sqlcmd -S localhost\SQL2008r2 -i restore.sql -v database=MyDatabase -v root="%CD%"
PAUSE

The sql file (e.g. restore.sql)

There are a few things to note here:

  1. The name of the backup file, in my example MyDatabase.bak - the script assumes this is also in the same folder
  2. The names of the files associated with your database. These may differ on the machine where the database was backed up, to the machine where you are restoring the database to. You can get these names from the original database in Management Studio by right-clicking the database and viewing properties, click Files, and checking the Logical Name column. If you don't know these, just put any old value in and you will receive an error when running the script that should show the correct name. In my example the data file is MyDataFile, and the log file is MyLogFile_log
  3. The user you want to grant db_owner access to. This user must exist as a login on the database instance. In my example, it is called 'myuser'. You may want to change the roles assigned to the user, I am just assigning the db_owner role.

USE MASTER
GO

DROP DATABASE $(database)
GO

RESTORE DATABASE $(database) FROM DISK = '$(root)\MyDatabase.bak'
WITH MOVE 'MyDataFile' TO 'c:\temp\MyDatabase.mdf',
MOVE 'MyLogFile_log' TO 'c:\temp\MyDatabase.ldf'
GO

USE $(database)
GO

sp_grantdbaccess 'myuser'
GO

sp_addrolemember 'db_owner', 'myuser'
GO
06 February 2012 at 12:22
Exporting an SVN repository to an Hg repo is dead easy with the latest version of TortoiseHg:
  1. Open Workbench, and click File...Settings...Extensions
  2. Select the "convert" checkbox and restart work bench
    hg convert extension
  3. From the command prompt, run "hg convert http://<yoursubversionrepo/> <yourdestinationfolder>", and you're done!
03 January 2012 at 13:11
Some useful jQuery plugins:
  • DropKick - superb replacement for standard drop-downs, with in-built graceful degradation
  • FlexSlider - awesome slider plugin for image display
  • Apprise - a nice little replacement for alert/confirmation boxes, although I\'m not sure how well this works across platforms. It doesn\'t look great on IE7/8.
  • Reveal - very nice modal dialog implementation
03 December 2011 at 07:35
This is the start of my own technical blog. I'll be shifting my current tech blog (http://salmontech.blogspot.com) to this location over the next few months, as well as restoring posts from the blog I had before that.
04 October 2004 at 00:00

Caching - File Dependancies

You can output the contents of a file from the cache, and ASP.NET provides the facility to clear the cache whenever the contents of the file change. For example:

  DataSet ds = (DataSet)Cache["MyInfo"];
  if (ds == null) {
    ds = new DataSet();
    ds.ReadXml(MapPath("MyInfo.xml"));
    Cache.Insert("MyInfo", ds, Caching.CacheDependency(MapPath("MyInfo.xml")));
  }
  // do whatever you want with the dataset here...
  DropDownList1.DataSource = ds;  ...

Output Caching

As per the microsoft documentation, pages can be cached on the server with the following:

  <%@ OutputCache Duration="60" VaryByParam="None" Location="Server" %>

This can also be cleared on another page (if someone changes the values to be shown on an item, for example), using the static RemoveOutputCacheItem method.

If you want to clear the output cache for "http://yourserver/webSiteRoot/cachedFile.aspx", then in your page that does the clear call, do the following:

  HttpResponse.RemoveOutputCacheItem("/webSiteRoot/cachedFile.aspx"); 

Output Caching - Clearing using Cache Dependencies

An easier way to remove output caching from multiple pages is to attach a cache dependency on those pages. In the page that is actually cached:

  string cacheKey = "mypage.aspx?" + parameters; 
  Cache[cacheKey] = new object(); 
  Response.AddCacheItemDependency(cacheKey); 

Then, on the page that invalidates the cache (for example, an admin page that inserts/updates database records):

  string cacheKey = "mypage.aspx?" + parameters; 
  Cache.Remove(cacheKey); 
02 October 2001 at 00:00
Threads in Java can be very simple if you just stick to the basics. To run a thread in your class, you should implement the Runnable interface, and then place your thread code into the start(), stop() and run() methods. For example, you want to create a dialog that returns a value to the calling class:
public class myClass extends Dialog implements Runnable {

    private Thread timer;      // class-wide reference to thread object

    // run method from Runnable interface - this method runs until a 
    // specified condition is true - so you would probably want to have 
    // another variable which checks, for example, that the user has clicked 
    // a Cancel or OK button
    public void run() {
        while (this.isVisible()) {
            try {
                // user has not yet closed the window - sleep and loop again
                Thread.currentThread().sleep(500);
            } 
            catch (InterruptedException ie) {
            }
        }
    }

    // method which will return the value - makes the dialog visible, starts 
    // the Thread, and then when the thread dies a result is returned
    public int setVisible() {
        this.show();
        this.start();
        return result;
    }

    // implemented from Runnable interface - initiates a new thread
    public void start() {
        timer = new Thread(this);
        timer.start();
    }
    
    // cleans up objects when the Thread completes
    public void stop() {
        timer = null;
    }

}
Even more simply, if you want to run a single line in your class as a thread, you can do the following (taking away the pain of implementing the Runnable interface):
  public void doStuff() {
    Thread runner = new Thread() {
      public void run() {
         // do thread stuff here
      }
    };
    runner.start();
  }
01 October 2001 at 00:00
To show a standard windows dialog box, you need to import the java.awt.FileDialog class, which can be used to display files on your machine in the following way:
  FileDialog dlg = new FileDialog(this, "What file do you want to save?", FileDialog.SAVE);
  dlg.setFile("*.java");		// file extension filter
  dlg.setDirectory(".");		// initial directory
  dlg.show();
  String saveFile;
  if((saveFile = d.getFile()) != null) {
    filename.setText(saveFile);
    myTextField.setText(d.getDirectory());
  }
Alternatively, if you want to maintain a standard swing look and feel, you can import the javax.swing.JFileChooser class, which can be used in the same way.
  JFileChooser chooser = new JFileChooser(".");
  // chooser.setFileFilter(filter); 
  chooser.setFileHidingEnabled(false);
  int returnVal = chooser.showOpenDialog(parent); 
  if(returnVal == JFileChooser.APPROVE_OPTION) { 
    System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); 
    System.out.println("You chose to open this directory: " + chooser.getCurrentDirectory()); 
  } 
To save files using the swing set, use the following code:
  JFileChooser saver = new JFileChooser(".");
  saver.setFileHidingEnabled(false);
  int returnVal = saver.showSaveDialog(parent); 
  if (returnVal == JFileChooser.APPROVE_OPTION) {
    File selFile = saver.getSelectedFile();
    if (selFile.exists()) {
      int sel = JOptionPane.showConfirmDialog(parent, "Overwrite file " + 
        selFile.getAbsolutePath() + "?", "File exists",
        JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
      if (sel == JOptionPane.NO_OPTION) {
        // do NO overwrite action here
        return;
      }
    }
    // do save action here
  } 
22 August 2001 at 00:00
Opening files from within your application that you do not want to handle within the application itself is really simple using the System.Diagnostics namespace.

Eg: to open the user's default browser to a web site:

  try 
  {
    System.Diagnostics.Process.Start("http://yoursite.com");
  }
  catch (Exception) 
  {
    // error handling
  }

Eg: To open the user's mail client to send mail to someone:

  try 
  {
    System.Diagnostics.Process.Start("mailto: someone@somewhere.com");
  }
  catch (Exception) 
  {
    // error handling
  }

Eg: To open a gif file:

  try 
  {
    System.Diagnostics.Process.Start("C:/YourFile.gif");
  }
  catch (Exception) 
  {
    // error handling
  }
20 August 2001 at 00:00
When coding drag and drop operations in C# Windows applications, you need to complete two steps. Firstly, add a DragOver event to your form in which you change the cursor over your target application so the user can see they will copy the dragged object on the form:
  private void event_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
  {
    e.Effect = DragDropEffects.Copy;
  }

The second step involves handling the actual dropping of the file. This is done by adding a DragDrop event to your form, and retrieving the string array which Windows passes to your application containing the names of all the files dragged and dropped:
  private void event_DragDrop(object sender, DragEventArgs e) 
  {
    // get reference to the dataobject
    DataObject dataObj = (DataObject)e.Data;
    // convert into array of file names
    string[] files = (string[])(dataObj.GetData(DataFormats.FileDrop));
    // loop through each argument, performing the appropriate file opening
    for (int i=0; i
01 August 2001 at 00:00
Abstraction
The process of modelling real-world objects. When you create a class you create an abstraction of a real-world object (like a dictionary definition of that real-world object).

Encapsulation
The property of being a self-contained unit is called encapsulation. With encapsulation, we can accomplish data hiding. Data hiding is the highly valued characteristic that an object can be used without the user knowing or caring how it works internally. Just as you can use a refrigerator without knowing how the compressor works, you can use a well-designed object without knowing about its internal data members.

Inheritance
When an object is derived from another object. It inherits all the properties etc. of the parent object, but can also add to them as needed.

Polymorphism
Different objects do "the right thing" through what is called function polymorphism and class polymorphism. Poly means many, and morph means form. Polymorphism refers to the process whereby an object invokes a method of another object in a common manner (with the same name) without understanding or caring how it is accomplished.