Blog Archive

Sunday, December 25, 2011

Using AppFabric


Client App Config:

<configSections>
    <!-- required to read the <dataCacheClient> element -->
    <section name="dataCacheClient" type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
            Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, 
            Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere"/>
  </configSections>

  <dataCacheClient>
    <transportProperties maxBufferPoolSize="7" maxBufferSize="200000000"/>


    <!-- (optional) specify local cache
      <localCache
         isEnabled="true"
         sync="TimeoutBased"
         objectCount="100000"
         ttlValue="300" /> -->

    <!--(optional) specify cache notifications poll interval
      <clientNotification pollInterval="300" /> -->

    <hosts>
      <host name="10.32.68.136" cachePort="22233"/>
      <!--<host
         name="CacheServer2"
         cachePort="22233"/>-->
    </hosts>
  </dataCacheClient>
Client Code No Config:
           DataCacheFactoryConfiguration cfg= new DataCacheFactoryConfiguration();
            cfg.Servers= new DataCacheServerEndpoint[]
            {
                new DataCacheServerEndpoint("10.32.68.136",22233)//jqdappfabric.dev.gmo.tld",22233)
            };
            Microsoft.ApplicationServer.Caching.DataCacheFactory f = new DataCacheFactory(cfg);
            Console.WriteLine("Factory Created");
            DataCache c=f.GetDefaultCache();
            Console.WriteLine("Cache Connected");
            Console.WriteLine("Put into Cache");
            c.Put("k1","v1");
            Console.WriteLine("Get From Cache");
            Console.WriteLine(c.Get("k1"));
Client Code with Config:
          DataCacheFactory cf = new DataCacheFactory();
            DataCache cache = cf.GetDefaultCache();
            cache.Put("AllEntityHierarchy", list);
            object obj = cache.Get("AllEntityHierarchy");
NOTE: if Visual Studio 2010 Intelle-trace shows "No DNS entry" then use Hosts file.
   

Some usefull PowShellCommand:
 
 import/export-CacheClusterConfig: shows/set user permission.
 start/stop-cachecluster
 grant/invoke-CacheAllowedClientAccount

Thursday, December 1, 2011

WebSocket Handler


Separate Open and Message and use Collection to Broadcast
public class JsonWebSocketHandler : WebSocketHandler
{

WebSocketCollection _wsCns = new WebSocketCollection();
public override void OnMessage(string message)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
_wsCns.Broadcast(ser.Serialize( new
{
data="Test",
id=1
}));
}

public override void OnOpen()
{
_wsCns.Add(this);
}
}

IHttpHandler can inject WebSocketHanldler (Extension Method for Context)

public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new JsonWebSocketHandler());
}
}

JavaScript also need to separate Open and Send

$(function () {
var cn = new WebSocket("ws://localhost/TestJsonWebSocket/jswsh.ashx");
$("#b").click( function ()
{
cn.onmessage = function (msg) {
alert(msg);
}
});

$("#b2").click(function () {
cn.send(window.JSON.stringify({ type: 1 }));
}
);

});

Saturday, November 26, 2011

Websocket asp.net fx4.5


(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;
ArraySegment arrS = 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

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.')
});

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();
.....
}

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")
{
List list = 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 List RootFunds;
protected int DrillDownGroupId;
protected ApexDataContext _context = ApexDal.Instance.CreateApexDataContext();
protected bool AllowMove;

protected List Unlayedouts = 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)
{
List toRemove = 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(List list,int drillDownGroupId)
{
InitializeComponent();
RootFunds = list;
DrillDownGroupId = drillDownGroupId;
_context = ApexDal.Instance.CreateApexDataContext();
GetCustomGroupData();
}


#region CG data

IEnumerable cGroups;
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

Saturday, July 9, 2011

Drag Move UI Element inside a Canvas


private Point m_StartPoint;
private double m_OriginalLeft;
private double m_OriginalTop;
private Boolean m_IsDown;
private UIElement m_OriginalElement;
private Boolean m_IsDragging;

private void MyCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (MyCanvas == e.Source || !AllowMove) return;
m_IsDown = true;
m_StartPoint = e.GetPosition(MyCanvas);
m_OriginalElement = e.Source as UIElement;
MyCanvas.CaptureMouse();
e.Handled = true;
}

private void MyCanvas_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (m_IsDown)
{
if (!m_IsDragging && Math.Abs(e.GetPosition(MyCanvas).X - m_StartPoint.X) > SystemParameters.MinimumHorizontalDragDistance && Math.Abs(e.GetPosition(MyCanvas).Y - m_StartPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
{
DragStarted();
}
if (m_IsDragging)
{
DragMoved();
}
}
}


private void MyCanvas_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (m_IsDown)
{
DragFinished(false);
e.Handled = true;
}
}

private void DragFinished(bool p)
{
System.Windows.Input.Mouse.Capture(null);
m_IsDragging = false;
m_IsDown = false;
}
private void DragMoved()
{
Point currentPosition = System.Windows.Input.Mouse.GetPosition(MyCanvas);
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);
}

private void DragStarted()
{
m_IsDragging = true;
m_OriginalLeft = Canvas.GetLeft(m_OriginalElement);
m_OriginalTop = Canvas.GetTop(m_OriginalElement);

}

Tuesday, June 28, 2011

Parallel Data Fetching by F#



namespace JQD.Parallel
open System
open System.Collections.Generic
type DataFetcher() =
let f (hhr) =Reporting.HoldingMapper.MapHolding(hhr)
let f2 (ar:Reporting.Domain.Objects.GetHoldingsHierarchyResult[]) =
ar|> Array.Parallel.map (fun (g) -> Reporting.HoldingMapper.MapHolding(g))
|> Array.Parallel.map (fun h -> h.MarketValue )
|> Array.sum

member this.DA(ar:Reporting.Domain.Objects.GetHoldingsHierarchyResult[]) =
ar|> Array.Parallel.map (fun (g) -> Reporting.HoldingMapper.MapHolding(g))
|> Array.Parallel.map (fun h -> h.MarketValue )
|> Array.sum

member this.DA3(ar:DateTime[],groupId:int) =
ar|> Array.Parallel.map( fun i -> Seq.toArray(Reporting.Dal.GetHoldingsHierarchy(groupId,i,i)))
|> Array.Parallel.map(fun g -> f2(g))

Wednesday, June 15, 2011

WPF DataGrid Row/Cell Accessor


public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}

public static DataGridRow GetSelectedRow( DataGrid grid)
{
return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

public static DataGridRow GetRow( DataGrid grid, int index)
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// May be virtualized, bring into view and try again.
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}

public static DataGridCell GetCell( DataGrid grid, DataGridRow row, int column)
{
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild(row);

if (presenter == null)
{
grid.ScrollIntoView(row, grid.Columns[column]);
presenter = GetVisualChild<DataGridCellsPresenter>(row);
}

DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
return cell;
}
return null;
}

public static DataGridCell GetCell( DataGrid grid, int row, int column)
{
DataGridRow rowContainer = GetRow(grid,row);
return GetCell(grid,rowContainer, column);
}

Tuesday, June 14, 2011

F# Active Parttern to break down data



// break down into tuple
open System.Drawing
let (|RGB|) (col:System.Drawing.Color) = (col.R, col.G, col.B)
let (|HSB|) (col:System.Drawing.Color) = (col.GetHue(), col.GetSaturation(),col.GetBrightness())

//parsing
open System
let (|Int|_|)(x:string) =
let mutable y =0.0
if System.Double.TryParse(x, &y) then Some(x)
else None

let PrintRGB x =
match x with
| RGB (r,g,b) -> printfn"%d %d %d" r g b

let Parse x =
match x with
| Int t -> printfn "%A" t
| _ -> printfn "not integer"


Sunday, June 12, 2011

F# Discriminated Union as Option Type



type Options<'a> =
| Some of 'a
| None

let op1 = Some(10.0)
let op2 = None
let op3 = Options.Some("adf")

let ShowOption x =
match x with
| None ->printfn "%A" "Nothing"
| Some t ->printfn "%A" t

ShowOption op1
ShowOption op2
ShowOption op3

Saturday, June 11, 2011

F# Finding Prime Number



let IsNotMultipleOf n x =
x=n || x%n<>0

let rec RemoveAllMultiples listn listx =
match listn with
| head::tail -> RemoveAllMultiples tail (List.filter (IsNotMultipleOf head) listx)
| [] -> listx

let GetPrimeTo n =
let r= (int) ( sqrt(float n))
RemoveAllMultiples [2..r] [1..100]

printfn "%A" (GetPrimeTo 100)

Wednesday, June 8, 2011

F# Async Workflow


#light
open System.IO
open System.Net
open System

let AyncHttp(url:string) =
async {
let req=WebRequest.Create(url)
let! rsp=req.AsyncGetResponse()
use s= rsp.GetResponseStream()
use r= new System.IO.StreamReader(s)
r.ReadToEnd()
}

//let SyncHttp(url:string) =
// let req=WebRequest.Create(url)
// let rsp=req.GetResponse()
// use s= rsp.GetResponseStream()
// use r= new System.IO.StreamReader(s)
// r.ReadToEnd()



let dt=System.DateTime.Now

//SyncHttp "http://maps.google.com"
//SyncHttp "http://maps.live.com"
//SyncHttp("http://www.nhl.com");
//SyncHttp("http://www.nfl.com");
//SyncHttp("http://www.china.com");
//SyncHttp("http://www.sina.com");
//SyncHttp("http://www.nba.com");
//printf "%A" (DateTime.Now-dt).Milliseconds

Async.Parallel [
AyncHttp("http://maps.google.com");
AyncHttp("http://maps.live.com");
AyncHttp("http://www.nhl.com");
AyncHttp("http://www.nfl.com");
AyncHttp("http://www.china.com");
AyncHttp("http://www.sina.com");
AyncHttp("http://www.nba.com");
]
|> Async.RunSynchronously

printf "%A" (DateTime.Now-dt).Milliseconds

Thursday, May 26, 2011

TreeMap and Zoom Control onto TreeGraph (WPF Toolkit and Extension)


WPF ToolKit and CodePlex WPF Extension

<Window x:Class="GMO.Monitor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:dv="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:tc="clr-namespace:TreeContainer;assembly=TreeContainer"
xmlns:wpfec="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions"
x:Name="M"
>
<Grid >
<!--<WrapPanel>-->
<DockPanel>
<dv:TreeMap Name="tmp1" Height="Auto" Width="200" >
<dv:TreeMap.Interpolators>
<dv:SolidColorBrushInterpolator
TargetName="bdr"
TargetProperty="Background"
DataRangeBinding="{Binding Path=totalValue}"
From="Green"
To="White"/>
</dv:TreeMap.Interpolators>
<dv:TreeMap.ItemDefinition>
<dv:TreeMapItemDefinition
ItemsSource="{Binding}"
ValueBinding="{Binding Path=totalValue}"
>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="Black" Name="bdr" MouseDown="bdr_MouseDown" ToolTip="{Binding Path=ToolTip}" >
<TextBlock Text="{Binding Path=shortname}" VerticalAlignment="Center" Margin="2,2,0,0" FontSize="10" />
</Border>
</DataTemplate>
</dv:TreeMapItemDefinition>
</dv:TreeMap.ItemDefinition>
</dv:TreeMap>
<wpfec:ZoomControl >

<Grid Width="1000" Height="1000" Background="Beige">
<Canvas>
<tc:TreeContainer tc:TreeContainer.Root="O" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="tc1" HorizontalBuffer="38" VerticalBuffer="48" HorizontalBufferSubtree="40" VerticalJustification="top">

</tc:TreeContainer>
</Canvas>
</Grid>
</wpfec:ZoomControl>
</DockPanel>
<!--</WrapPanel>-->
</Grid>
</Window>


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 System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Controls.DataVisualization;
using GMO.Monitor.Model;
using TreeContainer;
using System.Collections.ObjectModel;

namespace GMO.Monitor
{
///
/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
ApexDevEntities ctx = new ApexDevEntities();
public MainWindow()
{
InitializeComponent();
var q = from t in ctx.GetDashboard() select new { t.shortname, t.totalValue, t.groupid, ToolTip = t.shortname + "," + t.groupid.ToString() };
tmp1.ItemsSource = q;
}

protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
//vb.Width = this.ActualWidth - tmp1.ActualWidth; ;
//vb.Height = this.ActualHeight - tmp1.ActualHeight;
base.OnRenderSizeChanged(sizeInfo);
}

private void bdr_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount <= 1) return;

Border bdr = sender as Border;
string tip = bdr.ToolTip.ToString();
int GrpId = Convert.ToInt32(tip.Split(',')[1]);
TextBlock tb = bdr.Child as TextBlock;
tc1.Clear();
TreeNode root= tc1.AddRoot(tb.Text);
var q = from t in ctx.CustomGroups where t.RelatedGroupId == GrpId select t;
foreach (var q1 in q)
{
TextBlock tb1 = new TextBlock() { Text = q1.CustomGroupName};
TreeNode tn= tc1.AddNode(tb1, root);
tn.Tag = q.FirstOrDefault();
// tn.MouseDoubleClick += new MouseButtonEventHandler(tn_MouseDoubleClick);
// TreeNode tn = sender as TreeNode;
DateTime dt = new DateTime(2011, 2, 1);
string subCGstr = "a,0,b,1,c,2";
var q2 = from t in ctx.GetCustomGroupExposures(dt, q1.CustomGroupId, true, subCGstr) select t;
foreach (var q3 in q2)
{
TextBlock tb3 = new TextBlock() { Text = q3.Bet + "\r\n " + q3.Exposure.ToString() + "\r\n " + q3.PercentExposure.ToString() };
TreeNode tn1 = tc1.AddNode(tb3, tn);
}
}
}

void tn_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
tc1.Clear();
TreeNode tn = sender as TreeNode;
CustomGroup cg = tn.Tag as CustomGroup;
TextBlock tb= new TextBlock() { Text= cg.CustomGroupName};
TreeNode root = tc1.AddRoot(tb);
DateTime dt = new DateTime(2011,2,1);
var q = from t in ctx.GetCustomGroupExposures(dt, cg.CustomGroupId, true, "") select t;
foreach (var q1 in q)
{
TextBlock tb1 = new TextBlock() { Text = q1.Bet+" "+q1.Exposure.ToString() +" "+q1.PercentExposure.ToString() };
TreeNode tn1 = tc1.AddNode(tb1, root);
}
}
}

public class Data1
{
public string shortname { get; set; }
public double totalValue { get; set; }
}
}

Saturday, April 23, 2011

Generating C# code from Shader File (WIP)

Shazzam tools generate C# code

Sunday, April 17, 2011

Data Visualization



1. Quiet Status on Dashboard should have non-alerting color

2. Single Number should be communicated with alerting color, Icon graphic ( tiny, "SparkCon ???")

3. Large data set are good for Line Chart Period Analysis. Small data set mush rely on Bar Chart.

4. Period comparison should not use line chart overlay. Comparison= Delta of %

5. How to Breakdown a variable:
Human are good in visualizing Height no area plot, unit plot, Pie chart ( need to calculate area, counting, pizza size w/o number). Sorted Bar chart are better.

6.Breakdown over a period of time:
Bar chart side by side comparison with different color will show difference and trend
Stack line or bar are not clear.

7. How to visuaize Category:
Map, Shapes, Color, Lines

8. How to visualize Quantity:
Size, Count, Speed, Color Intensity, Height Comparison.

9. Typical usage: Cluster Point Chart, Bar with Median, Mean, Sorting, Markup Chain Workflow Graph. Highlighting GridCell, Projectin, Targeting

10. Other techniques: Click-through, Grouping, Multi-factor, Summary and Rating, Confidence Level to filter out outliers

Wednesday, March 30, 2011

App Fabric Caching Client Code



PorfolioExplorer.cs :: public void LoadDataFromRootFundComboBox()
{
...
LoadData(SelectedGroup);


cacheCluster = new DataCacheServerEndpoint[1];
cacheCluster[0] = new DataCacheServerEndpoint(
"jqdappfabric",
// "10.32.68.131",
22233);

DataCacheFactoryConfiguration cfg = new DataCacheFactoryConfiguration();
cfg.Servers = cacheCluster;
DataCacheFactory factory = new DataCacheFactory(cfg);
cache = factory.GetDefaultCache();
try
{
if (EventEngine.Instance.CurrentHoldingComposite != null)
cache.Put("CurrentHoldingComposite", EventEngine.Instance.CurrentHoldingComposite, new TimeSpan(240, 0, 0));
if (EventEngine.Instance.RootFund != null)
cache.Put("RootFund", EventEngine.Instance.RootFund, new TimeSpan(240, 0, 0));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

DataCacheFactory factory;
DataCache cache;
DataCacheServerEndpoint[] cacheCluster;

AppConfig
=========

<configSections>
<!-- required to read the <dataCacheClient> element -->
<section name="dataCacheClient" type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere"/>

<dataCacheClient>
<transportProperties maxBufferPoolSize="7" maxBufferSize="2000000000"/>


<!-- (optional) specify local cache
<localCache
isEnabled="true"
sync="TimeoutBased"
objectCount="100000"
ttlValue="300" /> -->

<!--(optional) specify cache notifications poll interval
<clientNotification pollInterval="300" /> -->

<hosts>
<host name="jqdappfabric" cachePort="22233"/>
<!-- name="CacheServer2"
cachePort="22233"/>-->
</hosts>
</dataCacheClient>

Note that there are 2 DLL from server that can be used on XP ( only suppoed to installed to Win7 but it works
Microsoft.ApplicationServer.Caching.Client.dll
Microsoft.ApplicationServer.Caching.Core.dll

The other two may be useful:
Microsoft.WindowsFabric.Common.dll
Microsoft.WindowsFabric.Data.Common.dll



Friday, February 25, 2011

WPF 300DPI High Resoluation Printing



PrintDialog dlg = new PrintDialog();
GeneralTransform transformToRoot = this.TransformToAncestor(win_root);

Rect rect = new Rect(transformToRoot.Transform(new Point(0, 0)), transformToRoot.Transform(new Point(this.ActualWidth, this.ActualHeight)));

double scale = 300 / 96;

RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(scale * (rect.Width + 1)), (int)(scale * (rect.Height + 1)), scale * 96, scale * 96, PixelFormats.Default);
bitmap.Render(g); // g=grid

Image img = new Image();
img.Source = bitmap;
img.Stretch = Stretch.None;

img.Measure(new Size(dlg.PrintableAreaWidth,
dlg.PrintableAreaHeight));
Size sizeImage = img.DesiredSize;
img.Arrange(new Rect(new Point(0, 0), sizeImage));

dlg.PrintVisual(img, "Test300DPI");

For 3D:

Rect = Viewport3DVisual.ViewPort and it comes from visual brush:

<Border>
<Border.Background>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<Viewport3DVisual x:Name="visual3d" Viewport="0 0 384 384">


Saturday, February 19, 2011

Create OData Producer


(1) Create a Web App and add .mdf file to App Data Folder
(2) Add EF edmx and drag drop the .mdf's table (SQL Express)
(3) Add new item Web ->WCF Data Service (Will generate Atom Data Feed Service)

(4)
public class WcfDataService1 : DataService<AdventureWorks_DataEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Products", EntitySetRights.AllRead);
config.SetEntitySetPageSize("Products", 2);
.. }

[QueryInterceptor("Products")]
public Expression<Func<Product,bool>> OnQueryCustomer()
{
return p => p.Name.Contains("Adjustable");
}
(5) Test in browser http://localhost/WcfDataService1/Products?$select=Name
...?$top=5
Feed Reader can be turned off Tool->Internet option->content->..

(6) Also test using Silverlight Client
...
AdventureWorks_DataEntities _svs;
DataServiceCollection<Product> _products;
public MainPage()
{
InitializeComponent();

_products.LoadCompleted += new EventHandler(_products_LoadCompleted);

Tuesday, February 15, 2011

WCF NamedPipeBinding in AppFabric



(1) Create anApp under default site running ASP.Net 4.0 AppPool
( net.pipe cannot have port number)
(2) Setting Binding for defulat site and App Advanced Setting to Enable net.pipe protocol

(3)Create a WCP Lib project by VS.net 2010 and publish into the App
(if svc file are missing, manually add one. It should be there if protocol include wsHttp*)
(4) VS.net 2001 ->Tool->WCF Config editor to edit App Web Config and add net.pipe endpoint and mexnetpipe endpoint. Note that Address for net.pipe can be empty but must set up mex for net.pipe.
(5) IIS Manager -> Manage WCF -> Config --> auto-start enabled

(6) svcutil net.pipe://localhost/TestNP/WcfServiceLibrary6.Service1.svc

(7) Client Code:
Service1Client c = new Service1Client("NetNamedPipeBinding_IService1");
c.Open();
string s= c.GetData(123));
c.Close();


<endpoint binding="netNamedPipeBinding" contract="WcfServiceLibrary6.IService1" />
<endpoint address="mex" binding="mexNamedPipeBinding" bindingConfiguration="" contract="IMetadataExchange" />
Note: binding config is optional
<bindings>
<netNamedPipeBinding>
<binding name="binding1">
<security mode="None" />
</binding>
</netNamedPipeBinding>
</bindings>

Thursday, February 3, 2011

Screen Shot into Clipboard


Bitmap ScreenShot;
int w = (int)aGrid.ActualWidth;
int h = (int)aGrid.ActualHeight;
int x = (int)aGrid.PointToScreen(new System.Windows.Point(0, 0)).X;
int y = (int)aGrid.PointToScreen(new System.Windows.Point(0, 0)).Y;
ScreenShot = new Bitmap(w, h);
Graphics g = Graphics.FromImage(ScreenShot);
g.CopyFromScreen(x, y, 0, 0, new System.Drawing.Size(w, h));
g.Dispose();

System.Windows.Forms.Clipboard.SetImage(ScreenShot);



Thursday, January 20, 2011

Command Utility to merge and Page Number PDF

Download:
(1) pdftk and winpdftextstamp 32 or 64 bit
(2) pdftk 1.pdf 2.pdf 3.pdf output file.pdf
(2) windpdftextstamp -ifile.pdf -ofile_n.pdf

Install PDFCreator as NT Service using SC command



(1) Add PDFCreator to the exception list DEP
Control Panel => System => Advanced system settings =>Advanced => Data Execution Prevention.

(2) Ge srvany.exe from the Windows Server 2003 Resource Kit (There are no Windows 2008 Server Resource Kit as of today)

(3) create the service with the sc command:

sc create pdfcreator start= auto binPath= "C:\Program Files\oldResourceKitTools\srvany.exe" DisplayName= "PDFCreator" obj= DOMAIN\User password= password
(Note that there is one space after Equal Sign)

(4) sc query pdfcreator

(5) Reg editing as in KB137890 :

1. Regedt32.exe locate
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\pdfcreator
2.Add Key.
Key Name: Parameters
Class :<leave blank>
3.Select the Parameters key, Add Value.
Value Name: Application
Data Type : REG_SZsc start
String : <path>\<application.ext>

where <path>\<application.ext> is the drive and full path to the application executable including the extension (i.e., C:\PDFCreator\pdfcreator.exe)


Monday, January 17, 2011

Set up ghostscript PDL to convert xps to PDF



For 32 Bit:
Download binary e.g. ghostpdl-8.71-win32.zip http://www.ghostscript.com/releases/
unzip and find gswin32
command gxps-871.exe -sDEVICE=pdfwrite -sOutputFile=33.pdf -dNOPAUSE tiger.xps

For 64 Bit

download ghostpdl-9.00.tar.gz and get all the source
use VC++ nmake xps_msvc.mak to complike gxps.exe ( from 64 bit sdk prompt)
gxps -sDEVICE=pdfwrite -sOutputFile=77.pdf -sNOPAUSE tigger.xsp

CutePDF is a printer that convert any doc to PDF and can be programed in C#
(PopUp Dialog to save file). It uses ghostscript.
http://www.cutepdf.com/products/cutepdf/writer.asp

Walk WPF visual Tree and Logical Tree



public static List<T> GetChildren<T>(Visual parent) where T : Visual
{
List<T> childrenT = new List<T>();
int numOfChildren = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numOfChildren;i++ )
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
if ((v as T) == null)
{
childrenT.AddRange(GetChildren<T>(v));
}
else childrenT.Add(v as T);
}
return childrenT;
}

public MainWindow() { InitializeComponent(); WalkVisualTree(g); WalkLogicalTree(g); } List<DependencyObject> listV = new List<DependencyObject>(); void WalkVisualTree(DependencyObject dobj) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dobj); i++) { DependencyObject dobj2=VisualTreeHelper.GetChild(dobj, i); listV.Add(dobj2); WalkVisualTree(dobj2); } } List<FrameworkElement> listL = new List<FrameworkElement>(); void WalkLogicalTree(FrameworkElement dobj) { if (dobj == null) return; foreach ( var c in LogicalTreeHelper.GetChildren(dobj)) { listL.Add(c as FrameworkElement); WalkLogicalTree(c as FrameworkElement); } } }