(1) Need to turn on IIS features, Fx 4.5 and WebScoket from Control Panel
(2) Currently must run ASP.Net project in IIS 8.0. So project config must uncheck IIS express. May also need to clean up applicationHost.Config to clear all site/project pointing to port 80.
Make a httpHandler
public void ProcessRequest(HttpContext ctx)
{
if (ctx.IsWebSocketRequest)
{
Microsoft.Web.WebSockets.WebSocketExtensions.AcceptWebSocketRequest(ctx, new Class1());
// ctx.AcceptWebSocketRequest(Test);
}
else
{
ctx.Response.StatusCode = 400;
}
}
async Task Test(AspNetWebSocketContext wsCtx)
{
AspNetWebSocket ws = wsCtx.WebSocket as AspNetWebSocket;
string UserMsg = "Test from WS";
WebSocketHandler wsH = new WebSocketHandler();
wsH.WebSocketContext = wsCtx;
ArraySegmentarrS = new ArraySegment (Encoding.UTF8.GetBytes(UserMsg));
wsH.Send(UserMsg);
await ws.SendAsync(arrS, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
}
public class Class1: WebSocketHandler
{
}
Use JQuery to connect
<
script src="Scripts/jquery-1.7.1.js" ></script>
<script>
$(function () {
$("#b").click(function () {
var conn = new WebSocket("ws://localhost/TestWebSocket2/test.ashx");
conn.onmessage = function (msg) {
alert(msg.data);
}
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Connect to WS" id="b" />
Both JQuery and WebSocket can be downloaded from NuGet
Saturday, November 26, 2011
Websocket asp.net fx4.5
Tuesday, October 11, 2011
WinRT Code
WinRT component in C# -- public type must be WinRT types
=========================
public sealed class Class1
{
public IList Test()
{
return new List();
}
public IAsyncOperation Test4() //WinRT type
{
return AsyncInfoFactory.Create( ()=>Test2());
}
private async Task Test2()
{
var v = new HttpClient();
var q = await v.GetAsync("");
string s="";
return s;
}
}
Storaage File RO collection
=================================
RO Collection <==> Windows.Foundation.Collections.IVectorView
async void Test()
{
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
var files = await picker.PickMultipleFilesAsync();
foreach (StorageFile f in files)
{
lb.Items.Add(f.Name);
}
}
Camera from C# ( no more Win32)
==================================
async void camera()
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
}
}
JavaScript
myGroups.forEach(function (g, i) {
var even = (i % 2) === 0;
groups.push({
key: 'group' + i,
title: 'Collection title lorem ' + i+g.name,
backgroundColor: colors[i % colors.length],
label: 'Eleifend posuere',
description: even ? 'ǺSed nisl nibh, eleifend posuere.' : 'ǺSed nisl nibh, eleifend posuere laoreet egestas, porttitor quis lorem.',
fullDescription: 'Ǻ Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.' + (even ? '' : ' Ǻ Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.')
});
=========================
public sealed class Class1
{
public IList
{
return new List
}
public IAsyncOperation
{
return AsyncInfoFactory.Create( ()=>Test2());
}
private async Task
{
var v = new HttpClient();
var q = await v.GetAsync("");
string s="";
return s;
}
}
Storaage File RO collection
=================================
RO Collection <==> Windows.Foundation.Collections.IVectorView
async void Test()
{
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
var files = await picker.PickMultipleFilesAsync();
foreach (StorageFile f in files)
{
lb.Items.Add(f.Name);
}
}
Camera from C# ( no more Win32)
==================================
async void camera()
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
}
}
JavaScript
myGroups.forEach(function (g, i) {
var even = (i % 2) === 0;
groups.push({
key: 'group' + i,
title: 'Collection title lorem ' + i+g.name,
backgroundColor: colors[i % colors.length],
label: 'Eleifend posuere',
description: even ? 'ǺSed nisl nibh, eleifend posuere.' : 'ǺSed nisl nibh, eleifend posuere laoreet egestas, porttitor quis lorem.',
fullDescription: 'Ǻ Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.' + (even ? '' : ' Ǻ Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.')
});
Friday, September 16, 2011
MVP on WinForm
(1) Model ---Reference Data
Data Entry windows almost always need reference data to guide user input. A dropdown list filled with 50 US States is a perfect example. Naturally, we would want a simple type structure class and a complex type storage class to hold 50 states for databinding purposes:
public struct State
{
public State(int? id, string name)
{
_StateID = id;
_StateName = name;
}
private int? _StateID;
public int? StateID
{
get { return _StateID;}
set { _StateID = value; }
}
private string _StateName;
public string StateName
{
get { return _StateName; }
set { _StateName = value; }
}
}
public class States
{
private static List _StateList = new List();
static States()
{
_StateList.Add(new State(0, "MA"));
....
_StateList.Add(new State(null, "(empty)")); // add (empty) for user to de-select to
}
public static List StateList
{
get { return _StateList; }
}
}
(2) Model --- Entity Data
Suppose UI is designed to present User an address for View/Edit/Create, we then need an entity to represent Address:
public class Address
{
private int? _StateID;
public int? StateID
{
get { return _StateID; }
set { _StateID = value; }
}
}
Note Database normalization requires only saving StateID to database and avoid duplicating StateName.
(3) Presenter --- one way databinding to View
Upon View calling its single entry point, a Presenter will initialize View, Load Data from Model and Execute Business logic (e.g. show, update, add):
public interface IAddressView
{
void ShowReferenceData();
void ShowCurrentAddress();
}
class AddressPresenter
{
private IAddressView _view;
public AddressPresenter(IAddressView view)
{
_view = view;
}
public void Render(int? UserID)
{
LoadEntityData(UserID);
_view.ShowReferenceData();
_view.ShowCurrentAddress();
}
private ASC.ReferenceData.State _State;
public ASC.ReferenceData.State State
{
get { return _State;}
set { _State=value;}
}
private ASC.Entity.Address _Address;
private void LoadEntityData(int? UserID)
{
// simulate retrival of Address from Database
_Address = new ASC.Entity.Address();
if (UserID >0) _Address.StateID = 3;
// All UserID <=0 will have empty selection of state in its Address Entity;
foreach (ASC.ReferenceData.State s in ASC.ReferenceData.States.StateList)
{
if (s.StateID == _Address.StateID)
{
_State = new ASC.ReferenceData.State(_Address.StateID, s.StateName);
break;
}
}
}
public void Update()
{
// Save Entity to Database
}
public void Add()
{
// Insert Entity to Database
}
}
Note that two properties in Address Entity Data are represented as a single property of type ASC.ReferenceData.State. This will enable loading into a ComboBox for ease of databinding.
(4) View --- Implement IView and Reverse DataBind
As before, View need to implement IView with consideration of reference data
public partial class AddressChangeForm : Form, IAddressView
{
public void ShowReferenceData()
{
this.cbState.DataSource = ASC.ReferenceData.States.StateList;
this.cbState.DisplayMember = "StateName";
}
public void ShowCurrentAddress()
{
cbState.DataBindings.Add("SelectedItem", _Presenter, "State",false,DataSourceUpdateMode.OnPropertyChanged, new ASC.ReferenceData.State(null,"(empty)"));
}
Note that Reference data are push to View using one-way databinding, while Presenter data are push to View with change probagated backwards through OnPropertyChanged.
Presenter entry point will be called upon user action:
private void btnGetCurrent_Click(object sender, EventArgs e)
{
cbState.DataBindings.Clear();
_Presenter = new AddressPresenter(this);
_Presenter.Render(1078);
}
And a new presenter need to be created upon User Add New action:
private void btnAdd_Click(object sender, EventArgs e)
{
.....
cbState.DataBindings.Clear();
_Presenter = new AddressPresenter(this);
_Presenter.Render(-1);
......
_Presenter.Add();
cbState.DataBindings.Clear();
.....
}
Data Entry windows almost always need reference data to guide user input. A dropdown list filled with 50 US States is a perfect example. Naturally, we would want a simple type structure class and a complex type storage class to hold 50 states for databinding purposes:
public struct State
{
public State(int? id, string name)
{
_StateID = id;
_StateName = name;
}
private int? _StateID;
public int? StateID
{
get { return _StateID;}
set { _StateID = value; }
}
private string _StateName;
public string StateName
{
get { return _StateName; }
set { _StateName = value; }
}
}
public class States
{
private static List _StateList = new List();
static States()
{
_StateList.Add(new State(0, "MA"));
....
_StateList.Add(new State(null, "(empty)")); // add (empty) for user to de-select to
}
public static List StateList
{
get { return _StateList; }
}
}
(2) Model --- Entity Data
Suppose UI is designed to present User an address for View/Edit/Create, we then need an entity to represent Address:
public class Address
{
private int? _StateID;
public int? StateID
{
get { return _StateID; }
set { _StateID = value; }
}
}
Note Database normalization requires only saving StateID to database and avoid duplicating StateName.
(3) Presenter --- one way databinding to View
Upon View calling its single entry point, a Presenter will initialize View, Load Data from Model and Execute Business logic (e.g. show, update, add):
public interface IAddressView
{
void ShowReferenceData();
void ShowCurrentAddress();
}
class AddressPresenter
{
private IAddressView _view;
public AddressPresenter(IAddressView view)
{
_view = view;
}
public void Render(int? UserID)
{
LoadEntityData(UserID);
_view.ShowReferenceData();
_view.ShowCurrentAddress();
}
private ASC.ReferenceData.State _State;
public ASC.ReferenceData.State State
{
get { return _State;}
set { _State=value;}
}
private ASC.Entity.Address _Address;
private void LoadEntityData(int? UserID)
{
// simulate retrival of Address from Database
_Address = new ASC.Entity.Address();
if (UserID >0) _Address.StateID = 3;
// All UserID <=0 will have empty selection of state in its Address Entity;
foreach (ASC.ReferenceData.State s in ASC.ReferenceData.States.StateList)
{
if (s.StateID == _Address.StateID)
{
_State = new ASC.ReferenceData.State(_Address.StateID, s.StateName);
break;
}
}
}
public void Update()
{
// Save Entity to Database
}
public void Add()
{
// Insert Entity to Database
}
}
Note that two properties in Address Entity Data are represented as a single property of type ASC.ReferenceData.State. This will enable loading into a ComboBox for ease of databinding.
(4) View --- Implement IView and Reverse DataBind
As before, View need to implement IView with consideration of reference data
public partial class AddressChangeForm : Form, IAddressView
{
public void ShowReferenceData()
{
this.cbState.DataSource = ASC.ReferenceData.States.StateList;
this.cbState.DisplayMember = "StateName";
}
public void ShowCurrentAddress()
{
cbState.DataBindings.Add("SelectedItem", _Presenter, "State",false,DataSourceUpdateMode.OnPropertyChanged, new ASC.ReferenceData.State(null,"(empty)"));
}
Note that Reference data are push to View using one-way databinding, while Presenter data are push to View with change probagated backwards through OnPropertyChanged.
Presenter entry point will be called upon user action:
private void btnGetCurrent_Click(object sender, EventArgs e)
{
cbState.DataBindings.Clear();
_Presenter = new AddressPresenter(this);
_Presenter.Render(1078);
}
And a new presenter need to be created upon User Add New action:
private void btnAdd_Click(object sender, EventArgs e)
{
.....
cbState.DataBindings.Clear();
_Presenter = new AddressPresenter(this);
_Presenter.Render(-1);
......
_Presenter.Add();
cbState.DataBindings.Clear();
.....
}
Friday, September 2, 2011
WinForm Google Suggest AutoComplete
Initiated from BB Quick Access Button
dataGridViewBC.ReadOnly = false;
dataGridViewBC.Columns[1].Visible = false;
this.toolStripStatusLabel1.Text = "";
this.textBoxSecurity.Text = "";
string BBSymbol = ((Button)sender).Text;
BBSymbol = (BBSymbol.Length == 1) ? BBSymbol.PadRight(2, ' ') : BBSymbol;
using (SqlConnection cn = new SqlConnection(connString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(@"
select distinct
substring(ext_sec_id,1,len(ext_sec_id)-2),
substring(ticker,1,len(ticker)-2),
sec_name from csm_security where sec_typ_cd='Fut' and ticker like '" + BBSymbol + "__'", cn);
SqlDataReader r = cmd.ExecuteReader();
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
string s = "";
while (r.Read())
{
s = " " + r.GetValue(0).ToString() + " " + r.GetValue(1).ToString() + " " + r.GetValue(2).ToString();
col.Add(s);
}
this.textBoxSecurity.AutoCompleteCustomSource = col;
this.textBoxSecurity.Focus();
if (col.Count == 1)
{
this.textBoxSecurity.Text = s;
FillGridView();
SetSelectedValueForAllComboEdit();
}
if (col.Count >= 2) SendKeys.Send(" ");
Initiated from Search Button
private void btnSearch_Click(object sender, EventArgs e)
{
dataGridViewBC.ReadOnly = false;
dataGridViewBC.Columns[1].Visible = false;
this.toolStripStatusLabel1.Text = "";
if (this.textBoxSecurity.Text.Length <= 1) return;
if (this.btnSearch.Text == "Get Rates" && this.textBoxSecurity.Text.Trim() != "No Match")
{
FillGridView();
SetSelectedValueForAllComboEdit();
}
if (this.btnSearch.Text == "Search")
{
Listlist = FindMatch(_SecurityList, this.textBoxSecurity.Text.Trim());
_MatchedCollection = new AutoCompleteStringCollection();
foreach (string s in list)
{
_MatchedCollection.Add(s);
}
if (_MatchedCollection.Count == 0) _MatchedCollection.Add(" No Match");
this.textBoxSecurity.AutoCompleteCustomSource = _MatchedCollection;
this.textBoxSecurity.Focus();
this.textBoxSecurity.Clear();
SendKeys.Send(" ");
this.btnSearch.Text = "Get Rates";
}
Thursday, August 4, 2011
Fish Eye Xaml
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontSize" Value="12" />
<Style.Triggers>
<EventTrigger RoutedEvent="Button.MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="FontSize"
To="36" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Button.MouseLeave">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="FontSize"
To="12" Duration="0:0:0.25" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</StackPanel.Resources>
<Button>Button No. 1</Button>
<Button>Button No. 2</Button>
<Button>Button No. 3</Button>
<Button>Button No. 4</Button>
<Button>Button No. 5</Button>
<Button>Button No. 6</Button>
<Button>Button No. 7</Button>
<Button>Button No. 8</Button>
<Button>Button No. 9</Button>
</StackPanel>
Tuesday, August 2, 2011
3D Eye ball UI Try out
<Window
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"
x:Class="WpfApplication13.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480" Loaded="Window_Loaded">
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource DBApex}}">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="80*" />
</Grid.ColumnDefinitions>
<DataGrid x:Name="dg" Margin="8,8,0,8" Grid.Row="1" Grid.ColumnSpan="2" AutoGenerateColumns="False" ItemsSource="{Binding Collection}" FontSize="18.667" SelectionChanged="dg_SelectionChanged">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding UD}" Header="UD"/>
<DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
<DataGridTextColumn Binding="{Binding Market_Value}" Header="Market_Value"/>
<DataGridTextColumn Binding="{Binding MTD}" Header="MTD"/>
<DataGridTextColumn Binding="{Binding QTD}" Header="QTD"/>
<DataGridTextColumn Binding="{Binding YTD}" Header="YTD"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="btnD" Content="Direct" HorizontalAlignment="Right" Margin="0,8,8,0" Width="58" FontSize="8" Click="btnD_Click" />
<Button x:Name="btnE" Content="EyeBall" HorizontalAlignment="Left" Margin="77,8,0,0" Width="53" FontSize="8" Click="btnE_Click" />
<Viewport3D ClipToBounds="True" Grid.Row="1" Grid.Column="0" >
<Viewport3D.Camera>
<PerspectiveCamera Position=".2, 0, 1.5" x:Name="camera" LookDirection="-.2,0,-1"/>
</Viewport3D.Camera>
<Viewport2DVisual3D >
<Viewport2DVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="uiRotate" Angle="40" Axis="0, 1, 0" />
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Viewport2DVisual3D.Transform>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0" TextureCoordinates="0,0 0,1 1,1 1,0" TriangleIndices="0 1 2 0 2 3"/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" Brush="White"/>
</Viewport2DVisual3D.Material>
<Viewport2DVisual3D.Visual>
<DataGrid x:Name="dg2" ClipToBounds="False" Height="400" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False" ItemsSource="{Binding Collection}" FontSize="18.667" VerticalScrollBarVisibility="Visible" SelectionChanged="dg2_SelectionChanged" >
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding UD}" Header="UD"/>
<DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
<DataGridTextColumn Binding="{Binding Market_Value}" Header="Market_Value"/>
<DataGridTextColumn Binding="{Binding MTD}" Header="MTD"/>
<DataGridTextColumn Binding="{Binding QTD}" Header="QTD"/>
<DataGridTextColumn Binding="{Binding YTD}" Header="YTD"/>
</DataGrid.Columns>
</DataGrid>
</Viewport2DVisual3D.Visual>
</Viewport2DVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Color="#FFFFFFFF" Direction="0,0,-1"/>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</Grid>
</Window>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dg2.Visibility = System.Windows.Visibility.Collapsed;
}
private void btnE_Click(object sender, RoutedEventArgs e)
{
dg.Visibility = System.Windows.Visibility.Collapsed;
dg2.Visibility = System.Windows.Visibility.Visible;
}
private void btnD_Click(object sender, RoutedEventArgs e)
{
dg.Visibility = System.Windows.Visibility.Visible;
dg2.Visibility = System.Windows.Visibility.Collapsed;
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
Double r = this.ActualHeight / dg2.Height * 300 / 480; r = 0.7;
camera.Position = new System.Windows.Media.Media3D.Point3D(.2/r, 0, 1.5/r);
}
private void dg2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//dg.Visibility = System.Windows.Visibility.Visible;
//dg2.Visibility = System.Windows.Visibility.Collapsed;
}
private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
dg.Visibility = System.Windows.Visibility.Collapsed;
dg2.Visibility = System.Windows.Visibility.Visible;
}
Move User Control arround inside Canvas
namespace Reporting.Wpf.UserControls
{
public class BaseGroupCharts : UserControl
{
protected ListRootFunds;
protected int DrillDownGroupId;
protected ApexDataContext _context = ApexDal.Instance.CreateApexDataContext();
protected bool AllowMove;
protected ListUnlayedouts = new List ();
protected double f = 0.2;
#region buiding Layed-outs/unlayed-outs
public virtual void BuildUnlayedouts(bool UseActual) { }
protected void ShowAtRightUppoerCornerUnlayedouts(bool UseActual, int LeftOffSet, Canvas cv)
{
double W = UseActual ? ActualWidth : Width;
double H = UseActual ? ActualHeight : Height;
int n = Unlayedouts.Count;
int col = (int)Math.Round(Math.Sqrt(n * W / H));
int row = (int)Math.Round(Math.Sqrt(n * H / W));
for (int i = 0; i < Unlayedouts.Count; i++)
{
Resizer r = Unlayedouts[i];
Canvas.SetLeft(r, (1 - f) * W + r.Width * (i % col) + LeftOffSet);
Canvas.SetTop(r, r.Height * (int)(i / col));
cv.Children.Add(r);
}
}
protected void ClearUnlayedouts(Canvas cv)
{
ListtoRemove = new List ();
foreach (var q in cv.Children)
{
Resizer r = q as Resizer;
if (r != null)
{
double left = (double)r.GetValue(Canvas.LeftProperty);
double top = (double)r.GetValue(Canvas.TopProperty);
if (left >= 0.8 * ActualWidth && top <= 0.2 * ActualHeight) toRemove.Add(r);
}
}
foreach (Resizer r in toRemove) cv.Children.Remove(r);
}
#endregion
#region lock/unlock
protected bool Locked = true;
protected void ToggleLockUnlock(Image imgLock, Canvas cv)
{
imgLock.Focus();
if (Locked)
{
imgLock.Source = new BitmapImage(new Uri("pack://application:,,,/GMO.AA.Reporting.Wpf;component/Images/Unlock.png"));
Locked = false;
foreach (UIElement c in cv.Children)
{
Resizer r = c as Resizer;
if (r != null) r.IsGripVisible = true;
}
ClearUnlayedouts(cv);
Unlayedouts.Clear();
BuildUnlayedouts(true);
ShowAtRightUppoerCornerUnlayedouts(true, 0, cv);
}
else
{
imgLock.Source = new BitmapImage(new Uri("pack://application:,,,/GMO.AA.Reporting.Wpf;component/Images/Lock.png"));
Locked = true;
ClearUnlayedouts(cv);
Unlayedouts.Clear();
BuildUnlayedouts(true);
ShowAtRightUppoerCornerUnlayedouts(true, 1000, cv);
foreach (UIElement c in cv.Children)
{
Resizer r = c as Resizer;
if (r != null) r.IsGripVisible = false;
}
}
}
#endregion
#region Drag Move
private Point m_StartPoint;
private double m_OriginalLeft;
private double m_OriginalTop;
private Boolean m_IsDown;
private UIElement m_OriginalElement;
private Boolean m_IsDragging;
protected void UserControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) AllowMove = true;
}
protected void UserControl_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) AllowMove = false;
}
protected void MyCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Canvas cv = sender as Canvas;
if (cv == e.Source || !AllowMove) return;
m_IsDown = true;
m_StartPoint = e.GetPosition(sender as Canvas);
m_OriginalElement = e.Source as UIElement;
cv.CaptureMouse();
e.Handled = true;
}
protected void MyCanvas_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (m_IsDown)
{
if (!m_IsDragging && Math.Abs(e.GetPosition(sender as Canvas).X - m_StartPoint.X) > SystemParameters.MinimumHorizontalDragDistance && Math.Abs(e.GetPosition(sender as Canvas).Y - m_StartPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
{
DragStarted();
}
if (m_IsDragging)
{
DragMoved(sender as Canvas);
}
}
}
protected void MyCanvas_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (m_IsDown)
{
DragFinished(false);
e.Handled = true;
}
}
protected void DragFinished(bool p)
{
System.Windows.Input.Mouse.Capture(null);
m_IsDragging = false;
m_IsDown = false;
}
protected void DragMoved(Canvas cv)
{
Point currentPosition = System.Windows.Input.Mouse.GetPosition(cv);
double elementLeft = (currentPosition.X - m_StartPoint.X) + m_OriginalLeft;
double elementTop = (currentPosition.Y - m_StartPoint.Y) + m_OriginalTop;
Canvas.SetLeft(m_OriginalElement, elementLeft);
Canvas.SetTop(m_OriginalElement, elementTop);
}
protected void DragStarted()
{
m_IsDragging = true;
m_OriginalLeft = Canvas.GetLeft(m_OriginalElement);
m_OriginalTop = Canvas.GetTop(m_OriginalElement);
}
#endregion
#region Resize
protected void MyCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.PreviousSize.Height == 0 || e.PreviousSize.Width == 0) return;
double rH = e.NewSize.Height / e.PreviousSize.Height;
double rW = e.NewSize.Width / e.PreviousSize.Width;
Canvas cv = sender as Canvas;
foreach (UIElement c in cv.Children)
{
Resizer r = c as Resizer;
if (r != null)
{
r.Width = r.Width * rW;
r.Height = r.Height * rH;
r.SetValue(Canvas.LeftProperty, (double)r.GetValue(Canvas.LeftProperty) * rW);
r.SetValue(Canvas.TopProperty, (double)r.GetValue(Canvas.TopProperty) * rH);
}
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GMO.AA.Reporting.Wpf.Common;
using GMO.AA.Reporting.Domain.Objects;
using System.DirectoryServices.AccountManagement;
using System.IO;
using GMO.OpenSource.Windows.Controls;
using GMO.AA.Reporting.UI.Core;
namespace Reporting.Wpf.UserControls
{
///
/// Interaction logic for GroupCharts.xaml
///
public partial class GroupChartsCanvas : BaseGroupCharts
{
public event DrillDownRequestedEventHandler DrillDownRequested;
public GroupChartsCanvas(Listlist,int drillDownGroupId)
{
InitializeComponent();
RootFunds = list;
DrillDownGroupId = drillDownGroupId;
_context = ApexDal.Instance.CreateApexDataContext();
GetCustomGroupData();
}
#region CG data
IEnumerablecGroups;
void GetCustomGroupData()
{
string userName = UserPrincipal.Current.DisplayName;
cGroups = (from x in _context.CustomGroups
where x.RelatedGroupId == DrillDownGroupId && !x.Deleted &&
(x.Public == true || x.CreatedByUserName == userName)
select x).OrderBy(y => y.CustomGroupName);
}
#endregion
#region override Un-Layed-outs in upper right corner
public override void BuildUnlayedouts(bool UseActual)
{
double W = UseActual ? ActualWidth : Width;
double H = UseActual ? ActualHeight : Height;
int n = cGroups.Count()+1;
double LCw = f * W, LCh = f * H;
int col = (int)Math.Round(Math.Sqrt(n * W / H));
int row = (int)Math.Round(Math.Sqrt(n * H / W));
foreach (CustomGroup cg in cGroups)
{
Resizer r = new Resizer() { Height = LCh / row, Width = LCw / col, ToolTip = cg.CustomGroupName };
CustomGroupExposureChart cgec = new CustomGroupExposureChart(cg, ChartVendors.Infragistic);
cgec.AllowDataPointDrillDown = true;
cgec.RelatedGroupName = EventEngine.Instance.SelectedGroup.GroupName;
cgec.DrillDownRequested += new DrillDownRequestedEventHandler(cgec_DrillDownRequested);
r.Content = cgec;
Unlayedouts.Add(r);
}
Resizer r1 = new Resizer() { Height = LCh / row, Width = LCw / col, ToolTip = "Currency Exposure"};
r1.Content = new CurrencyExposureChart();
Unlayedouts.Add(r1);
Resizer r2 = new Resizer() { Height = LCh / row, Width = LCw / col, ToolTip = "CountryExposure" };
r2.Content = new CountryExposureChart();
Unlayedouts.Add(r2);
Resizer r3 = new Resizer() { Height = LCh / row, Width = LCw / col, ToolTip = "Sector Exposure" };
r3.Content = new SectorExposureChart();
Unlayedouts.Add(r3);
}
void cgec_DrillDownRequested(object sender, DrillDownRequestedEventArgs e)
{
if (DrillDownRequested != null)
DrillDownRequested(sender,new DrillDownRequestedEventArgs() { GroupId = DrillDownGroupId, RelatedGroupId = e.RelatedGroupId, GroupName=e.GroupName, CustomGroup=e.CustomGroup, RelatedGroupName=e.RelatedGroupName });
}
#endregion
#region Control Events
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
BuildUnlayedouts(true);
ShowAtRightUppoerCornerUnlayedouts(true, 1000, MyCanvas);
foreach (UIElement c in MyCanvas.Children)
{
Resizer r = c as Resizer;
if (r != null) r.IsGripVisible = false;
}
Focus();
}
private void imgEdit_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ToggleLockUnlock(imgLock, MyCanvas);
}
#endregion
}
}
Resizer comes from Kent Boogaart
http://kentb.blogspot.com/2007/04/resizer-wpf-control.html
Subscribe to:
Posts (Atom)