Print Preview Popup as FixedDocument
(1) PageContent will has Compiler Error but can stil render with FixedPage---Known Defect of WPF.
(2) Fixed document will has toolbar shown by WPF, no coded needed. So this is simplest printing
<Window x:Class="TestWPFPrinting.PrintPreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PrintPreview" Height="300" Width="300">
<FixedDocument Name="customerReport">
<PageContent>
<FixedPage>
<Label FontSize="20" Margin="100,20,0,0">REPORT</Label>
<ListView BorderThickness="0" Margin="50,100,0,0" FontSize="14" Width="Auto" Height="Auto" ItemsSource="{Binding}">
<ListView.View>
<GridView x:Name="gridReport">
<GridViewColumn Width="200" Header="FirstName" DisplayMemberBinding="{Binding Path=FirstName}">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="200" Header="LastName" DisplayMemberBinding="{Binding Path=LastName}">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</FixedPage>
</PageContent>
</FixedDocument>
</Window>
Bind to Data
public partial class PrintPreview : Window
{
private List<Customer> _customers;
public PrintPreview(List<Customer> customers)
{
InitializeComponent();
_customers = customers;
// generate report
this.DataContext = _customers;
}
}
public class Customer
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
Main Form
private void button1_Click(object sender, RoutedEventArgs e)
{
List<Customer> customers = new List<Customer>();
for (int i = 1; i <= 200; i++)
{
Customer customer = new Customer();
customer.FirstName = "FirstName " + i;
customer.LastName = "LastName " + i;
customers.Add(customer);
}
PrintPreview w = new PrintPreview(customers);
w.Show();
Sunday, January 29, 2012
WPF Printing using FixedDcoument
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;
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
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";
}
Subscribe to:
Posts (Atom)