Friday, 19 November 2010

WPF data storage without a database

In some smaller programs its not always beneficial to supply a sql database especially if you are only using one or two sets of information i.e. contacts and addresses.

First create a class for a set of information, in this case I have setup a Contact class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example.Model
{
    [Serializable]
    public class Contact : Notifier
    {
        private Guid _id = Guid.Empty;
        private string _firstNames;
        private string _surname;
        private string _homePhone;
        private string _workPhone;
        private string _mobilePhone;
        private string _imagePath;
        private string _jobTitle;
        private string _organization;
        private string _primaryEmail;
        private string _secondaryEmail;

        public Guid Id
        {
            get { return _id; }
            set { _id = value; }
        }
        public string FirstNames
        {
            get { return _firstNames; }
            set { _firstNames = value; }
        }
        public string Surname
        {
            get { return _surname; }
            set { _surname = value; }
        }
        public string HomePhone
        {
            get { return _homePhone; }
            set { _homePhone = value; }
        }
        public string WorkPhone
        {
            get { return _workPhone; }
            set { _workPhone = value; }
        }
        public string MobilePhone
        {
            get { return _mobilePhone; }
            set { _mobilePhone = value; }
        }
        public string ImagePath
        {
            get { return _imagePath; }
            set { _imagePath = value; }
        }
        public string JobTitle
        {
            get { return _jobTitle; }
            set { _jobTitle = value; }
        }
        public string Organization
        {
            get { return _organization; }
            set { _organization = value; }
        }
        public string PrimaryEmail
        {
            get { return _primaryEmail; }
            set { _primaryEmail = value; }
        }
        public string SecondaryEmail
        {
            get { return _secondaryEmail; }
            set { _secondaryEmail = value; }
        }

        public override bool Equals(object obj)
        {
            Contact other = obj as Contact;
            return other != null && other.Id == Id;            
        }
    }
}
Then setup our class for saving data, I have called it DataRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Example.Model
{
    public class DataRepository
    {
        private List _contactStore;       
        private readonly string _stateFile;

        public DataRepository()
        {
            _stateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "contacts.state");

            Deserialize();
        }

        public void SaveContact(Contact contact)
        {
            if (contact.Id == Guid.Empty)
                contact.Id = Guid.NewGuid();

            if (!_contactStore.Contains(contact))
                _contactStore.Add(contact);

            Serialize();
        }
        public void DeleteContact(Contact contact)
        {
            _contactStore.Remove(contact);
            Serialize();
        }
        public List FindAllContacts()
        {
            return new List(_contactStore);
        }
        private void Serialize()
        {
            using (FileStream stream = File.Open(_stateFile, FileMode.OpenOrCreate))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, _contactStore);
            }
        }

        private void Deserialize()
        {
            if (File.Exists(_stateFile))
            {
                using (FileStream stream = File.Open(_stateFile, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    _contactStore = (List)formatter.Deserialize(stream);
                }
            }
            else _contactStore = new List();            
        }
        
    }
}
Break It Down

On the first line of the class member it creates a new string for a file called contacts.state: _stateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "contacts.state");

In the Deserialize function this effectively checks to see if the file exists by this name and if so creates a filestream to extract the data.

Whenever a save or delete is performed the Serialize function is called which creates the file if it does not exist and adds the contact list to the file.

How to use
Easy simply create a new DataRepository class, load the current data and call the functions as required:
DataRepository _dataRepository;  // define class
ObservableCollection _currentContacts = new ObservableCollection(_dataRepository.FindAllContacts()); // load current data and use however you wish
Saving a record from a pre defined Contact class
if (!_currentContacts.Contains(contact)) // assumes you have created a new Contact class already
     _currentContacts.Add(contact);
    _dataRepository.SaveContact(contact);

Let me know if you have any more questions or get stuck.

Wednesday, 17 November 2010

Using javascript validation on an ASP .Net page

Whilst in normal scenarios you would use the .net validators for ASP I found several scenarios where they were got in the way, especially if I had more than one button on a form performing tasks different to the area that needed validating.

I decided to do some javascript validation like I would have done with classic ASP instead and use an alert message box rather than displaying items on the page. Turns out it was pretty easy, first change the button(or other control) to use its OnClientClick method to call a javascript function like so:
<asp:Button ID="btnPerformTask" runat="server" Text="Perform Task" 
OnClick="btnPerformTask_Click" OnClientClick="return validateMe();" />

Then create the javascript function to perform the validation (here I have done it against a textbox with an id of txtInputToCheck):
function validateMe() {

if (document.getElementById('<%=txtInputToCheck.ClientID%>').value.length == 0) {
alert("Text has not been entered.");
return false;
}

return true;

}

I needed to use the txtInputToCheck.ClientID as the ID that appears on the page when rendered is not the same as you define in the HTML of your page. Then I simply check the value length to see if its been entered and return false if so.

Returning false stops the page from posting and returning true allows it to do so, return true is put at the end so if all validation is ok I am letting the page continue.

Tuesday, 16 November 2010

ComboBox binding in Silverlight

Using a combobox in silverlight is really easy but it's a little more tricky when you want to bind data to the combobox, it tends to bind ok but setting the SelectedItem doesn't get set.

Therefore I used the notify property changed to update the UI instead. Heres how you can achieve the same:
XAML:
<UserControl x:Class="TestSLApp.MainPage"
xmlns:this="clr-namespace:TestSLApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<this:ViewModel x:Key="VM" />
</Grid.Resources>
<ComboBox Width="100" Height="50"
ItemsSource="{Binding MYLIST, Source={StaticResource VM}}"
SelectedItem="{Binding MySelectedItem, Mode=TwoWay, Source={StaticResource VM}}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding SomeText}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</UserControl>

Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace TestSLApp
{
public partial class MainPage : UserControl
{
private ViewModel VIEWMODEL
{
get
{
return LayoutRoot.Resources["VM"] as ViewModel;
}
}

public MainPage()
{
InitializeComponent();
VIEWMODEL.MYLIST = new List()
{
new DropDownItem() { ID = 1, SomeText="Text1"},
new DropDownItem() { ID = 2, SomeText="Text2"},
new DropDownItem() { ID = 3, SomeText="Text3"},
new DropDownItem() { ID = 4, SomeText="Text4"},
new DropDownItem() { ID = 5, SomeText="Text5"},
new DropDownItem() { ID = 6, SomeText="Text6"}
};
VIEWMODEL.MySelectedItem = VIEWMODEL.MYLIST.FirstOrDefault(o => o.ID == 5);
}
}


public class ViewModel : INotifyPropertyChanged
{
private List _list = null;
public List MYLIST
{
get
{
return _list;
}
set
{
if (_list == value)
return;
_list = value;
NotifyPropertyChanged("MYLIST");
}
}

private DropDownItem _mySelectedItem = null;
public DropDownItem MySelectedItem
{
get
{
return _mySelectedItem;
}
set
{
if (_mySelectedItem == value)
return;
_mySelectedItem = value;
NotifyPropertyChanged("MySelectedItem");
}
}


public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
}

public class DropDownItem
{
public int ID { get; set; }
public string SomeText { get; set; }
}
}


I actually put the ViewModel class in a seperate document but have kept it in the same code here for easy reference.

User Control Cast Error

Came across an error I haven't had before using ASP .Net so thought I would share this with the world in case someone else had the same problem. After updating a page and copying it to the webserver when I came to look at it again I got this message:

Unable to cast object of type 'ASP.controls_student_ascx' to type 'Controls_Student'

In order to resolve this I had to clear my cache and then it worked fine.

Monday, 15 November 2010

Using javascript to create full screen windows in ASP .Net

My current role at DatabridgeMiS involves creating a web version of existing software, which can be tricky when trying to create the same functionality of popup windows that can be maximized to full screen.

When using the Ajax Control Toolkit I can use the ModalPopupExtender to create simple popup windows by setting the target to a panel that is invisible by default. I can set the panels width and height to control the size of my popup window.

However, I wanted to be able to achieve full width and height but I found using percentages of 100% for both and the body worked ok to some extent but looked confusing in places plus I wanted specific sizing for some items.

So I decided to create my own code to perform this action myself. I already had jquery attached to my page so I could use the document.Ready function to insert my code.

First I needed to find the width and height of the current viewport:

var viewportwidth;
var viewportheight;

if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerWidth;
viewportheight = window.innerHeight;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
viewportheight = document.documentElement.clientHeight;
viewportwidth = document.documentElement.clientWidth;
}
else {
viewportheight = document.getElementsByTagName('body')[0].clientHeight;
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
}

The code above performs different checks as different browsers use different methods of obtaining the viewport information and using only one method wouldn't work across the board. Next I used a jquery style function to find all 'panels' that I had put a class of 'fullscreen' on:

$('.fullscreen').each(function (i) {
$(this).width(viewportwidth);
$(this).height(viewportheight);
});

This then regardless of browser makes my popup full screen (although watch out for margin or padding settings that could enlarge it).

Then I simply used other jquery style functions to set elements height/width within the popup by simply subtracting the viewport settings. Have a play yourself and check it out on different browsers and screens, works brilliantly.

Future of Silverlight

On the 2nd December 2010 there will be an event in Redmond discussing silverlight, looking forward to what comes out of this after recent speculation that there would be no further development into silverlight.

Check out the details of the event at http://www.silverlight.net/news/events/firestarter/.

Sunday, 14 November 2010

title tags on images

The alt tag is always important when using images in case of blind users or the image couldn't be displayed. But don't forget to include a title tag as well because if you didn't know already FireFox doesn't display the tooltip from an alt tag only the title.
Published with Blogger-droid v1.6.3

Saturday, 13 November 2010

Using Linq to Split a List

Started using more Linq and had to use it recently for splitting a list of items.

Basically I had to create a treeview of items and I didn't want to have to keep loading the items from a stored procedure everytime I needed to add items to a node.

So here's what I did instead, I used one stored procedure to create one list:
List<NodeItem> list1 = New List<NodeItem>();
list1.LoadListItems(); // this function uses stored procedure and loads list

And then I filter this list into as many other ones as I need (or create a loop and create a list for each node I want to add to), by doing the following:
int NodeID = CurrentNodeID;
List<NodeItem> subNodes = New List<NodeItem>();
subNodes = list1.Where(n => n.LinkedID == NodeID).ToList();

This preserves list1 and saves me from running another data query, sorted.

Security Update for .Net

There is a recently discovered security vulnerability in .Net which is publicly known so make sure you get yourself updated. See here for more information.

Wednesday, 3 November 2010

Issue with using CSS check for iPad device width

Many people out there adopt the following way of using a stylesheet based on the max device width in order to use different styling for an iPad:

<link href="css/iPad.css" media="all and (max-device-width:1024px)" rel="stylesheet" type="text/css">

However after doing several browser checks in different resolutions for a site I had done just this on I found that if you were using a screen resolution of 1024x768 and the browser Google Chrome it uses the iPad css.

Therefore I had to change this strategy and instead now use the following code to get a better check on the device accessing the site:

<script type="text/javascript"> // <![CDATA[
if ((navigator.userAgent.indexOf('iPad') != -1)) {
document.write('<link href="css/iPad.css" media="all" rel="stylesheet" type="text/css">');
} // ]]></script>

Works perfectly now!!