Search

Fast Restores with Sql Server Snapshots

Friday, 18 December 2015

Using Backup/Restore to reset you data is ok but it can take a while. Snapshots are a much faster alternative. On my system a 20Gb snapshot restores in less than 10 seconds.

What are snapshots
A database snapshot is a readonly view of a database at the time the snapshot was created. The exist as a database on the server – you can find them in ‘Database Snapshots’ in the Sql Managment Studio object explorer. You can use them for reporting but here we are creating them, then restoring them over the main database.

Creating snapshots
Here’s the script to create a snapshot. It doesn’t need much explanation…

If db_id('DemoSnapshot') is Not Null
Begin
    Drop Database DemoSnapshot
End


CREATE DATABASE DemoSnapshot ON ( NAME = DemoDatabase, FILENAME =  'E:\TempBackups\Demo.ss') As Snapshot of DemoDatabase

If your database filename doesn’t match the database name you might get an error that says all files must be specified. In that case you need to pass the file name to the Name parameter.

Restoring snapshots
The script to restore the snapshot is simple as well. It closes existing connections by putting the database into single user mode, restores the snapshot, then puts the database back into multi user mode.

ALTER DATABASE DemoData SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE DemoData From Database_Snapshot = 'DemoSnapshot'
GO

ALTER DATABASE DemoData SET MULTI_USER
GO
 

That’s it, run the restore script whenever you want to put the database back to the saved state.

Quick Fix: Android Emulator is offscreen

Thursday, 16 April 2015

image
I’ve been having an annoying problem when the title bar for my Android emulator is off the top of the screen in Windows so I can’t move it around. I’ve found a couple of fixes…
1 – Hove over the icon on the TaskBar until a preview appears. Right click on the preview and select move. Then you can move the emulator with the cursor keys.
2 – Try using a different skin. I’ve found switching to no skin will bring the emulator back on screen and then I can switch it back to my normal skin with no problems.

An Autohotkey Timer Function

Sunday, 25 January 2015

Here's a handy time function for use with autohotkey, it waits for the specified number of seconds and shows a countdown on the screen.

#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.

TimerSleep(Time)
{
    Countdown := Time

    Loop, %Time%
    {
        SplashTextOn, , 30,Sleeping, %Countdown%  
        Sleep, 1000
        Countdown := Countdown - 1
    }

    SplashTextOff
    return 0
}

Xamarin Android - ViewPager & PageTranformers

Monday, 27 October 2014

This post looks at how to use a ViewPager to let users swipe between fragments and how to make some cool animations during the swipe. The source code for these examples is available here.

ViewPager Basics

To set up a basic view pager we need:
  • A Layout with a ViewPager widget.
  • Some fragments to use as pages.
  • A PagerAdapter which managers the fragments.
  • An Activity to tie everything together.
The layout for the ViewPager is really simple - it just has a ViewPager in it:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
In this example the page fragments are simple as well, the layout is contains a TextView and the fragment class just picks up the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px"
    android:background="@drawable/Fragment">
    <TextView
        android:text="textView1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:textColor="#ff000000" />
</LinearLayout>
public class PagerFragment : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.Inflate(Resource.Layout.DemoFragment, container, false);
        return view;
    }
}
We need a PagerAdapter to manage the fragments, this is simple in the demo but would be more complicated in real life.
internal class DemoPagerAdapter : Android.Support.V13.App.FragmentStatePagerAdapter
{
    private const int PageCount = 5;

    public DemoPagerAdapter(FragmentManager fm) : base(fm)
    {
    }

    public override Fragment GetItem(int position)
    {
        return new PagerFragment();
    }

    public override int Count
    {
        get { return PageCount; }
    }
}
Finally we need an activity to tie it all together. The activity uses the view pager layout and ties it up to the pager adapter.
[Activity(Label = "PagerDemo", Icon = "@drawable/icon")]
public class PagerActivity : Activity
{
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        this.SetContentView(Resource.Layout.PagerActivity);
        
        pagerAdapter = new DemoPagerAdapter(this.FragmentManager);

        viewPager = this.FindViewById(Resource.Id.pager);
        viewPager.Adapter = pagerAdapter;
    }
}
After putting it all together you get an activity which looks like this. This is great but now we'll look at making the transitions between the pagers much cooler.


Animations with Page Transformers

To spice up the animation between the fragments we need a class that implements ViewPager.IPageTransformer. This will let us customise the animation as the pages change in pretty much any way we like. We’ll also need to set the page transformer against the view pager using SetPageTransformer. The interface has a single method called TransformPage which accepts the view from the pages fragment and a float called position. The position variable will change from -1 to 1 as the page changes. -1 is off screen to the right, 1 is off screen to the left, and 0 means that the page is fully in the centre of the screen.

First of all we’ll fade the fragments out as they go off screen, this is what the FadeTransformer class looks like when it’s running:



Here’s the code for the transformer. You can see it calculates the alpha value and then apply it to the view. We also need to set the alpha value to 0 when the view is fully of screen (positions 1 and -1).
/// <summary>
/// This FadeTransformer fades fragments in and out as they are swiped.
/// </summary>
public class FadeTransformer : Java.Lang.Object, ViewPager.IPageTransformer
{
 private float MinAlpha = 0.3f; // Minimum alpha value.

 public void TransformPage(View view, float position)
 {
  if (position < -1 || position > 1) 
  {
   view.Alpha = 0; // The view is offscreen.
  } 
  else 
  {
   float scale = 1 - Math.Abs (position); // The scale should be 1 at position 0, and 0 at positions 1 and -1
   float alpha = MinAlpha + (1 - MinAlpha) * scale; // Calculate the alpha value
   view.Alpha = alpha; // Apply the value to the view

   view.FindViewById<TextView> (Resource.Id.textView1).Text = string.Format ("Position: {0}\r\nAlpha: {1}", position, alpha);
  }
 }
}
Here’s another page transformer - this time we’ll shrink the views as they go offscreen:



And here’s the code. Calculating the scale is fairly simple. We also need to set the views TranslateX property, this keeps the edges of the old and new pages nice and close together:
/// <summary>
/// This ScaleTransformer zooms fragments in and out as they are swiped.
/// </summary>
public class ScaleTransformer : Java.Lang.Object, ViewPager.IPageTransformer
{
 private float MinScale = 0.5f; // Minimum scale value.

 public void TransformPage(View view, float position)
 {
  if (position < -1 || position > 1) 
  {
   view.Alpha = 0; // The view is offscreen.
  } 
  else 
  {
   view.Alpha = 1;

   // Scale the view.
   float scale = 1 - Math.Abs (position) * (1 - MinScale);
   view.ScaleX = scale;
   view.ScaleY = scale;

   // Set the X Translation to keep the views close together.
   float xMargin = view.Width * (1 - scale) / 2;

   if (position < 0) 
   {
    view.TranslationX = xMargin  / 2;
   } 
   else 
   {
    view.TranslationX = -xMargin  / 2;
   }

   view.FindViewById<TextView> (Resource.Id.textView1).Text = string.Format ("Position: {0}\r\nScale: {1}", position, scale);
  }
 }
}
In Android you can apply 3d effects to views easily. Here’s a page transformer that has a 3d ‘wheel’ effect.



Here’s the code, we need to set the pivots for the rotation - the y pivot is half way down the view and the x pivot can be on either edge. The x pivots should be on adjacent edges of the old and new views. The rotation values is calculated by multiplying the position by the maximum rotation value.
internal class WheelPageTransformer : Java.Lang.Object, ViewPager.IPageTransformer
{
    private const float MaxAngle = 30F;

    public void TransformPage(View view, float position)
    {
  if (position < -1 || position > 1) 
  {
   view.Alpha = 0; // The view is offscreen.
  } 
  else 
        {
   view.Alpha = 1; 

   view.PivotY = view.Height / 2; // The Y Pivot is halfway down the view.

   // The X pivots need to be on adjacent sides.
            if (position < 0)
            {
                view.PivotX = view.Width;
            }
            else
            {
                view.PivotX = 0;
            }

            view.RotationY = MaxAngle * position; // Rotate the view.

   view.FindViewById<TextView> (Resource.Id.textView1).Text = string.Format ("Position: {0}\r\nPivotX: {1}\r\nRotationY {2}", position, view.PivotX, view.RotationY);
        }
    }
}
Here’s the final transformer, in this one pages from the right of the screen are treated normally but pages on the left sink into the background.



This transformer is slightly different to the other as the pages are drawn in the opposite order so that the z-indexs are correct. We control this in the call to SetPageTransformer. The other difference is that the transformer only really does anything when the pages are to the left of the screen.
internal class SinkAndSlideTransformer : Java.Lang.Object, ViewPager.IPageTransformer
{
    public void TransformPage(View view, float position)
    {
  if (position < -1 || position > 1) 
  {
   view.Alpha = 0; // The view is offscreen.
  } 
  else 
  {
   view.Alpha = 1;

   if (position < 0) 
   {
    // 'Sink' the view if it's to the left.
    // Scale the view.
    view.ScaleX = 1 - Math.Abs (position);
    view.ScaleY = 1 - Math.Abs (position);

    // Set the translationX to keep the view in the middle.
    view.TranslationX = view.Width * Math.Abs (position);
   } 
  }
    }
}

Android–Bluetooth Barcode Scanners & The Soft Keyboard

Wednesday, 22 October 2014

Bluetooth barcode scanners are a great alternative to barcode apps that use the camera. The only downside is that because they work as bluetooth keyboards they can stop the soft keyboard from appearing. This means you have to turn the scanner off if you want to type anything in. Here’s a way to get the scanner and the soft keyboard working together…
  1. Pair the scanner and to the device.
  2. Go to Settings.
  3. Go to Language & Input.
  4. Under ‘Keyboard & Input Methods’ click on ‘Default’.
  5. Turn ‘Hardware/Physical Keyboard’ Off.
Screenshot_2014-10-22-12-01-02
Now the scanner and the soft keyboard will work together. The downside to this method is that you have to do it each item the scanner is paired with the device. I’m investigating solutions to that so watch this space…

Xamarin Android Listviews - Custom Activity Layout

Monday, 20 October 2014

This post demonstrates how to use a custom activity layout with an Android ListView. The source code for the example is available here.
The previous examples have used the default list activity layout, which is just a full screen list view. Now we’ll use a custom layout to show the list view and a few other controls. The is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="All Players By Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSort" />
<Button
android:text="Just Notts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnJustNotts" />
<Button
android:text="Empty List"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnEmpty" />
<TextView
android:text="Nothing to show!"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/empty"
android:layout_margin="4dp" />
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@android:id/list" />
</LinearLayout>
This is a simple vertical linear layout. There are some buttons at the top which control what is displayed, a text view which is displayed if the list is empty, and the list itself. The list has the id “android:id/list” - this id tells the activity to use the list. The activity will display the element with the id “@android:id/empty” if there are no items in the list. It doesn’t have to be present and it can be used with any layout element.
In the code for the activity we need to use the custom layout in the OnCreate method…
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    this.SetContentView(Resource.Layout.CustomLayout);

    this.FindViewById<Button>(Resource.Id.btnSort).Click += this.btnSort_Click;
    this.FindViewById<Button>(Resource.Id.btnJustNotts).Click += this.btnJustNotts_Click;
    this.FindViewById<Button>(Resource.Id.btnEmpty).Click += this.btnEmpty_Click;

    data = Player.GetPlayers();
    this.ListAdapter = new PlayerAdapter(this, data);
}

Xamarin Android Listviews - Checkboxes On List Items

Friday, 17 October 2014

This post demonstrates how to put check boxes on list items, and how to handle the checkbox change events. The source code for the example is available here.

First of all we need a layout for the list items. This is the one I’ve used:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relativeLayout1"
    android:padding="4dp">
    <TextView
        android:text="txtName"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtName" />
    <TextView
        android:text="txtTeam"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtName"
        android:id="@+id/txtTeam"
        android:layout_alignLeft="@+id/txtName" />
    <CheckBox
        android:text="Captain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtTeam"
        android:id="@+id/chkCaptain"
        android:layout_marginRight="0.0dp" />
</RelativeLayout>

Then we need an adapter, mine looks like this:

private class CheckBoxAdapter : BaseAdapter
{
    private Activity activity;
    private List data;

    public CheckBoxAdapter(Activity activity, List data)
    {
        this.activity = activity;
        this.data = data;
    }

    public override Player this[int position]
    {
        get { return this.data[position]; }
    }

    public override int Count
    {
        get { return this.data.Count(); }
    }

    public override long GetItemId(int position)
    {
        return 0;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = convertView;

        if (view == null)
        {
            view = this.activity.LayoutInflater.Inflate(Resource.Layout.PlayerListItem4, null);
        }

        Player player = this.data[position];

        view.FindViewById(Resource.Id.txtName).Text = player.Name;
        view.FindViewById(Resource.Id.txtTeam).Text = player.Team;

        CheckBox chkCaptain = view.FindViewById(Resource.Id.chkCaptain);
        chkCaptain.Tag = player.Name;

        chkCaptain.SetOnCheckedChangeListener(null);
        chkCaptain.Checked = player.Captain;
        chkCaptain.SetOnCheckedChangeListener(new CheckedChangeListener(this.activity));

        return view;
    }

    private class CheckedChangeListener : Java.Lang.Object, CompoundButton.IOnCheckedChangeListener
    {
        private Activity activity;

        public CheckedChangeListener(Activity activity)
        {
            this.activity = activity;
        }

        public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
        {
            if (isChecked)
            {
                string name = (string)buttonView.Tag;
                string text = string.Format("{0} Checked.", name);
                Toast.MakeText(this.activity, text, ToastLength.Short).Show();
            }
        }
    }
}

Notice how we need to call SetOnCehckedChangeListener(null) before changing the value of the check box. This is because changing the value will also fire the event. If we don’t set the listener to null the change handler is called every time we bind an item to the layout.

The rest of the controller is pretty simple. The CheckedChangeListener shows a toast message whenever the checkbox is checked.