Wednesday, 17 November 2010

Graph# – WPF Graph Layout Framework

Download Graph#

Add References to

  • GraphSharp.dll
  • GraphSharp.Controls.dll
  • QuickGraph.dll
  • WPFExtensions.dll

This sample shows you how to

  • Visualize Data on the graph
  • Update Graph using notifications
  • Add menu items to graph object
  • Add events to graph object
  • Zoom in/out

graphsharp

<Window x:Class="Samples.TestGraph.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:graphsharp="clr-namespace:GraphSharp.Controls;assembly=GraphSharp.Controls"
    xmlns:zoom="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions"
    xmlns:local="clr-namespace:Samples.TestGraph"
    Title="Window1" Height="335" Width="592">
    <Grid>
            <Grid.Resources>        
                <local:ActiveConverter x:Key="activeConverter"/>
                <DataTemplate DataType="{x:Type local:SampleVertex}">
                    <Border  Background="{Binding Path=Active, Converter={StaticResource activeConverter}, NotifyOnTargetUpdated=True}"
					BorderBrush="LightGray" 
					BorderThickness="1,1,1,1"
					CornerRadius="10,10,10,10"
					Padding="10,10,10,10"
					HorizontalAlignment="Center"
					VerticalAlignment="Center"
					Cursor="Hand">
                        <Border.ContextMenu>
                            <ContextMenu>
                                <MenuItem x:Name="Change" Click="MenuItem_Click" Tag="{Binding}">
                                    <MenuItem.Header>
                                        <TextBlock HorizontalAlignment="Left">Change</TextBlock>
                                    </MenuItem.Header>
                                </MenuItem>
                            </ContextMenu>
                        </Border.ContextMenu>
                        <Border.ToolTip>
                            <ToolTip>
                                <TextBlock Text="{Binding Text}" />
                            </ToolTip>
                        </Border.ToolTip>
                        <TextBlock Text="{Binding Text}" TextAlignment="Center" TextWrapping="Wrap" />
                    </Border>
                </DataTemplate>
            </Grid.Resources>
            
            <zoom:ZoomControl Name="zoomControl">
            <graphsharp:GraphLayout x:Name="graphLayout"
                                    Graph="{Binding Path=Graph}"
                                    LayoutAlgorithmType="{Binding Path=LayoutAlgorithm}"
                                    OverlapRemovalAlgorithmType="FSA" />            
            </zoom:ZoomControl>        
    </Grid>
</Window>
namespace Samples.TestGraph
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = this;
            CreateGraph();
        }
        private readonly BidirectionalGraph<object, IEdge<object>> _graph = new BidirectionalGraph<object, IEdge<object>>();
        public IBidirectionalGraph<object, IEdge<object>> Graph
        {
            get { return _graph; }
        }
        private string _layoutAlgorithm = "EfficientSugiyama";
        public string LayoutAlgorithm
        {
            get { return _layoutAlgorithm; }
            set
            {
                if (value != _layoutAlgorithm)
                {
                    _layoutAlgorithm = value;                    
                }
            }
        }
        private void CreateGraph()
        {
            _graph.Clear();
            SampleVertex obj1 = new SampleVertex("One");
            _graph.AddVertex(obj1);
            SampleVertex obj2 = new SampleVertex("Two");
            _graph.AddVertex(obj2);
            SampleVertex obj3 = new SampleVertex("Three");
            _graph.AddVertex(obj3);
            _graph.AddEdge(new Edge<object>(obj1, obj2));
            _graph.AddEdge(new Edge<object>(obj1, obj3));
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            var vertex = menuItem.Tag as SampleVertex;
            vertex.Change();            
        }
    }
    public class SampleVertex : INotifyPropertyChanged
    {
        private bool _active;
        private string _text;
        public bool Active
        {
            get { return _active; }
            set
            {
                _active = value;
                NotifyChanged("Active");
            }
        }
        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                NotifyChanged("Text");
            }
        }
        public SampleVertex(string text)
        {
            Text = text;
        }
        public void Change()
        {
            Active = !Active;
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    [ValueConversion(typeof(bool), typeof(Brush))]
    public class ActiveConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var state = (bool)value;
            if(state)
            {
                return new SolidColorBrush(Colors.WhiteSmoke);
            }else
            {
                return new SolidColorBrush(Colors.LightSalmon);
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

Monday, 15 November 2010

Free WPF Docking Library (like in Visual Studio)

AvalonDock
http://avalondock.codeplex.com/
Getting Started Tutorial
ADTutorial2.png

Thursday, 11 November 2010

Python Reference

#import libraries
import sys,os,shutil,glob,string,re,datetime
 
#=====================================
# IO Samples
#=====================================
 
#read file line by line
f=open('text.txt','r')
for line in f:
	print string.split(line, '\n')[0] #remove linebreak
 	
#read file all at once
f=open('text.txt','r')
text = f.read()		
print(text)
 
#current directory
print os.getcwd()
 
#list files/folders in current directory
for file in os.listdir(os.getcwd()):
	print file
	
#print directory structure
def printDir(path,indent):
	for root, dirs, files in os.walk(path):
		for name in dirs:
			print indent+name
			printDir(os.path.join(root,name),indent+" ")
		for name in files:
			print indent+name
	 
printDir(os.getcwd())	
	 
#create dir
os.mkdir("Test")
 
#delete dir
os.remove("Test")	
 
#execute command
os.system("mkdir x")
  
#execute command line and return a result
result = os.popen("ls").read()
  
#wildcard file names
print glob.glob("*.py")
  
#copy file
shutil.copy("file1.py","file2.py")
  
#movw file
shutil.move('dir1', 'dir2')
  
#command line arguments
print sys.argv
print sys.argv[1]
  
 
#=====================================
# Exception Handling
#=====================================
 
#catch error
try:
	f=open('test.py',r)
	f.readline()
except:
	print "Error:",sys.exc_info()
	print " Error:",sys.exc_info()[0]
	print " Msg  :",sys.exc_info()[1]	
 
#raise error	
try:
	raise NameError, 'Custom Error'
except:
	print "Error:",sys.exc_info()
  
 
#=====================================	
# String/Formatting Samples
#=====================================
 
#string character manipulation
sampletext = "Hello"
print sampletext[2:] #llo (everything but first 2)
print sampletext[-2:] #ll (last 2)
print sampletext #He (first 2)
print sampletext[:-2] #Hel (everything but last 2)
 
#templating string
t = string.Template("This $one is a $two")
print t.substitute(one='1',two='2')
 
#template from file
f=open('template.txt','r')
t = string.Template(f.read())
print t.substitute(param1='1',param2='2')
 
#split string
for resultline in result.split("\n"):	
	print resultline
 
#cast int to string
number = 1
text = str(number)
print text
 
 
#=====================================	
# DateTime Parsing/Formatting
#=====================================
#date
print datetime.date.today()
 
#datetime
print datetime.datetime.today()
 
#format date
print datetime.datetime.today().strftime("%y%m%d_%H%M%S")
 
#parse date
dt = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
print dt	
  
 	
#=====================================
# Math
#=====================================
val = 5
print '5 mod 2: ', val % 2
print '5 div 2: ', val / 2
 
print abs(-4)	
  
   
#=====================================	
# Regex
#=====================================
 
#regex
regexValue = "Name John"
regex = "(Name)\s*(?P<FirstName>\w+)"
m = re.match(regex,regexValue)	
if m:
 print 'First Name: ' + m.group('FirstName')
else:
 print 'FirstName not found'
 
 
#=====================================
# Custom Libraries/Modules
#=====================================
 
# Save this module to fibo.py (Fibonacci numbers)
#-------------
# write Fibonacci series up to n
def fib(n):
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b
 
# return Fibonacci series up to n
def fib2(n): 
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
#-------------
 
# Calling fib methods
import fibo
s = 'This is fibo or 5: ' + str(fibo.fib2(5))
print s	
 
# Save this module to cars.py
#-------------
# Custom class
class Car:	
	def __init__(self,i):
		self.i = i
 	
	def increment(self):
		print 'incrementing'
		self.i=self.i+1
		
	def printvalue(self):
		print self.i;
		
# Calling cars class
import cars
car = cars.Car(5)
print car.i
car.printvalue()
car.increment()
car.printvalue()	
 
 
#=====================================
# Unit Tests
#=====================================
 
import unittest
 
class TestStatisticalFunctions(unittest.TestCase):
	def test_average(self):
		self.assert_(isinstance(2 + 4, int))
		self.assertEqual(abs(-4), 4)        
		self.assertRaises(ZeroDivisionError, lambda : 1/0)        
 
#run tests		
unittest.main()